text
stringlengths
54
60.6k
<commit_before>// Code partially copyright Edd Dawson 2007 // // Boost Software License - Version 1.0 - August 17th, 2003 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "libmesh/libmesh_config.h" #include "libmesh/print_trace.h" #include "libmesh/libmesh.h" #include <unistd.h> // needed for getpid() #include <fstream> #include <sstream> #if defined(LIBMESH_HAVE_GCC_ABI_DEMANGLE) && defined(LIBMESH_HAVE_GLIBC_BACKTRACE) #include <iostream> #include <string> #include <execinfo.h> #include <cxxabi.h> #include <cstdlib> namespace libMesh { std::string process_trace(const char *name) { std::string fullname = name; std::string saved_begin, saved_end; size_t namestart, nameend; /** * The Apple backtrace function returns more information than the Linux version. * We need to pass only the function name to the demangler or it won't decode it for us. * * lineno: stackframeno address functionname + offset */ #ifdef __APPLE__ namestart = fullname.find("0x"); if (namestart != std::string::npos) { namestart = fullname.find(' ', namestart) + 1; saved_begin = fullname.substr(0, namestart); } else namestart = 0; nameend = fullname.find('+'); if (nameend == std::string::npos || nameend <= namestart) nameend = fullname.size(); else { nameend -= 1; saved_end = fullname.substr(nameend, fullname.length()); } #else namestart = fullname.find('('); if (namestart == std::string::npos) return fullname; else namestart++; nameend = fullname.find('+'); if (nameend == std::string::npos || nameend <= namestart) return fullname; #endif std::string type_name = fullname.substr(namestart, nameend - namestart); // Try to demangle now return saved_begin + demangle(type_name.c_str()) + saved_end; } std::string demangle(const char *name) { int status = 0; char *d = 0; std::string ret = name; try { if ( (d = abi::__cxa_demangle(name, 0, 0, &status)) ) ret = d; } catch(...) { } std::free(d); return ret; } void print_trace(std::ostream &out_stream) { void *addresses[40]; char **strings; int size = backtrace(addresses, 40); strings = backtrace_symbols(addresses, size); out_stream << "Stack frames: " << size << std::endl; for(int i = 0; i < size; i++) out_stream << i << ": " << process_trace(strings[i]) << std::endl; std::free(strings); } } // namespace libMesh #else namespace libMesh { void print_trace(std::ostream &) {} std::string demangle(const char *name) { return std::string(name); } } #endif namespace libMesh { void write_traceout() { #ifdef LIBMESH_ENABLE_TRACEFILES std::stringstream outname; outname << "traceout_" << static_cast<std::size_t>(libMesh::global_processor_id()) << '_' << getpid() << ".txt"; std::ofstream traceout(outname.str().c_str(), std::ofstream::app); libMesh::print_trace(traceout); #endif } } <commit_msg>abi::__cxa_demangle is a C-compilable function, therefore doesn't throw.<commit_after>// Code partially copyright Edd Dawson 2007 // // Boost Software License - Version 1.0 - August 17th, 2003 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "libmesh/libmesh_config.h" #include "libmesh/print_trace.h" #include "libmesh/libmesh.h" #include <unistd.h> // needed for getpid() #include <fstream> #include <sstream> #if defined(LIBMESH_HAVE_GCC_ABI_DEMANGLE) && defined(LIBMESH_HAVE_GLIBC_BACKTRACE) #include <iostream> #include <string> #include <execinfo.h> #include <cxxabi.h> #include <cstdlib> namespace libMesh { std::string process_trace(const char *name) { std::string fullname = name; std::string saved_begin, saved_end; size_t namestart, nameend; /** * The Apple backtrace function returns more information than the Linux version. * We need to pass only the function name to the demangler or it won't decode it for us. * * lineno: stackframeno address functionname + offset */ #ifdef __APPLE__ namestart = fullname.find("0x"); if (namestart != std::string::npos) { namestart = fullname.find(' ', namestart) + 1; saved_begin = fullname.substr(0, namestart); } else namestart = 0; nameend = fullname.find('+'); if (nameend == std::string::npos || nameend <= namestart) nameend = fullname.size(); else { nameend -= 1; saved_end = fullname.substr(nameend, fullname.length()); } #else namestart = fullname.find('('); if (namestart == std::string::npos) return fullname; else namestart++; nameend = fullname.find('+'); if (nameend == std::string::npos || nameend <= namestart) return fullname; #endif std::string type_name = fullname.substr(namestart, nameend - namestart); // Try to demangle now return saved_begin + demangle(type_name.c_str()) + saved_end; } std::string demangle(const char *name) { int status = 0; std::string ret = name; // Actually do the demangling char *demangled_name = abi::__cxa_demangle(name, 0, 0, &status); // If demangling returns non-NULL, save the result in a string. if (demangled_name) ret = demangled_name; // According to cxxabi.h docs, the caller is responsible for // deallocating memory. std::free(demangled_name); return ret; } void print_trace(std::ostream &out_stream) { void *addresses[40]; char **strings; int size = backtrace(addresses, 40); strings = backtrace_symbols(addresses, size); out_stream << "Stack frames: " << size << std::endl; for(int i = 0; i < size; i++) out_stream << i << ": " << process_trace(strings[i]) << std::endl; std::free(strings); } } // namespace libMesh #else namespace libMesh { void print_trace(std::ostream &) {} std::string demangle(const char *name) { return std::string(name); } } #endif namespace libMesh { void write_traceout() { #ifdef LIBMESH_ENABLE_TRACEFILES std::stringstream outname; outname << "traceout_" << static_cast<std::size_t>(libMesh::global_processor_id()) << '_' << getpid() << ".txt"; std::ofstream traceout(outname.str().c_str(), std::ofstream::app); libMesh::print_trace(traceout); #endif } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CustomAnimationDialog.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 03:34:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SD_CUSTOMANIMATIONDIALOG_HXX #define _SD_CUSTOMANIMATIONDIALOG_HXX #ifndef _SD_CUSTOMANIMATIONEFFECT_HXX #include "CustomAnimationEffect.hxx" #endif #ifndef _SD_CUSTOMANIMATIONPRESET_HXX #include "CustomAnimationPreset.hxx" #endif #ifndef _SV_TABDLG_HXX #include <vcl/tabdlg.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif class TabControl; class OKButton; class CancelButton; class HelpButton; namespace sd { // -------------------------------------------------------------------- // property handles const sal_Int32 nHandleSound = 0; const sal_Int32 nHandleHasAfterEffect = 1; const sal_Int32 nHandleIterateType = 2; const sal_Int32 nHandleIterateInterval = 3; const sal_Int32 nHandleStart = 4; const sal_Int32 nHandleBegin = 5; const sal_Int32 nHandleDuration = 6; const sal_Int32 nHandleRepeat = 7; const sal_Int32 nHandleRewind = 8; const sal_Int32 nHandleEnd = 9; const sal_Int32 nHandleMasterRel = 10; const sal_Int32 nHandleDimColor = 11; const sal_Int32 nHandleMaxParaDepth = 12; const sal_Int32 nHandlePresetId = 13; const sal_Int32 nHandleProperty1Type = 14; const sal_Int32 nHandleProperty1Value = 15; const sal_Int32 nHandleProperty2Type = 16; const sal_Int32 nHandleProperty2Value = 17; const sal_Int32 nHandleAccelerate = 18; const sal_Int32 nHandleDecelerate = 19; const sal_Int32 nHandleAutoReverse = 20; const sal_Int32 nHandleTrigger = 21; const sal_Int32 nHandleHasText = 22; const sal_Int32 nHandleTextGrouping = 23; const sal_Int32 nHandleAnimateForm = 24; const sal_Int32 nHandleTextGroupingAuto = 25; const sal_Int32 nHandleTextReverse = 26; const sal_Int32 nHandleCurrentPage = 27; const sal_Int32 nHandleSoundURL = 28; const sal_Int32 nHandleSoundVolumne = 29; const sal_Int32 nHandleSoundEndAfterSlide = 30; const sal_Int32 nHandleCommand = 31; const sal_Int32 nPropertyTypeNone = 0; const sal_Int32 nPropertyTypeDirection = 1; const sal_Int32 nPropertyTypeSpokes = 2; const sal_Int32 nPropertyTypeFirstColor = 3; const sal_Int32 nPropertyTypeSecondColor = 4; const sal_Int32 nPropertyTypeZoom = 5; const sal_Int32 nPropertyTypeFillColor = 6; const sal_Int32 nPropertyTypeColorStyle = 7; const sal_Int32 nPropertyTypeFont = 8; const sal_Int32 nPropertyTypeCharHeight = 9; const sal_Int32 nPropertyTypeCharColor = 10; const sal_Int32 nPropertyTypeCharHeightStyle = 11; const sal_Int32 nPropertyTypeCharDecoration = 12; const sal_Int32 nPropertyTypeLineColor = 13; const sal_Int32 nPropertyTypeRotate = 14; const sal_Int32 nPropertyTypeColor = 15; const sal_Int32 nPropertyTypeAccelerate = 16; const sal_Int32 nPropertyTypeDecelerate = 17; const sal_Int32 nPropertyTypeAutoReverse = 18; const sal_Int32 nPropertyTypeTransparency = 19; const sal_Int32 nPropertyTypeFontStyle = 20; const sal_Int32 nPropertyTypeScale = 21; // -------------------------------------------------------------------- class PropertySubControl { public: virtual ~PropertySubControl(); virtual ::com::sun::star::uno::Any getValue() = 0; virtual Control* getControl() = 0; static PropertySubControl* create( sal_Int32 nType, ::Window* pParent, const ::com::sun::star::uno::Any& rValue, const rtl::OUString& rPresetId, const Link& rModifyHdl ); }; // -------------------------------------------------------------------- class PropertyControl : public ListBox { public: PropertyControl( Window* pParent, const ResId& rResId ); ~PropertyControl(); void setSubControl( PropertySubControl* pSubControl ); PropertySubControl* getSubControl() const { return mpSubControl; } virtual void Resize(); private: PropertySubControl* mpSubControl; }; // -------------------------------------------------------------------- class CustomAnimationDurationTabPage; class CustomAnimationEffectTabPage; class CustomAnimationTextAnimTabPage; class STLPropertySet; class CustomAnimationDialog : public TabDialog { public: CustomAnimationDialog( Window* pParent, STLPropertySet* pSet, USHORT nPage = 0 ); ~CustomAnimationDialog(); STLPropertySet* getDefaultSet() { return mpSet; } STLPropertySet* getResultSet(); static STLPropertySet* createDefaultSet(); private: STLPropertySet* mpSet; STLPropertySet* mpResultSet; CustomAnimationEffectPtr mpEffect; TabControl* mpTabControl; OKButton* mpOKButton; CancelButton* mpCancelButton; HelpButton* mpHelpButton; CustomAnimationDurationTabPage* mpDurationTabPage; CustomAnimationEffectTabPage* mpEffectTabPage; CustomAnimationTextAnimTabPage* mpTextAnimTabPage; }; }; #endif // _SD_CUSTOMANIMATIONDIALOG_HXX <commit_msg>INTEGRATION: CWS impress49 (1.2.172); FILE MERGED 2005/06/10 15:51:40 cl 1.2.172.1: #i41546# reworked after effects<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CustomAnimationDialog.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2005-09-23 10:45:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SD_CUSTOMANIMATIONDIALOG_HXX #define _SD_CUSTOMANIMATIONDIALOG_HXX #ifndef _SD_CUSTOMANIMATIONEFFECT_HXX #include "CustomAnimationEffect.hxx" #endif #ifndef _SD_CUSTOMANIMATIONPRESET_HXX #include "CustomAnimationPreset.hxx" #endif #ifndef _SV_TABDLG_HXX #include <vcl/tabdlg.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif class TabControl; class OKButton; class CancelButton; class HelpButton; namespace sd { // -------------------------------------------------------------------- // property handles const sal_Int32 nHandleSound = 0; const sal_Int32 nHandleHasAfterEffect = 1; const sal_Int32 nHandleIterateType = 2; const sal_Int32 nHandleIterateInterval = 3; const sal_Int32 nHandleStart = 4; const sal_Int32 nHandleBegin = 5; const sal_Int32 nHandleDuration = 6; const sal_Int32 nHandleRepeat = 7; const sal_Int32 nHandleRewind = 8; const sal_Int32 nHandleEnd = 9; const sal_Int32 nHandleAfterEffectOnNextEffect = 10; const sal_Int32 nHandleDimColor = 11; const sal_Int32 nHandleMaxParaDepth = 12; const sal_Int32 nHandlePresetId = 13; const sal_Int32 nHandleProperty1Type = 14; const sal_Int32 nHandleProperty1Value = 15; const sal_Int32 nHandleProperty2Type = 16; const sal_Int32 nHandleProperty2Value = 17; const sal_Int32 nHandleAccelerate = 18; const sal_Int32 nHandleDecelerate = 19; const sal_Int32 nHandleAutoReverse = 20; const sal_Int32 nHandleTrigger = 21; const sal_Int32 nHandleHasText = 22; const sal_Int32 nHandleTextGrouping = 23; const sal_Int32 nHandleAnimateForm = 24; const sal_Int32 nHandleTextGroupingAuto = 25; const sal_Int32 nHandleTextReverse = 26; const sal_Int32 nHandleCurrentPage = 27; const sal_Int32 nHandleSoundURL = 28; const sal_Int32 nHandleSoundVolumne = 29; const sal_Int32 nHandleSoundEndAfterSlide = 30; const sal_Int32 nHandleCommand = 31; const sal_Int32 nPropertyTypeNone = 0; const sal_Int32 nPropertyTypeDirection = 1; const sal_Int32 nPropertyTypeSpokes = 2; const sal_Int32 nPropertyTypeFirstColor = 3; const sal_Int32 nPropertyTypeSecondColor = 4; const sal_Int32 nPropertyTypeZoom = 5; const sal_Int32 nPropertyTypeFillColor = 6; const sal_Int32 nPropertyTypeColorStyle = 7; const sal_Int32 nPropertyTypeFont = 8; const sal_Int32 nPropertyTypeCharHeight = 9; const sal_Int32 nPropertyTypeCharColor = 10; const sal_Int32 nPropertyTypeCharHeightStyle = 11; const sal_Int32 nPropertyTypeCharDecoration = 12; const sal_Int32 nPropertyTypeLineColor = 13; const sal_Int32 nPropertyTypeRotate = 14; const sal_Int32 nPropertyTypeColor = 15; const sal_Int32 nPropertyTypeAccelerate = 16; const sal_Int32 nPropertyTypeDecelerate = 17; const sal_Int32 nPropertyTypeAutoReverse = 18; const sal_Int32 nPropertyTypeTransparency = 19; const sal_Int32 nPropertyTypeFontStyle = 20; const sal_Int32 nPropertyTypeScale = 21; // -------------------------------------------------------------------- class PropertySubControl { public: virtual ~PropertySubControl(); virtual ::com::sun::star::uno::Any getValue() = 0; virtual Control* getControl() = 0; static PropertySubControl* create( sal_Int32 nType, ::Window* pParent, const ::com::sun::star::uno::Any& rValue, const rtl::OUString& rPresetId, const Link& rModifyHdl ); }; // -------------------------------------------------------------------- class PropertyControl : public ListBox { public: PropertyControl( Window* pParent, const ResId& rResId ); ~PropertyControl(); void setSubControl( PropertySubControl* pSubControl ); PropertySubControl* getSubControl() const { return mpSubControl; } virtual void Resize(); private: PropertySubControl* mpSubControl; }; // -------------------------------------------------------------------- class CustomAnimationDurationTabPage; class CustomAnimationEffectTabPage; class CustomAnimationTextAnimTabPage; class STLPropertySet; class CustomAnimationDialog : public TabDialog { public: CustomAnimationDialog( Window* pParent, STLPropertySet* pSet, USHORT nPage = 0 ); ~CustomAnimationDialog(); STLPropertySet* getDefaultSet() { return mpSet; } STLPropertySet* getResultSet(); static STLPropertySet* createDefaultSet(); private: STLPropertySet* mpSet; STLPropertySet* mpResultSet; CustomAnimationEffectPtr mpEffect; TabControl* mpTabControl; OKButton* mpOKButton; CancelButton* mpCancelButton; HelpButton* mpHelpButton; CustomAnimationDurationTabPage* mpDurationTabPage; CustomAnimationEffectTabPage* mpEffectTabPage; CustomAnimationTextAnimTabPage* mpTextAnimTabPage; }; }; #endif // _SD_CUSTOMANIMATIONDIALOG_HXX <|endoftext|>
<commit_before>#ifndef __PROCESS_PROTOBUF_HPP__ #define __PROCESS_PROTOBUF_HPP__ #include <glog/logging.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <vector> #include <tr1/unordered_map> #include <process/process.hpp> // Provides a "protocol buffer process", which is to say a subclass of // Process that allows you to install protocol buffer handlers in // addition to normal message and HTTP handlers. Then you can simply // send around protocol buffer objects which will get passed to the // appropriate handlers. namespace google { namespace protobuf { // Type conversions helpful for changing between protocol buffer types // and standard C++ types (for parameters). template <typename T> const T& convert(const T& t) { return t; } template <typename T> std::vector<T> convert(const google::protobuf::RepeatedPtrField<T>& items) { std::vector<T> result; for (int i = 0; i < items.size(); i++) { result.push_back(items.Get(i)); } return result; } }} // namespace google { namespace protobuf { template <typename T> class ProtobufProcess : public process::Process<T> { public: ProtobufProcess(const std::string& id = "") : process::Process<T>(id) {} virtual ~ProtobufProcess() {} protected: virtual void operator () () { // TODO(benh): Shouldn't we just make Process::serve be a virtual // function, and then the one we get from process::Process will be // sufficient? do { if (serve() == process::TERMINATE) break; } while (true); } void send(const process::UPID& to, const google::protobuf::Message& message) { std::string data; message.SerializeToString(&data); process::Process<T>::send(to, message.GetTypeName(), data.data(), data.size()); } using process::Process<T>::send; const std::string& serve(double secs = 0, bool once = false) { do { const std::string& name = process::Process<T>::serve(secs, once); if (protobufHandlers.count(name) > 0) { protobufHandlers[name](process::Process<T>::body()); } else { return name; } } while (!once); } template <typename M> void installProtobufHandler(void (T::*method)()) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&ProtobufProcess<T>::handler0, t, method, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C> void installProtobufHandler(void (T::*method)(P1C), P1 (M::*param1)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler1<M, P1, P1C>, t, method, param1, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C> void installProtobufHandler(void (T::*method)(P1C, P2C), P1 (M::*p1)() const, P2 (M::*p2)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler2<M, P1, P1C, P2, P2C>, t, method, p1, p2, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C> void installProtobufHandler(void (T::*method)(P1C, P2C, P3C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler3<M, P1, P1C, P2, P2C, P3, P3C>, t, method, p1, p2, p3, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C> void installProtobufHandler(void (T::*method)(P1C, P2C, P3C, P4C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler4<M, P1, P1C, P2, P2C, P3, P3C, P4, P4C>, t, method, p1, p2, p3, p4, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C, typename P5, typename P5C> void installProtobufHandler(void (T::*method)(P1C, P2C, P3C, P4C, P5C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const, P5 (M::*p5)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler5<M, P1, P1C, P2, P2C, P3, P3C, P4, P4C, P5, P5C>, t, method, p1, p2, p3, p4, p5, std::tr1::placeholders::_1); delete m; } private: static void handler0(T* t, void (T::*method)(), const std::string& data) { (t->*method)(); } template <typename M, typename P1, typename P1C> static void handler1(T* t, void (T::*method)(P1C), P1 (M::*p1)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C> static void handler2(T* t, void (T::*method)(P1C, P2C), P1 (M::*p1)() const, P2 (M::*p2)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C> static void handler3(T* t, void (T::*method)(P1C, P2C, P3C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)()), google::protobuf::convert((&m->*p3)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C> static void handler4(T* t, void (T::*method)(P1C, P2C, P3C, P4C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)()), google::protobuf::convert((&m->*p3)()), google::protobuf::convert((&m->*p4)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C, typename P5, typename P5C> static void handler5(T* t, void (T::*method)(P1C, P2C, P3C, P4C, P5C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const, P5 (M::*p5)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)()), google::protobuf::convert((&m->*p3)()), google::protobuf::convert((&m->*p4)()), google::protobuf::convert((&m->*p5)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } typedef std::tr1::function<void(const std::string&)> handler; std::tr1::unordered_map<std::string, handler> protobufHandlers; }; namespace process { inline void post(const process::UPID& to, const google::protobuf::Message& message) { std::string data; message.SerializeToString(&data); post(to, message.GetTypeName(), data.data(), data.size()); } // template <typename Request, typename Response> // class RequestResponseProcess // : public ProtobufProcess<RequestResponseProcess<Request, Response> > // { // public: // RequestResponseProcess( // const UPID& _pid, // const Request& _request, // const Promise<Response>& _promise) // : pid(_pid), request(_request), promise(_promise) {} // protected: // virtual void operator () () // { // send(pid, request); // ProcessBase::receive(); // Response response; // CHECK(ProcessBase::name() == response.GetTypeName()); // response.ParseFromString(ProcessBase::body()); // promise.set(response); // } // private: // const UPID pid; // const Request request; // Promise<Response> promise; // }; // template <typename Request, typename Response> // struct Protocol // { // Future<Response> operator () (const UPID& pid, const Request& request) // { // Future<Response> future; // Promise<Response> promise; // promise.associate(future); // RequestResponseProcess<Request, Response>* process = // new RequestResponseProcess<Request, Response>(pid, request, promise); // spawn(process, true); // return future; // } // }; } // namespace process { #endif // __PROCESS_PROTOBUF_HPP__ <commit_msg>Updated a comment.<commit_after>#ifndef __PROCESS_PROTOBUF_HPP__ #define __PROCESS_PROTOBUF_HPP__ #include <glog/logging.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <vector> #include <tr1/unordered_map> #include <process/process.hpp> // Provides a "protocol buffer process", which is to say a subclass of // Process that allows you to install protocol buffer handlers in // addition to normal message and HTTP handlers. Then you can simply // send around protocol buffer objects which will get passed to the // appropriate handlers. Note that this header file assumes you will // be linking against BOTH libprotobuf and libglog. namespace google { namespace protobuf { // Type conversions helpful for changing between protocol buffer types // and standard C++ types (for parameters). template <typename T> const T& convert(const T& t) { return t; } template <typename T> std::vector<T> convert(const google::protobuf::RepeatedPtrField<T>& items) { std::vector<T> result; for (int i = 0; i < items.size(); i++) { result.push_back(items.Get(i)); } return result; } }} // namespace google { namespace protobuf { template <typename T> class ProtobufProcess : public process::Process<T> { public: ProtobufProcess(const std::string& id = "") : process::Process<T>(id) {} virtual ~ProtobufProcess() {} protected: virtual void operator () () { // TODO(benh): Shouldn't we just make Process::serve be a virtual // function, and then the one we get from process::Process will be // sufficient? do { if (serve() == process::TERMINATE) break; } while (true); } void send(const process::UPID& to, const google::protobuf::Message& message) { std::string data; message.SerializeToString(&data); process::Process<T>::send(to, message.GetTypeName(), data.data(), data.size()); } using process::Process<T>::send; const std::string& serve(double secs = 0, bool once = false) { do { const std::string& name = process::Process<T>::serve(secs, once); if (protobufHandlers.count(name) > 0) { protobufHandlers[name](process::Process<T>::body()); } else { return name; } } while (!once); } template <typename M> void installProtobufHandler(void (T::*method)()) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&ProtobufProcess<T>::handler0, t, method, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C> void installProtobufHandler(void (T::*method)(P1C), P1 (M::*param1)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler1<M, P1, P1C>, t, method, param1, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C> void installProtobufHandler(void (T::*method)(P1C, P2C), P1 (M::*p1)() const, P2 (M::*p2)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler2<M, P1, P1C, P2, P2C>, t, method, p1, p2, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C> void installProtobufHandler(void (T::*method)(P1C, P2C, P3C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler3<M, P1, P1C, P2, P2C, P3, P3C>, t, method, p1, p2, p3, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C> void installProtobufHandler(void (T::*method)(P1C, P2C, P3C, P4C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler4<M, P1, P1C, P2, P2C, P3, P3C, P4, P4C>, t, method, p1, p2, p3, p4, std::tr1::placeholders::_1); delete m; } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C, typename P5, typename P5C> void installProtobufHandler(void (T::*method)(P1C, P2C, P3C, P4C, P5C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const, P5 (M::*p5)() const) { google::protobuf::Message* m = new M(); T* t = static_cast<T*>(this); protobufHandlers[m->GetTypeName()] = std::tr1::bind(&handler5<M, P1, P1C, P2, P2C, P3, P3C, P4, P4C, P5, P5C>, t, method, p1, p2, p3, p4, p5, std::tr1::placeholders::_1); delete m; } private: static void handler0(T* t, void (T::*method)(), const std::string& data) { (t->*method)(); } template <typename M, typename P1, typename P1C> static void handler1(T* t, void (T::*method)(P1C), P1 (M::*p1)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C> static void handler2(T* t, void (T::*method)(P1C, P2C), P1 (M::*p1)() const, P2 (M::*p2)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C> static void handler3(T* t, void (T::*method)(P1C, P2C, P3C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)()), google::protobuf::convert((&m->*p3)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C> static void handler4(T* t, void (T::*method)(P1C, P2C, P3C, P4C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)()), google::protobuf::convert((&m->*p3)()), google::protobuf::convert((&m->*p4)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } template <typename M, typename P1, typename P1C, typename P2, typename P2C, typename P3, typename P3C, typename P4, typename P4C, typename P5, typename P5C> static void handler5(T* t, void (T::*method)(P1C, P2C, P3C, P4C, P5C), P1 (M::*p1)() const, P2 (M::*p2)() const, P3 (M::*p3)() const, P4 (M::*p4)() const, P5 (M::*p5)() const, const std::string& data) { M m; m.ParseFromString(data); if (m.IsInitialized()) { (t->*method)(google::protobuf::convert((&m->*p1)()), google::protobuf::convert((&m->*p2)()), google::protobuf::convert((&m->*p3)()), google::protobuf::convert((&m->*p4)()), google::protobuf::convert((&m->*p5)())); } else { LOG(WARNING) << "Initialization errors: " << m.InitializationErrorString(); } } typedef std::tr1::function<void(const std::string&)> handler; std::tr1::unordered_map<std::string, handler> protobufHandlers; }; namespace process { inline void post(const process::UPID& to, const google::protobuf::Message& message) { std::string data; message.SerializeToString(&data); post(to, message.GetTypeName(), data.data(), data.size()); } // template <typename Request, typename Response> // class RequestResponseProcess // : public ProtobufProcess<RequestResponseProcess<Request, Response> > // { // public: // RequestResponseProcess( // const UPID& _pid, // const Request& _request, // const Promise<Response>& _promise) // : pid(_pid), request(_request), promise(_promise) {} // protected: // virtual void operator () () // { // send(pid, request); // ProcessBase::receive(); // Response response; // CHECK(ProcessBase::name() == response.GetTypeName()); // response.ParseFromString(ProcessBase::body()); // promise.set(response); // } // private: // const UPID pid; // const Request request; // Promise<Response> promise; // }; // template <typename Request, typename Response> // struct Protocol // { // Future<Response> operator () (const UPID& pid, const Request& request) // { // Future<Response> future; // Promise<Response> promise; // promise.associate(future); // RequestResponseProcess<Request, Response>* process = // new RequestResponseProcess<Request, Response>(pid, request, promise); // spawn(process, true); // return future; // } // }; } // namespace process { #endif // __PROCESS_PROTOBUF_HPP__ <|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/views/extensions/browser_action_overflow_menu_controller.h" #include "app/gfx/canvas.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/views/browser_actions_container.h" #include "chrome/browser/views/extensions/browser_action_drag_data.h" #include "chrome/common/extensions/extension.h" #include "views/controls/menu/menu_item_view.h" BrowserActionOverflowMenuController::BrowserActionOverflowMenuController( BrowserActionsContainer* owner, views::MenuButton* menu_button, const std::vector<BrowserActionView*>& views, int start_index) : owner_(owner), observer_(NULL), menu_button_(menu_button), views_(&views), start_index_(start_index), for_drop_(false) { menu_.reset(new views::MenuItemView(this)); menu_->set_has_icons(true); size_t command_id = 0; for (size_t i = start_index; i < views_->size(); ++i) { BrowserActionView* view = (*views_)[i]; scoped_ptr<gfx::Canvas> canvas(view->GetIconWithBadge()); menu_->AppendMenuItemWithIcon( command_id, UTF8ToWide(view->button()->extension()->name()), canvas->ExtractBitmap()); ++command_id; } } BrowserActionOverflowMenuController::~BrowserActionOverflowMenuController() { if (observer_) observer_->NotifyMenuDeleted(this); } bool BrowserActionOverflowMenuController::RunMenu(gfx::NativeWindow window, bool for_drop) { for_drop_ = for_drop; gfx::Rect bounds = menu_button_->GetBounds( views::View::IGNORE_MIRRORING_TRANSFORMATION); gfx::Point screen_loc; views::View::ConvertPointToScreen(menu_button_, &screen_loc); bounds.set_x(screen_loc.x()); bounds.set_y(screen_loc.y()); views::MenuItemView::AnchorPosition anchor = menu_button_->UILayoutIsRightToLeft() ? views::MenuItemView::TOPRIGHT : views::MenuItemView::TOPLEFT; if (for_drop) { menu_->RunMenuForDropAt(window, bounds, anchor); } else { menu_->RunMenuAt(window, menu_button_, bounds, anchor, false); delete this; } return true; } void BrowserActionOverflowMenuController::CancelMenu() { menu_->Cancel(); } void BrowserActionOverflowMenuController::ExecuteCommand(int id) { BrowserActionView* view = (*views_)[start_index_ + id]; owner_->OnBrowserActionExecuted(view->button()); } bool BrowserActionOverflowMenuController::ShowContextMenu( views::MenuItemView* source, int id, int x, int y, bool is_mouse_gesture) { // This blocks until the user choses something or dismisses the menu. owner_->GetContextMenu()->Run( (*views_)[start_index_ + id]->button()->extension(), gfx::Point(x, y)); // The user is done with the context menu, so we can close the underlying // menu. menu_->Cancel(); return true; } void BrowserActionOverflowMenuController::DropMenuClosed( views::MenuItemView* menu) { delete this; } bool BrowserActionOverflowMenuController::GetDropFormats( views::MenuItemView* menu, int* formats, std::set<OSExchangeData::CustomFormat>* custom_formats) { custom_formats->insert(BrowserActionDragData::GetBrowserActionCustomFormat()); return true; } bool BrowserActionOverflowMenuController::AreDropTypesRequired( views::MenuItemView* menu) { return true; } bool BrowserActionOverflowMenuController::CanDrop( views::MenuItemView* menu, const OSExchangeData& data) { BrowserActionDragData drop_data; if (!drop_data.Read(data)) return false; return drop_data.IsFromProfile(owner_->profile()); } int BrowserActionOverflowMenuController::GetDropOperation( views::MenuItemView* item, const views::DropTargetEvent& event, DropPosition* position) { // Don't allow dropping from the BrowserActionContainer into slot 0 of the // overflow menu since once the move has taken place the item you are dragging // falls right out of the menu again once the user releases the button // (because we don't shrink the BrowserActionContainer when you do this). if ((item->GetCommand() == 0) && (*position == DROP_BEFORE)) { BrowserActionDragData drop_data; if (!drop_data.Read(event.GetData())) return DragDropTypes::DRAG_NONE; if (drop_data.index() < owner_->VisibleBrowserActions()) return DragDropTypes::DRAG_NONE; } return DragDropTypes::DRAG_MOVE; } int BrowserActionOverflowMenuController::OnPerformDrop( views::MenuItemView* menu, DropPosition position, const views::DropTargetEvent& event) { BrowserActionDragData drop_data; if (!drop_data.Read(event.GetData())) return DragDropTypes::DRAG_NONE; size_t drop_index; ViewForId(menu->GetCommand(), &drop_index); // When not dragging within the overflow menu (dragging an icon into the menu) // subtract one to get the right index. if (position == DROP_BEFORE && drop_data.index() < owner_->VisibleBrowserActions()) --drop_index; owner_->MoveBrowserAction(drop_data.id(), drop_index); if (for_drop_) delete this; return DragDropTypes::DRAG_MOVE; } bool BrowserActionOverflowMenuController::CanDrag(views::MenuItemView* menu) { return true; } void BrowserActionOverflowMenuController::WriteDragData( views::MenuItemView* sender, OSExchangeData* data) { size_t drag_index; BrowserActionView* view = ViewForId(sender->GetCommand(), &drag_index); std::string id = view->button()->extension()->id(); BrowserActionDragData drag_data(id, drag_index); drag_data.Write(owner_->profile(), data); } int BrowserActionOverflowMenuController::GetDragOperations( views::MenuItemView* sender) { return DragDropTypes::DRAG_MOVE; } BrowserActionView* BrowserActionOverflowMenuController::ViewForId( int id, size_t* index) { // The index of the view being dragged (GetCommand gives a 0-based index into // the overflow menu). size_t view_index = owner_->VisibleBrowserActions() + id; if (index) *index = view_index; return owner_->GetBrowserActionViewAt(view_index); } <commit_msg>Fix anchoring of the menu. It was flipped.<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/views/extensions/browser_action_overflow_menu_controller.h" #include "app/gfx/canvas.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/views/browser_actions_container.h" #include "chrome/browser/views/extensions/browser_action_drag_data.h" #include "chrome/common/extensions/extension.h" #include "views/controls/menu/menu_item_view.h" BrowserActionOverflowMenuController::BrowserActionOverflowMenuController( BrowserActionsContainer* owner, views::MenuButton* menu_button, const std::vector<BrowserActionView*>& views, int start_index) : owner_(owner), observer_(NULL), menu_button_(menu_button), views_(&views), start_index_(start_index), for_drop_(false) { menu_.reset(new views::MenuItemView(this)); menu_->set_has_icons(true); size_t command_id = 0; for (size_t i = start_index; i < views_->size(); ++i) { BrowserActionView* view = (*views_)[i]; scoped_ptr<gfx::Canvas> canvas(view->GetIconWithBadge()); menu_->AppendMenuItemWithIcon( command_id, UTF8ToWide(view->button()->extension()->name()), canvas->ExtractBitmap()); ++command_id; } } BrowserActionOverflowMenuController::~BrowserActionOverflowMenuController() { if (observer_) observer_->NotifyMenuDeleted(this); } bool BrowserActionOverflowMenuController::RunMenu(gfx::NativeWindow window, bool for_drop) { for_drop_ = for_drop; gfx::Rect bounds = menu_button_->GetBounds( views::View::IGNORE_MIRRORING_TRANSFORMATION); gfx::Point screen_loc; views::View::ConvertPointToScreen(menu_button_, &screen_loc); bounds.set_x(screen_loc.x()); bounds.set_y(screen_loc.y()); views::MenuItemView::AnchorPosition anchor = menu_button_->UILayoutIsRightToLeft() ? views::MenuItemView::TOPLEFT : views::MenuItemView::TOPRIGHT; if (for_drop) { menu_->RunMenuForDropAt(window, bounds, anchor); } else { menu_->RunMenuAt(window, menu_button_, bounds, anchor, false); delete this; } return true; } void BrowserActionOverflowMenuController::CancelMenu() { menu_->Cancel(); } void BrowserActionOverflowMenuController::ExecuteCommand(int id) { BrowserActionView* view = (*views_)[start_index_ + id]; owner_->OnBrowserActionExecuted(view->button()); } bool BrowserActionOverflowMenuController::ShowContextMenu( views::MenuItemView* source, int id, int x, int y, bool is_mouse_gesture) { // This blocks until the user choses something or dismisses the menu. owner_->GetContextMenu()->Run( (*views_)[start_index_ + id]->button()->extension(), gfx::Point(x, y)); // The user is done with the context menu, so we can close the underlying // menu. menu_->Cancel(); return true; } void BrowserActionOverflowMenuController::DropMenuClosed( views::MenuItemView* menu) { delete this; } bool BrowserActionOverflowMenuController::GetDropFormats( views::MenuItemView* menu, int* formats, std::set<OSExchangeData::CustomFormat>* custom_formats) { custom_formats->insert(BrowserActionDragData::GetBrowserActionCustomFormat()); return true; } bool BrowserActionOverflowMenuController::AreDropTypesRequired( views::MenuItemView* menu) { return true; } bool BrowserActionOverflowMenuController::CanDrop( views::MenuItemView* menu, const OSExchangeData& data) { BrowserActionDragData drop_data; if (!drop_data.Read(data)) return false; return drop_data.IsFromProfile(owner_->profile()); } int BrowserActionOverflowMenuController::GetDropOperation( views::MenuItemView* item, const views::DropTargetEvent& event, DropPosition* position) { // Don't allow dropping from the BrowserActionContainer into slot 0 of the // overflow menu since once the move has taken place the item you are dragging // falls right out of the menu again once the user releases the button // (because we don't shrink the BrowserActionContainer when you do this). if ((item->GetCommand() == 0) && (*position == DROP_BEFORE)) { BrowserActionDragData drop_data; if (!drop_data.Read(event.GetData())) return DragDropTypes::DRAG_NONE; if (drop_data.index() < owner_->VisibleBrowserActions()) return DragDropTypes::DRAG_NONE; } return DragDropTypes::DRAG_MOVE; } int BrowserActionOverflowMenuController::OnPerformDrop( views::MenuItemView* menu, DropPosition position, const views::DropTargetEvent& event) { BrowserActionDragData drop_data; if (!drop_data.Read(event.GetData())) return DragDropTypes::DRAG_NONE; size_t drop_index; ViewForId(menu->GetCommand(), &drop_index); // When not dragging within the overflow menu (dragging an icon into the menu) // subtract one to get the right index. if (position == DROP_BEFORE && drop_data.index() < owner_->VisibleBrowserActions()) --drop_index; owner_->MoveBrowserAction(drop_data.id(), drop_index); if (for_drop_) delete this; return DragDropTypes::DRAG_MOVE; } bool BrowserActionOverflowMenuController::CanDrag(views::MenuItemView* menu) { return true; } void BrowserActionOverflowMenuController::WriteDragData( views::MenuItemView* sender, OSExchangeData* data) { size_t drag_index; BrowserActionView* view = ViewForId(sender->GetCommand(), &drag_index); std::string id = view->button()->extension()->id(); BrowserActionDragData drag_data(id, drag_index); drag_data.Write(owner_->profile(), data); } int BrowserActionOverflowMenuController::GetDragOperations( views::MenuItemView* sender) { return DragDropTypes::DRAG_MOVE; } BrowserActionView* BrowserActionOverflowMenuController::ViewForId( int id, size_t* index) { // The index of the view being dragged (GetCommand gives a 0-based index into // the overflow menu). size_t view_index = owner_->VisibleBrowserActions() + id; if (index) *index = view_index; return owner_->GetBrowserActionViewAt(view_index); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Assistant of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "tracer.h" #include "bookmarkmanager.h" #include "bookmarkdialog.h" #include "bookmarkfiltermodel.h" #include "bookmarkitem.h" #include "bookmarkmodel.h" #include "centralwidget.h" #include "helpenginewrapper.h" #include <QtGui/QFileDialog> #include <QtGui/QMenu> #include <QtGui/QKeyEvent> #include <QtGui/QMessageBox> #include <QtGui/QSortFilterProxyModel> #include <QFile> #include "xbelsupport.h" QT_BEGIN_NAMESPACE // -- BookmarkManager::BookmarkWidget void BookmarkManager::BookmarkWidget::focusInEvent(QFocusEvent *event) { TRACE_OBJ if (event->reason() != Qt::MouseFocusReason) { ui.lineEdit->selectAll(); ui.lineEdit->setFocus(); // force the focus in event on bookmark manager emit focusInEvent(); } } // -- BookmarkManager::BookmarkTreeView BookmarkManager::BookmarkTreeView::BookmarkTreeView(QWidget *parent) : QTreeView(parent) { TRACE_OBJ setAcceptDrops(true); setDragEnabled(true); setAutoExpandDelay(1000); setUniformRowHeights(true); setDropIndicatorShown(true); setExpandsOnDoubleClick(true); connect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(setExpandedData(QModelIndex))); connect(this, SIGNAL(collapsed(QModelIndex)), this, SLOT(setExpandedData(QModelIndex))); } void BookmarkManager::BookmarkTreeView::subclassKeyPressEvent(QKeyEvent *event) { TRACE_OBJ QTreeView::keyPressEvent(event); } void BookmarkManager::BookmarkTreeView::setExpandedData(const QModelIndex &index) { TRACE_OBJ if (BookmarkModel *treeModel = qobject_cast<BookmarkModel*> (model())) treeModel->setData(index, isExpanded(index), UserRoleExpanded); } // -- BookmarkManager QMutex BookmarkManager::mutex; BookmarkManager* BookmarkManager::bookmarkManager = 0; // -- public BookmarkManager* BookmarkManager::instance() { TRACE_OBJ if (!bookmarkManager) { QMutexLocker _(&mutex); if (!bookmarkManager) bookmarkManager = new BookmarkManager(); } return bookmarkManager; } void BookmarkManager::destroy() { TRACE_OBJ delete bookmarkManager; bookmarkManager = 0; } QWidget* BookmarkManager::bookmarkDockWidget() const { TRACE_OBJ if (bookmarkWidget) return bookmarkWidget; return 0; } void BookmarkManager::takeBookmarksMenu(QMenu* menu) { TRACE_OBJ bookmarkMenu = menu; refeshBookmarkMenu(); } // -- public slots void BookmarkManager::addBookmark(const QString &title, const QString &url) { TRACE_OBJ showBookmarkDialog(title.isEmpty() ? tr("Untiled") : title, url.isEmpty() ? QLatin1String("about:blank") : url); } // -- private BookmarkManager::BookmarkManager() : typeAndSearch(false) , bookmarkMenu(0) , bookmarkModel(new BookmarkModel) , bookmarkWidget(new BookmarkWidget) , bookmarkTreeView(new BookmarkTreeView) { TRACE_OBJ bookmarkWidget->installEventFilter(this); connect(bookmarkWidget->ui.add, SIGNAL(clicked()), this, SLOT(addBookmark())); connect(bookmarkWidget->ui.remove, SIGNAL(clicked()), this, SLOT(removeBookmark())); connect(bookmarkWidget->ui.lineEdit, SIGNAL(textChanged(QString)), this, SLOT(textChanged(QString))); connect(bookmarkWidget, SIGNAL(focusInEvent()), this, SLOT(focusInEvent())); bookmarkTreeView->setModel(bookmarkModel); bookmarkTreeView->installEventFilter(this); bookmarkTreeView->viewport()->installEventFilter(this); bookmarkTreeView->setContextMenuPolicy(Qt::CustomContextMenu); bookmarkWidget->ui.stackedWidget->addWidget(bookmarkTreeView); connect(bookmarkTreeView, SIGNAL(activated(QModelIndex)), this, SLOT(setSourceFromIndex(QModelIndex))); connect(bookmarkTreeView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint))); connect(&HelpEngineWrapper::instance(), SIGNAL(setupFinished()), this, SLOT(setupFinished())); connect(bookmarkModel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(refeshBookmarkMenu())); } BookmarkManager::~BookmarkManager() { TRACE_OBJ HelpEngineWrapper::instance().setBookmarks(bookmarkModel->bookmarks()); } void BookmarkManager::removeItem(const QModelIndex &index) { TRACE_OBJ QModelIndex current = index; if (typeAndSearch) { // need to map because of proxy current = typeAndSearchModel->mapToSource(current); current = bookmarkFilterModel->mapToSource(current); } else if (!bookmarkModel->parent(index).isValid()) { return; // check if we should delete the "Bookmarks Menu", bail } if (bookmarkModel->hasChildren(current)) { int value = QMessageBox::question(bookmarkTreeView, tr("Remove"), tr("You are going to delete a Folder, this will also<br>" "remove it's content. Are you sure to continue?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (value == QMessageBox::Cancel) return; } bookmarkModel->removeItem(current); } bool BookmarkManager::eventFilter(QObject *object, QEvent *event) { if (object != bookmarkTreeView && object != bookmarkTreeView->viewport() && object != bookmarkWidget) return QObject::eventFilter(object, event); TRACE_OBJ const bool isWidget = object == bookmarkWidget; if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent*>(event); switch (ke->key()) { case Qt::Key_F2: { renameBookmark(bookmarkTreeView->currentIndex()); } break; case Qt::Key_Delete: { removeItem(bookmarkTreeView->currentIndex()); } break; case Qt::Key_Up: { // needs event filter on widget case Qt::Key_Down: if (isWidget) bookmarkTreeView->subclassKeyPressEvent(ke); } break; case Qt::Key_Escape: { emit escapePressed(); } break; default: break; } } if (event->type() == QEvent::MouseButtonRelease && !isWidget) { QMouseEvent *me = static_cast<QMouseEvent*>(event); switch (me->button()) { case Qt::LeftButton: { if (me->modifiers() & Qt::ControlModifier) setSourceFromIndex(bookmarkTreeView->currentIndex(), true); } break; case Qt::MidButton: { setSourceFromIndex(bookmarkTreeView->currentIndex(), true); } break; default: break; } } return QObject::eventFilter(object, event); } void BookmarkManager::buildBookmarksMenu(const QModelIndex &index, QMenu* menu) { TRACE_OBJ if (!index.isValid()) return; const QString &text = index.data().toString(); const QIcon &icon = qVariantValue<QIcon>(index.data(Qt::DecorationRole)); if (index.data(UserRoleFolder).toBool()) { if (QMenu* subMenu = menu->addMenu(icon, text)) { for (int i = 0; i < bookmarkModel->rowCount(index); ++i) buildBookmarksMenu(bookmarkModel->index(i, 0, index), subMenu); } } else { QAction *action = menu->addAction(icon, text); action->setData(index.data(UserRoleUrl).toString()); } } void BookmarkManager::showBookmarkDialog(const QString &name, const QString &url) { TRACE_OBJ BookmarkDialog dialog(bookmarkModel, name, url, bookmarkTreeView); dialog.exec(); } // -- private slots void BookmarkManager::setupFinished() { TRACE_OBJ bookmarkModel->setBookmarks(HelpEngineWrapper::instance().bookmarks()); bookmarkModel->expandFoldersIfNeeeded(bookmarkTreeView); refeshBookmarkMenu(); bookmarkTreeView->hideColumn(1); bookmarkTreeView->header()->setVisible(false); bookmarkTreeView->header()->setStretchLastSection(true); bookmarkFilterModel = new BookmarkFilterModel(this); bookmarkFilterModel->setSourceModel(bookmarkModel); bookmarkFilterModel->filterBookmarkFolders(); typeAndSearchModel = new QSortFilterProxyModel(this); typeAndSearchModel->setDynamicSortFilter(true); typeAndSearchModel->setSourceModel(bookmarkFilterModel); } void BookmarkManager::addBookmark() { TRACE_OBJ if (CentralWidget *widget = CentralWidget::instance()) { showBookmarkDialog(widget->currentTitle(), widget->currentSource().toString()); } } void BookmarkManager::removeBookmark() { TRACE_OBJ removeItem(bookmarkTreeView->currentIndex()); } //void BookmarkManager::manageBookmarks() //{ // TRACE_OBJ //} void BookmarkManager::refeshBookmarkMenu() { TRACE_OBJ if (!bookmarkMenu) return; bookmarkMenu->clear(); //bookmarkMenu->addAction(tr("Manage Bookmarks..."), this, // SLOT(manageBookmarks())); bookmarkMenu->addAction(tr("Import..."), this, SLOT(importBookmarks())); bookmarkMenu->addAction(tr("Export..."), this, SLOT(exportBookmarks())); bookmarkMenu->addAction(tr("Add Bookmark..."), this, SLOT(addBookmark()), QKeySequence(tr("Ctrl+D"))); bookmarkMenu->addSeparator(); const QModelIndex &root = bookmarkModel->index(0, 0, QModelIndex()); for (int i = 0; i < bookmarkModel->rowCount(root); ++i) buildBookmarksMenu(bookmarkModel->index(i, 0, root), bookmarkMenu); connect(bookmarkMenu, SIGNAL(triggered(QAction*)), this, SLOT(setSourceFromAction(QAction*))); } void BookmarkManager::renameBookmark(const QModelIndex &index) { // check if we should rename the "Bookmarks Menu", bail if (!typeAndSearch && !bookmarkModel->parent(index).isValid()) return; bookmarkModel->setItemsEditable(true); bookmarkTreeView->edit(index); bookmarkModel->setItemsEditable(false); } void BookmarkManager::importBookmarks() { TRACE_OBJ const QString &fileName = QFileDialog::getOpenFileName(0, tr("Open File"), QDir::currentPath(), tr("Files (*.xbel)")); if (fileName.isEmpty()) return; QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { XbelReader reader(bookmarkModel); reader.readFromFile(&file); } } void BookmarkManager::exportBookmarks() { TRACE_OBJ QString fileName = QFileDialog::getSaveFileName(0, tr("Save File"), QLatin1String("untitled.xbel"), tr("Files (*.xbel)")); const QLatin1String suffix(".xbel"); if (!fileName.endsWith(suffix)) fileName.append(suffix); QFile file(fileName); if (file.open(QIODevice::WriteOnly)) { XbelWriter writer(bookmarkModel); writer.writeToFile(&file); } else { QMessageBox::information(bookmarkTreeView, tr("Qt Assistant"), tr("Unable to save bookmarks."), tr("OK")); } } void BookmarkManager::setSourceFromAction(QAction *action) { TRACE_OBJ const QVariant &data = action->data(); if (data.canConvert<QUrl>()) emit setSource(data.toUrl()); } void BookmarkManager::setSourceFromIndex(const QModelIndex &index, bool newTab) { TRACE_OBJ QAbstractItemModel *base = bookmarkModel; if (typeAndSearch) base = typeAndSearchModel; if (base->data(index, UserRoleFolder).toBool()) return; const QVariant &data = base->data(index, UserRoleUrl); if (data.canConvert<QUrl>()) { if (newTab) emit setSourceInNewTab(data.toUrl()); else emit setSource(data.toUrl()); } } void BookmarkManager::customContextMenuRequested(const QPoint &point) { TRACE_OBJ QModelIndex index = bookmarkTreeView->indexAt(point); if (!index.isValid()) return; // check if we should open the menu on "Bookmarks Menu", bail if (!typeAndSearch && !bookmarkModel->parent(index).isValid()) return; QAction *remove = 0; QAction *rename = 0; QAction *showItem = 0; QAction *showItemInNewTab = 0; QMenu menu(QLatin1String("")); if (!typeAndSearch && bookmarkModel->data(index, UserRoleFolder).toBool()) { remove = menu.addAction(tr("Delete Folder")); rename = menu.addAction(tr("Rename Folder")); } else { showItem = menu.addAction(tr("Show Bookmark")); showItemInNewTab = menu.addAction(tr("Show Bookmark in New Tab")); menu.addSeparator(); remove = menu.addAction(tr("Delete Bookmark")); rename = menu.addAction(tr("Rename Bookmark")); } QAction *pickedAction = menu.exec(bookmarkTreeView->mapToGlobal(point)); if (pickedAction == rename) renameBookmark(index); else if (pickedAction == remove) removeItem(index); else if (pickedAction == showItem || pickedAction == showItemInNewTab) setSourceFromIndex(index, pickedAction == showItemInNewTab); } void BookmarkManager::focusInEvent() { TRACE_OBJ const QModelIndex &index = bookmarkTreeView->indexAt(QPoint(2, 2)); if (index.isValid()) bookmarkTreeView->setCurrentIndex(index); } void BookmarkManager::textChanged(const QString &text) { TRACE_OBJ if (!bookmarkWidget->ui.lineEdit->text().isEmpty()) { if (!typeAndSearch) { typeAndSearch = true; bookmarkTreeView->setItemsExpandable(false); bookmarkTreeView->setRootIsDecorated(false); bookmarkTreeView->setModel(typeAndSearchModel); } typeAndSearchModel->setFilterRegExp(QRegExp(text)); } else { typeAndSearch = false; bookmarkTreeView->setModel(bookmarkModel); bookmarkTreeView->setItemsExpandable(true); bookmarkTreeView->setRootIsDecorated(true); bookmarkModel->expandFoldersIfNeeeded(bookmarkTreeView); } } QT_END_NAMESPACE <commit_msg>Make sure the bookmarks menu updates on add/ remove as well.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Assistant of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "tracer.h" #include "bookmarkmanager.h" #include "bookmarkdialog.h" #include "bookmarkfiltermodel.h" #include "bookmarkitem.h" #include "bookmarkmodel.h" #include "centralwidget.h" #include "helpenginewrapper.h" #include <QtGui/QFileDialog> #include <QtGui/QMenu> #include <QtGui/QKeyEvent> #include <QtGui/QMessageBox> #include <QtGui/QSortFilterProxyModel> #include <QFile> #include "xbelsupport.h" QT_BEGIN_NAMESPACE // -- BookmarkManager::BookmarkWidget void BookmarkManager::BookmarkWidget::focusInEvent(QFocusEvent *event) { TRACE_OBJ if (event->reason() != Qt::MouseFocusReason) { ui.lineEdit->selectAll(); ui.lineEdit->setFocus(); // force the focus in event on bookmark manager emit focusInEvent(); } } // -- BookmarkManager::BookmarkTreeView BookmarkManager::BookmarkTreeView::BookmarkTreeView(QWidget *parent) : QTreeView(parent) { TRACE_OBJ setAcceptDrops(true); setDragEnabled(true); setAutoExpandDelay(1000); setUniformRowHeights(true); setDropIndicatorShown(true); setExpandsOnDoubleClick(true); connect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(setExpandedData(QModelIndex))); connect(this, SIGNAL(collapsed(QModelIndex)), this, SLOT(setExpandedData(QModelIndex))); } void BookmarkManager::BookmarkTreeView::subclassKeyPressEvent(QKeyEvent *event) { TRACE_OBJ QTreeView::keyPressEvent(event); } void BookmarkManager::BookmarkTreeView::setExpandedData(const QModelIndex &index) { TRACE_OBJ if (BookmarkModel *treeModel = qobject_cast<BookmarkModel*> (model())) treeModel->setData(index, isExpanded(index), UserRoleExpanded); } // -- BookmarkManager QMutex BookmarkManager::mutex; BookmarkManager* BookmarkManager::bookmarkManager = 0; // -- public BookmarkManager* BookmarkManager::instance() { TRACE_OBJ if (!bookmarkManager) { QMutexLocker _(&mutex); if (!bookmarkManager) bookmarkManager = new BookmarkManager(); } return bookmarkManager; } void BookmarkManager::destroy() { TRACE_OBJ delete bookmarkManager; bookmarkManager = 0; } QWidget* BookmarkManager::bookmarkDockWidget() const { TRACE_OBJ if (bookmarkWidget) return bookmarkWidget; return 0; } void BookmarkManager::takeBookmarksMenu(QMenu* menu) { TRACE_OBJ bookmarkMenu = menu; refeshBookmarkMenu(); } // -- public slots void BookmarkManager::addBookmark(const QString &title, const QString &url) { TRACE_OBJ showBookmarkDialog(title.isEmpty() ? tr("Untiled") : title, url.isEmpty() ? QLatin1String("about:blank") : url); } // -- private BookmarkManager::BookmarkManager() : typeAndSearch(false) , bookmarkMenu(0) , bookmarkModel(new BookmarkModel) , bookmarkWidget(new BookmarkWidget) , bookmarkTreeView(new BookmarkTreeView) { TRACE_OBJ bookmarkWidget->installEventFilter(this); connect(bookmarkWidget->ui.add, SIGNAL(clicked()), this, SLOT(addBookmark())); connect(bookmarkWidget->ui.remove, SIGNAL(clicked()), this, SLOT(removeBookmark())); connect(bookmarkWidget->ui.lineEdit, SIGNAL(textChanged(QString)), this, SLOT(textChanged(QString))); connect(bookmarkWidget, SIGNAL(focusInEvent()), this, SLOT(focusInEvent())); bookmarkTreeView->setModel(bookmarkModel); bookmarkTreeView->installEventFilter(this); bookmarkTreeView->viewport()->installEventFilter(this); bookmarkTreeView->setContextMenuPolicy(Qt::CustomContextMenu); bookmarkWidget->ui.stackedWidget->addWidget(bookmarkTreeView); connect(bookmarkTreeView, SIGNAL(activated(QModelIndex)), this, SLOT(setSourceFromIndex(QModelIndex))); connect(bookmarkTreeView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint))); connect(&HelpEngineWrapper::instance(), SIGNAL(setupFinished()), this, SLOT(setupFinished())); connect(bookmarkModel, SIGNAL(rowsRemoved(QModelIndex, int, int)), this, SLOT(refeshBookmarkMenu())); connect(bookmarkModel, SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(refeshBookmarkMenu())); connect(bookmarkModel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(refeshBookmarkMenu())); } BookmarkManager::~BookmarkManager() { TRACE_OBJ HelpEngineWrapper::instance().setBookmarks(bookmarkModel->bookmarks()); } void BookmarkManager::removeItem(const QModelIndex &index) { TRACE_OBJ QModelIndex current = index; if (typeAndSearch) { // need to map because of proxy current = typeAndSearchModel->mapToSource(current); current = bookmarkFilterModel->mapToSource(current); } else if (!bookmarkModel->parent(index).isValid()) { return; // check if we should delete the "Bookmarks Menu", bail } if (bookmarkModel->hasChildren(current)) { int value = QMessageBox::question(bookmarkTreeView, tr("Remove"), tr("You are going to delete a Folder, this will also<br>" "remove it's content. Are you sure to continue?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (value == QMessageBox::Cancel) return; } bookmarkModel->removeItem(current); } bool BookmarkManager::eventFilter(QObject *object, QEvent *event) { if (object != bookmarkTreeView && object != bookmarkTreeView->viewport() && object != bookmarkWidget) return QObject::eventFilter(object, event); TRACE_OBJ const bool isWidget = object == bookmarkWidget; if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent*>(event); switch (ke->key()) { case Qt::Key_F2: { renameBookmark(bookmarkTreeView->currentIndex()); } break; case Qt::Key_Delete: { removeItem(bookmarkTreeView->currentIndex()); } break; case Qt::Key_Up: { // needs event filter on widget case Qt::Key_Down: if (isWidget) bookmarkTreeView->subclassKeyPressEvent(ke); } break; case Qt::Key_Escape: { emit escapePressed(); } break; default: break; } } if (event->type() == QEvent::MouseButtonRelease && !isWidget) { QMouseEvent *me = static_cast<QMouseEvent*>(event); switch (me->button()) { case Qt::LeftButton: { if (me->modifiers() & Qt::ControlModifier) setSourceFromIndex(bookmarkTreeView->currentIndex(), true); } break; case Qt::MidButton: { setSourceFromIndex(bookmarkTreeView->currentIndex(), true); } break; default: break; } } return QObject::eventFilter(object, event); } void BookmarkManager::buildBookmarksMenu(const QModelIndex &index, QMenu* menu) { TRACE_OBJ if (!index.isValid()) return; const QString &text = index.data().toString(); const QIcon &icon = qVariantValue<QIcon>(index.data(Qt::DecorationRole)); if (index.data(UserRoleFolder).toBool()) { if (QMenu* subMenu = menu->addMenu(icon, text)) { for (int i = 0; i < bookmarkModel->rowCount(index); ++i) buildBookmarksMenu(bookmarkModel->index(i, 0, index), subMenu); } } else { QAction *action = menu->addAction(icon, text); action->setData(index.data(UserRoleUrl).toString()); } } void BookmarkManager::showBookmarkDialog(const QString &name, const QString &url) { TRACE_OBJ BookmarkDialog dialog(bookmarkModel, name, url, bookmarkTreeView); dialog.exec(); } // -- private slots void BookmarkManager::setupFinished() { TRACE_OBJ bookmarkModel->setBookmarks(HelpEngineWrapper::instance().bookmarks()); bookmarkModel->expandFoldersIfNeeeded(bookmarkTreeView); refeshBookmarkMenu(); bookmarkTreeView->hideColumn(1); bookmarkTreeView->header()->setVisible(false); bookmarkTreeView->header()->setStretchLastSection(true); bookmarkFilterModel = new BookmarkFilterModel(this); bookmarkFilterModel->setSourceModel(bookmarkModel); bookmarkFilterModel->filterBookmarkFolders(); typeAndSearchModel = new QSortFilterProxyModel(this); typeAndSearchModel->setDynamicSortFilter(true); typeAndSearchModel->setSourceModel(bookmarkFilterModel); } void BookmarkManager::addBookmark() { TRACE_OBJ if (CentralWidget *widget = CentralWidget::instance()) addBookmark(widget->currentTitle(), widget->currentSource().toString()); } void BookmarkManager::removeBookmark() { TRACE_OBJ removeItem(bookmarkTreeView->currentIndex()); } //void BookmarkManager::manageBookmarks() //{ // TRACE_OBJ //} void BookmarkManager::refeshBookmarkMenu() { TRACE_OBJ if (!bookmarkMenu) return; bookmarkMenu->clear(); //bookmarkMenu->addAction(tr("Manage Bookmarks..."), this, // SLOT(manageBookmarks())); bookmarkMenu->addAction(tr("Import..."), this, SLOT(importBookmarks())); bookmarkMenu->addAction(tr("Export..."), this, SLOT(exportBookmarks())); bookmarkMenu->addAction(tr("Add Bookmark..."), this, SLOT(addBookmark()), QKeySequence(tr("Ctrl+D"))); bookmarkMenu->addSeparator(); const QModelIndex &root = bookmarkModel->index(0, 0, QModelIndex()); for (int i = 0; i < bookmarkModel->rowCount(root); ++i) buildBookmarksMenu(bookmarkModel->index(i, 0, root), bookmarkMenu); connect(bookmarkMenu, SIGNAL(triggered(QAction*)), this, SLOT(setSourceFromAction(QAction*))); } void BookmarkManager::renameBookmark(const QModelIndex &index) { // check if we should rename the "Bookmarks Menu", bail if (!typeAndSearch && !bookmarkModel->parent(index).isValid()) return; bookmarkModel->setItemsEditable(true); bookmarkTreeView->edit(index); bookmarkModel->setItemsEditable(false); } void BookmarkManager::importBookmarks() { TRACE_OBJ const QString &fileName = QFileDialog::getOpenFileName(0, tr("Open File"), QDir::currentPath(), tr("Files (*.xbel)")); if (fileName.isEmpty()) return; QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { XbelReader reader(bookmarkModel); reader.readFromFile(&file); } } void BookmarkManager::exportBookmarks() { TRACE_OBJ QString fileName = QFileDialog::getSaveFileName(0, tr("Save File"), QLatin1String("untitled.xbel"), tr("Files (*.xbel)")); const QLatin1String suffix(".xbel"); if (!fileName.endsWith(suffix)) fileName.append(suffix); QFile file(fileName); if (file.open(QIODevice::WriteOnly)) { XbelWriter writer(bookmarkModel); writer.writeToFile(&file); } else { QMessageBox::information(bookmarkTreeView, tr("Qt Assistant"), tr("Unable to save bookmarks."), tr("OK")); } } void BookmarkManager::setSourceFromAction(QAction *action) { TRACE_OBJ const QVariant &data = action->data(); if (data.canConvert<QUrl>()) emit setSource(data.toUrl()); } void BookmarkManager::setSourceFromIndex(const QModelIndex &index, bool newTab) { TRACE_OBJ QAbstractItemModel *base = bookmarkModel; if (typeAndSearch) base = typeAndSearchModel; if (base->data(index, UserRoleFolder).toBool()) return; const QVariant &data = base->data(index, UserRoleUrl); if (data.canConvert<QUrl>()) { if (newTab) emit setSourceInNewTab(data.toUrl()); else emit setSource(data.toUrl()); } } void BookmarkManager::customContextMenuRequested(const QPoint &point) { TRACE_OBJ QModelIndex index = bookmarkTreeView->indexAt(point); if (!index.isValid()) return; // check if we should open the menu on "Bookmarks Menu", bail if (!typeAndSearch && !bookmarkModel->parent(index).isValid()) return; QAction *remove = 0; QAction *rename = 0; QAction *showItem = 0; QAction *showItemInNewTab = 0; QMenu menu(QLatin1String("")); if (!typeAndSearch && bookmarkModel->data(index, UserRoleFolder).toBool()) { remove = menu.addAction(tr("Delete Folder")); rename = menu.addAction(tr("Rename Folder")); } else { showItem = menu.addAction(tr("Show Bookmark")); showItemInNewTab = menu.addAction(tr("Show Bookmark in New Tab")); menu.addSeparator(); remove = menu.addAction(tr("Delete Bookmark")); rename = menu.addAction(tr("Rename Bookmark")); } QAction *pickedAction = menu.exec(bookmarkTreeView->mapToGlobal(point)); if (pickedAction == rename) renameBookmark(index); else if (pickedAction == remove) removeItem(index); else if (pickedAction == showItem || pickedAction == showItemInNewTab) setSourceFromIndex(index, pickedAction == showItemInNewTab); } void BookmarkManager::focusInEvent() { TRACE_OBJ const QModelIndex &index = bookmarkTreeView->indexAt(QPoint(2, 2)); if (index.isValid()) bookmarkTreeView->setCurrentIndex(index); } void BookmarkManager::textChanged(const QString &text) { TRACE_OBJ if (!bookmarkWidget->ui.lineEdit->text().isEmpty()) { if (!typeAndSearch) { typeAndSearch = true; bookmarkTreeView->setItemsExpandable(false); bookmarkTreeView->setRootIsDecorated(false); bookmarkTreeView->setModel(typeAndSearchModel); } typeAndSearchModel->setFilterRegExp(QRegExp(text)); } else { typeAndSearch = false; bookmarkTreeView->setModel(bookmarkModel); bookmarkTreeView->setItemsExpandable(true); bookmarkTreeView->setRootIsDecorated(true); bookmarkModel->expandFoldersIfNeeeded(bookmarkTreeView); } } QT_END_NAMESPACE <|endoftext|>
<commit_before>#include "NexusFileReader.h" #include <iostream> using namespace H5; /** * Create a object to read the specified file * * @param filename - the full path of the NeXus file * @return - an object with which to read information from the file */ NexusFileReader::NexusFileReader(const std::string &filename) : m_file(std::make_shared<H5File>(filename, H5F_ACC_RDONLY)) { DataSet dataset = m_file->openDataSet("/raw_data_1/good_frames"); size_t *numOfFrames = new size_t[1]; dataset.read(numOfFrames, PredType::NATIVE_UINT64); m_numberOfFrames = *numOfFrames; // Reduce number of frames by 1, this is a fix for an inconsistency between // the SANS and WISH files m_numberOfFrames--; delete[] numOfFrames; } /** * Get the size of the NeXus file in bytes * * @return - the size of the file in bytes */ hsize_t NexusFileReader::getFileSize() { return m_file->getFileSize(); } uint64_t NexusFileReader::getTotalEventCount() { DataSet dataset = m_file->openDataSet("/raw_data_1/detector_1_events/total_counts"); uint64_t *totalCount = new uint64_t[1]; dataset.read(totalCount, PredType::NATIVE_UINT64); return *totalCount; } /** * Gets the event index of the start of the specified frame * * @param frameNumber - find the event index for the start of this frame * @return - event index corresponding to the start of the specified frame */ hsize_t NexusFileReader::getFrameStart(hsize_t frameNumber) { auto dataset = m_file->openDataSet("/raw_data_1/detector_1_events/event_index"); uint64_t *frameStart = new uint64_t[1]; hsize_t count[1], offset[1], stride[1], block[1]; count[0] = 1; offset[0] = frameNumber; stride[0] = 1; block[0] = 1; auto dataspace = dataset.getSpace(); dataspace.selectHyperslab(H5S_SELECT_SET, count, offset, stride, block); hsize_t dimsm[1]; dimsm[0] = 1; DataSpace memspace(1, dimsm); dataset.read(frameStart, PredType::NATIVE_UINT64, memspace, dataspace); return *frameStart; } /** * Get the number of events which are in the specified frame * * @param frameNumber - the number of the frame in which to count the number of events * @return - the number of events in the specified frame */ hsize_t NexusFileReader::getNumberOfEventsInFrame(hsize_t frameNumber) { return getFrameStart(frameNumber + 1) - getFrameStart(frameNumber); } /** * Get the list of detector IDs corresponding to events in the specifed frame * * @param detIds - vector in which to store the detector IDs * @param frameNumber - the number of the frame in which to get the detector IDs * @return - false if the specified frame number is not the data range, true otherwise */ bool NexusFileReader::getEventDetIds(std::vector<uint32_t> &detIds, hsize_t frameNumber) { if (frameNumber >= m_numberOfFrames) return false; auto dataset = m_file->openDataSet("/raw_data_1/detector_1_events/event_id"); auto numberOfEventsInFrame = getNumberOfEventsInFrame(frameNumber); hsize_t count[1], offset[1], stride[1], block[1]; count[0] = numberOfEventsInFrame; offset[0] = getFrameStart(frameNumber); stride[0] = 1; block[0] = 1; auto dataspace = dataset.getSpace(); dataspace.selectHyperslab(H5S_SELECT_SET, count, offset, stride, block); uint32_t *detIdsArray = new uint32_t[numberOfEventsInFrame]; hsize_t dimsm[1]; dimsm[0] = numberOfEventsInFrame; DataSpace memspace(1, dimsm); dataset.read(detIdsArray, PredType::NATIVE_UINT32, memspace, dataspace); detIds.insert(detIds.end(), &detIdsArray[0], &detIdsArray[numberOfEventsInFrame]); return true; } /** * Get the list of flight times corresponding to events in the specifed frame * * @param tofs - vector in which to store the time-of-flight * @param frameNumber - the number of the frame in which to get the time-of-flights * @return - false if the specified frame number is not the data range, true otherwise */ bool NexusFileReader::getEventTofs(std::vector<uint64_t> &tofs, hsize_t frameNumber) { if (frameNumber >= m_numberOfFrames) return false; auto dataset = m_file->openDataSet("/raw_data_1/detector_1_events/event_time_offset"); auto numberOfEventsInFrame = getNumberOfEventsInFrame(frameNumber); hsize_t count[1], offset[1], stride[1], block[1]; count[0] = numberOfEventsInFrame; offset[0] = getFrameStart(frameNumber); stride[0] = 1; block[0] = 1; auto dataspace = dataset.getSpace(); dataspace.selectHyperslab(H5S_SELECT_SET, count, offset, stride, block); double *timeOffsetArray = new double[numberOfEventsInFrame]; hsize_t dimsm[1]; dimsm[0] = numberOfEventsInFrame; DataSpace memspace(1, dimsm); dataset.read(timeOffsetArray, PredType::NATIVE_DOUBLE, memspace, dataspace); tofs.resize(numberOfEventsInFrame); for (size_t tofIndex = 0; tofIndex < numberOfEventsInFrame; tofIndex++) { tofs[tofIndex] = static_cast<uint64_t>((timeOffsetArray[tofIndex] * 1e3)); } delete[] timeOffsetArray; return true; } <commit_msg>get rid of some raw pointers in NexusFileReader<commit_after>#include "NexusFileReader.h" #include <iostream> using namespace H5; /** * Create a object to read the specified file * * @param filename - the full path of the NeXus file * @return - an object with which to read information from the file */ NexusFileReader::NexusFileReader(const std::string &filename) : m_file(std::make_shared<H5File>(filename, H5F_ACC_RDONLY)) { DataSet dataset = m_file->openDataSet("/raw_data_1/good_frames"); size_t *numOfFrames = new size_t[1]; dataset.read(numOfFrames, PredType::NATIVE_UINT64); m_numberOfFrames = *numOfFrames; // Reduce number of frames by 1, this is a fix for an inconsistency between // the SANS and WISH files m_numberOfFrames--; delete[] numOfFrames; } /** * Get the size of the NeXus file in bytes * * @return - the size of the file in bytes */ hsize_t NexusFileReader::getFileSize() { return m_file->getFileSize(); } uint64_t NexusFileReader::getTotalEventCount() { DataSet dataset = m_file->openDataSet("/raw_data_1/detector_1_events/total_counts"); uint64_t *totalCount = new uint64_t[1]; dataset.read(totalCount, PredType::NATIVE_UINT64); return *totalCount; } /** * Gets the event index of the start of the specified frame * * @param frameNumber - find the event index for the start of this frame * @return - event index corresponding to the start of the specified frame */ hsize_t NexusFileReader::getFrameStart(hsize_t frameNumber) { auto dataset = m_file->openDataSet("/raw_data_1/detector_1_events/event_index"); uint64_t *frameStart = new uint64_t[1]; hsize_t count[1], offset[1], stride[1], block[1]; count[0] = 1; offset[0] = frameNumber; stride[0] = 1; block[0] = 1; auto dataspace = dataset.getSpace(); dataspace.selectHyperslab(H5S_SELECT_SET, count, offset, stride, block); hsize_t dimsm[1]; dimsm[0] = 1; DataSpace memspace(1, dimsm); dataset.read(frameStart, PredType::NATIVE_UINT64, memspace, dataspace); return *frameStart; } /** * Get the number of events which are in the specified frame * * @param frameNumber - the number of the frame in which to count the number of events * @return - the number of events in the specified frame */ hsize_t NexusFileReader::getNumberOfEventsInFrame(hsize_t frameNumber) { return getFrameStart(frameNumber + 1) - getFrameStart(frameNumber); } /** * Get the list of detector IDs corresponding to events in the specifed frame * * @param detIds - vector in which to store the detector IDs * @param frameNumber - the number of the frame in which to get the detector IDs * @return - false if the specified frame number is not the data range, true otherwise */ bool NexusFileReader::getEventDetIds(std::vector<uint32_t> &detIds, hsize_t frameNumber) { if (frameNumber >= m_numberOfFrames) return false; auto dataset = m_file->openDataSet("/raw_data_1/detector_1_events/event_id"); auto numberOfEventsInFrame = getNumberOfEventsInFrame(frameNumber); hsize_t count[1], offset[1], stride[1], block[1]; count[0] = numberOfEventsInFrame; offset[0] = getFrameStart(frameNumber); stride[0] = 1; block[0] = 1; auto dataspace = dataset.getSpace(); dataspace.selectHyperslab(H5S_SELECT_SET, count, offset, stride, block); detIds.resize(numberOfEventsInFrame); hsize_t dimsm[1]; dimsm[0] = numberOfEventsInFrame; DataSpace memspace(1, dimsm); dataset.read(detIds.data(), PredType::NATIVE_UINT32, memspace, dataspace); return true; } /** * Get the list of flight times corresponding to events in the specifed frame * * @param tofs - vector in which to store the time-of-flight * @param frameNumber - the number of the frame in which to get the time-of-flights * @return - false if the specified frame number is not the data range, true otherwise */ bool NexusFileReader::getEventTofs(std::vector<uint64_t> &tofs, hsize_t frameNumber) { if (frameNumber >= m_numberOfFrames) return false; auto dataset = m_file->openDataSet("/raw_data_1/detector_1_events/event_time_offset"); auto numberOfEventsInFrame = getNumberOfEventsInFrame(frameNumber); hsize_t count[1], offset[1], stride[1], block[1]; count[0] = numberOfEventsInFrame; offset[0] = getFrameStart(frameNumber); stride[0] = 1; block[0] = 1; auto dataspace = dataset.getSpace(); dataspace.selectHyperslab(H5S_SELECT_SET, count, offset, stride, block); std::vector<double> timeOffsetArray(numberOfEventsInFrame); hsize_t dimsm[1]; dimsm[0] = numberOfEventsInFrame; DataSpace memspace(1, dimsm); dataset.read(timeOffsetArray.data(), PredType::NATIVE_DOUBLE, memspace, dataspace); tofs.resize(numberOfEventsInFrame); for (size_t tofIndex = 0; tofIndex < numberOfEventsInFrame; tofIndex++) { tofs[tofIndex] = static_cast<uint64_t>((timeOffsetArray[tofIndex] * 1e3)); } return true; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* bzflag common header */ #include "common.h" /* interface header */ #include "Roaming.h" /* system headers */ #include <string> #include <math.h> #include <string.h> /* common headers */ #include "Flag.h" #include "StateDatabase.h" #include "BZDBCache.h" #include "AnsiCodes.h" /* local headers */ #include "Player.h" #include "LocalPlayer.h" #include "World.h" #include "ScoreboardRenderer.h" /* Someone needs to look at this to see if it can be cleaned up */ extern const bool devDriving; // initialize the singleton template <> Roaming* Singleton<Roaming>::_instance = (Roaming*)0; Roaming::Roaming() : view(roamViewDisabled), targetManual(-1), targetWinner(-1), targetFlag(-1) { resetCamera(); } void Roaming::resetCamera(void) { camera.pos[0] = 0.0f; camera.pos[1] = 0.0f; camera.pos[2] = BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT); camera.theta = 0.0f; camera.zoom = 60.0f; camera.phi = -0.0f; } void Roaming::setCamera(RoamingCamera* newCam) { memcpy(&camera, newCam, sizeof(RoamingCamera)); } void Roaming::setMode(RoamingView newView) { if (LocalPlayer::getMyTank()->getTeam() == ObserverTeam || devDriving) { // disallow disabling roaming in observer mode if ((newView == roamViewDisabled) && !devDriving) view = (RoamingView)(roamViewDisabled + 1); else view = newView; } else { // don't allow roaming for non-observers if (newView != roamViewDisabled) view = roamViewDisabled; } // make sure we have a valid target changeTarget(next); changeTarget(previous); } void Roaming::changeTarget(Roaming::RoamingTarget target, int explicitIndex) { bool found = false; World* world = World::getWorld(); if (view == roamViewFree || view == roamViewDisabled) { // do nothing found = true; } else if (view == roamViewFlag) { if (target == explicitSet) { targetFlag = explicitIndex; found = true; } else { int i, j; const int maxFlags = world->getMaxFlags(); for (i = 1; i < maxFlags; ++i) { if (target == next) { j = (targetFlag + i) % maxFlags; } else if (target == previous) { j = (targetFlag - i + maxFlags) % maxFlags; } const Flag& flag = world->getFlag(j); if (flag.type->flagTeam != NoTeam) { targetFlag = j; found = true; break; } } } } else { if (target == explicitSet) { targetManual = targetWinner = explicitIndex; found = true; } else { int i, j; for (i = 0; i < world->getCurMaxPlayers(); ++i) { if (target == next) { j = (targetManual + i + 2) % (world->getCurMaxPlayers() + 1) - 1; } else if (target == previous) { j = (targetManual - i + world->getCurMaxPlayers() + 1) % (world->getCurMaxPlayers() + 1) - 1; } if ((j == -1) || (world->getPlayer(j) && (world->getPlayer(j)->getTeam() != ObserverTeam) && world->getPlayer(j)->isAlive())) { targetManual = targetWinner = j; found = true; break; } } } } if (!found) view = roamViewFree; buildRoamingLabel(); } void Roaming::buildRoamingLabel(void) { std::string playerString = ""; World* world = World::getWorld(); // follow the important tank if (targetManual == -1) { Player* top = NULL; if (world && world->allowRabbit()) { // follow the white rabbit top = world->getCurrentRabbit(); if (top != NULL) { playerString = "Rabbit "; targetWinner = top->getId(); } } if (top == NULL) { // find the leader top = ScoreboardRenderer::getLeader(&playerString); if (top == NULL) { targetWinner = 0; } else { targetWinner = top->getId(); } } } Player* tracked; if (!devDriving) { tracked = world->getPlayer(targetWinner); } else { tracked = LocalPlayer::getMyTank(); } if (tracked) { if (BZDBCache::colorful) { int color = tracked->getTeam(); if (World::getWorld()->allowRabbit() && (color == RogueTeam)) { // hunters are orange (hack) color = OrangeColor; } else if (color < 0 || color > 4) { // non-teamed, rabbit are white (same as observer) color = WhiteColor; } playerString += ColorStrings[color]; } playerString += tracked->getCallSign(); const FlagType* flag = tracked->getFlag(); if (flag != Flags::Null) { if (BZDBCache::colorful) { playerString += ColorStrings[CyanColor] + " / "; if (flag->flagTeam != NoTeam) { playerString += ColorStrings[flag->flagTeam]; } else { playerString += ColorStrings[WhiteColor]; } } else { playerString += " / "; } if (flag->endurance == FlagNormal) { playerString += flag->flagName; } else { playerString += flag->flagAbbv; } } switch (view) { case roamViewTrack: { roamingLabel = "Tracking " + playerString; break; } case roamViewFollow: { roamingLabel = "Following " + playerString; break; } case roamViewFP: { roamingLabel = "Driving with " + playerString; break; } case roamViewFlag: { roamingLabel = std::string("Tracking ") + world->getFlag(targetFlag).type->flagName + " Flag"; break; } default: { roamingLabel = "Roaming"; break; } } } else { roamingLabel = "Roaming"; } } void Roaming::updatePosition(RoamingCamera* dc, float dt) { World* world = World::getWorld(); // are we tracking? bool tracking = false; const float* trackPos; if (view == roamViewTrack) { Player *target; if (!devDriving) { if (targetWinner < world->getCurMaxPlayers()) { target = world->getPlayer(targetWinner); } else { target = NULL; } } else { target = LocalPlayer::getMyTank(); } if (target != NULL) { trackPos = target->getPosition(); tracking = true; } } else if (view == roamViewFlag) { if ((world != NULL) && (targetFlag < world->getMaxFlags())) { Flag &flag = world->getFlag(targetFlag); trackPos = flag.position; tracking = true; } } // modify X and Y coords if (!tracking) { const float c = cosf(camera.theta * (float)(M_PI / 180.0f)); const float s = sinf(camera.theta * (float)(M_PI / 180.0f)); camera.pos[0] += dt * (c * dc->pos[0] - s * dc->pos[1]); camera.pos[1] += dt * (c * dc->pos[1] + s * dc->pos[0]); } else { float dx = camera.pos[0] - trackPos[0]; float dy = camera.pos[1] - trackPos[1]; float dist = sqrtf((dx * dx) + (dy * dy)); float nomDist = 4.0f * BZDBCache::tankSpeed; if (nomDist == 0.0f) { nomDist = 100.0f; } float distFactor = (dist / nomDist); if (distFactor < 0.25f) { distFactor = 0.25f; } float newDist = dist - (dt * distFactor * dc->pos[0]); const float minDist = BZDBCache::tankLength * 0.5f; if (newDist < minDist) { if (dist >= minDist) { newDist = minDist; } else { newDist = dist; } } float scale = 0.0f; if (dist > 0.0f) { scale = newDist / dist; } dx = dx * scale; dy = dy * scale; if (fabsf(dx) < 0.001f) dx = 0.001f; if (fabsf(dy) < 0.001f) dy = 0.001f; const float dtheta = -(dt * dc->theta * (float)(M_PI / 180.0f)); const float c = cosf(dtheta); const float s = sinf(dtheta); camera.pos[0] = trackPos[0] + ((c * dx) - (s * dy)); camera.pos[1] = trackPos[1] + ((c * dy) + (s * dx)); // setup so that free roam stays in the last state camera.theta = atan2f(trackPos[1] - camera.pos[1], trackPos[0] - camera.pos[0]); camera.theta *= (float)(180.0f / M_PI); camera.phi = atan2f(trackPos[2] - camera.pos[2], newDist); camera.phi *= (float)(180.0f / M_PI); } // modify Z coordinate camera.pos[2] += dt * dc->pos[2]; float muzzleHeight = BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT); if (camera.pos[2] < muzzleHeight) { camera.pos[2] = muzzleHeight; dc->pos[2] = 0.0f; } // adjust the angles if (!tracking) { camera.theta += dt * dc->theta; camera.phi += dt * dc->phi; } camera.zoom += dt * dc->zoom; if (camera.zoom < BZDB.eval("camera.zoomMin")) { camera.zoom = BZDB.eval("camera.zoomMin"); } else if (camera.zoom > BZDB.eval("camera.zoomMax")) { camera.zoom = BZDB.eval("camera.zoomMax"); } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>don't stay in a roaming mode when rejoining with a non-observer tank<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* bzflag common header */ #include "common.h" /* interface header */ #include "Roaming.h" /* system headers */ #include <string> #include <math.h> #include <string.h> /* common headers */ #include "Flag.h" #include "StateDatabase.h" #include "BZDBCache.h" #include "AnsiCodes.h" /* local headers */ #include "Player.h" #include "LocalPlayer.h" #include "World.h" #include "ScoreboardRenderer.h" /* Someone needs to look at this to see if it can be cleaned up */ extern const bool devDriving; // initialize the singleton template <> Roaming* Singleton<Roaming>::_instance = (Roaming*)0; Roaming::Roaming() : view(roamViewDisabled), targetManual(-1), targetWinner(-1), targetFlag(-1) { resetCamera(); } void Roaming::resetCamera(void) { camera.pos[0] = 0.0f; camera.pos[1] = 0.0f; camera.pos[2] = BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT); camera.theta = 0.0f; camera.zoom = 60.0f; camera.phi = -0.0f; } void Roaming::setCamera(RoamingCamera* newCam) { memcpy(&camera, newCam, sizeof(RoamingCamera)); } void Roaming::setMode(RoamingView newView) { if (LocalPlayer::getMyTank()->getTeam() == ObserverTeam || devDriving) { // disallow disabling roaming in observer mode if ((newView == roamViewDisabled) && !devDriving) view = (RoamingView)(roamViewDisabled + 1); else view = newView; } else { // don't allow roaming for non-observers if (newView != roamViewDisabled) view = roamViewDisabled; else view = newView; } // make sure we have a valid target changeTarget(next); changeTarget(previous); } void Roaming::changeTarget(Roaming::RoamingTarget target, int explicitIndex) { bool found = false; World* world = World::getWorld(); if (view == roamViewFree || view == roamViewDisabled) { // do nothing found = true; } else if (view == roamViewFlag) { if (target == explicitSet) { targetFlag = explicitIndex; found = true; } else { int i, j; const int maxFlags = world->getMaxFlags(); for (i = 1; i < maxFlags; ++i) { if (target == next) { j = (targetFlag + i) % maxFlags; } else if (target == previous) { j = (targetFlag - i + maxFlags) % maxFlags; } const Flag& flag = world->getFlag(j); if (flag.type->flagTeam != NoTeam) { targetFlag = j; found = true; break; } } } } else { if (target == explicitSet) { targetManual = targetWinner = explicitIndex; found = true; } else { int i, j; for (i = 0; i < world->getCurMaxPlayers(); ++i) { if (target == next) { j = (targetManual + i + 2) % (world->getCurMaxPlayers() + 1) - 1; } else if (target == previous) { j = (targetManual - i + world->getCurMaxPlayers() + 1) % (world->getCurMaxPlayers() + 1) - 1; } if ((j == -1) || (world->getPlayer(j) && (world->getPlayer(j)->getTeam() != ObserverTeam) && world->getPlayer(j)->isAlive())) { targetManual = targetWinner = j; found = true; break; } } } } if (!found) view = roamViewFree; buildRoamingLabel(); } void Roaming::buildRoamingLabel(void) { std::string playerString = ""; World* world = World::getWorld(); // follow the important tank if (targetManual == -1) { Player* top = NULL; if (world && world->allowRabbit()) { // follow the white rabbit top = world->getCurrentRabbit(); if (top != NULL) { playerString = "Rabbit "; targetWinner = top->getId(); } } if (top == NULL) { // find the leader top = ScoreboardRenderer::getLeader(&playerString); if (top == NULL) { targetWinner = 0; } else { targetWinner = top->getId(); } } } Player* tracked; if (!devDriving) { tracked = world->getPlayer(targetWinner); } else { tracked = LocalPlayer::getMyTank(); } if (tracked) { if (BZDBCache::colorful) { int color = tracked->getTeam(); if (World::getWorld()->allowRabbit() && (color == RogueTeam)) { // hunters are orange (hack) color = OrangeColor; } else if (color < 0 || color > 4) { // non-teamed, rabbit are white (same as observer) color = WhiteColor; } playerString += ColorStrings[color]; } playerString += tracked->getCallSign(); const FlagType* flag = tracked->getFlag(); if (flag != Flags::Null) { if (BZDBCache::colorful) { playerString += ColorStrings[CyanColor] + " / "; if (flag->flagTeam != NoTeam) { playerString += ColorStrings[flag->flagTeam]; } else { playerString += ColorStrings[WhiteColor]; } } else { playerString += " / "; } if (flag->endurance == FlagNormal) { playerString += flag->flagName; } else { playerString += flag->flagAbbv; } } switch (view) { case roamViewTrack: { roamingLabel = "Tracking " + playerString; break; } case roamViewFollow: { roamingLabel = "Following " + playerString; break; } case roamViewFP: { roamingLabel = "Driving with " + playerString; break; } case roamViewFlag: { roamingLabel = std::string("Tracking ") + world->getFlag(targetFlag).type->flagName + " Flag"; break; } default: { roamingLabel = "Roaming"; break; } } } else { roamingLabel = "Roaming"; } } void Roaming::updatePosition(RoamingCamera* dc, float dt) { World* world = World::getWorld(); // are we tracking? bool tracking = false; const float* trackPos; if (view == roamViewTrack) { Player *target; if (!devDriving) { if (targetWinner < world->getCurMaxPlayers()) { target = world->getPlayer(targetWinner); } else { target = NULL; } } else { target = LocalPlayer::getMyTank(); } if (target != NULL) { trackPos = target->getPosition(); tracking = true; } } else if (view == roamViewFlag) { if ((world != NULL) && (targetFlag < world->getMaxFlags())) { Flag &flag = world->getFlag(targetFlag); trackPos = flag.position; tracking = true; } } // modify X and Y coords if (!tracking) { const float c = cosf(camera.theta * (float)(M_PI / 180.0f)); const float s = sinf(camera.theta * (float)(M_PI / 180.0f)); camera.pos[0] += dt * (c * dc->pos[0] - s * dc->pos[1]); camera.pos[1] += dt * (c * dc->pos[1] + s * dc->pos[0]); } else { float dx = camera.pos[0] - trackPos[0]; float dy = camera.pos[1] - trackPos[1]; float dist = sqrtf((dx * dx) + (dy * dy)); float nomDist = 4.0f * BZDBCache::tankSpeed; if (nomDist == 0.0f) { nomDist = 100.0f; } float distFactor = (dist / nomDist); if (distFactor < 0.25f) { distFactor = 0.25f; } float newDist = dist - (dt * distFactor * dc->pos[0]); const float minDist = BZDBCache::tankLength * 0.5f; if (newDist < minDist) { if (dist >= minDist) { newDist = minDist; } else { newDist = dist; } } float scale = 0.0f; if (dist > 0.0f) { scale = newDist / dist; } dx = dx * scale; dy = dy * scale; if (fabsf(dx) < 0.001f) dx = 0.001f; if (fabsf(dy) < 0.001f) dy = 0.001f; const float dtheta = -(dt * dc->theta * (float)(M_PI / 180.0f)); const float c = cosf(dtheta); const float s = sinf(dtheta); camera.pos[0] = trackPos[0] + ((c * dx) - (s * dy)); camera.pos[1] = trackPos[1] + ((c * dy) + (s * dx)); // setup so that free roam stays in the last state camera.theta = atan2f(trackPos[1] - camera.pos[1], trackPos[0] - camera.pos[0]); camera.theta *= (float)(180.0f / M_PI); camera.phi = atan2f(trackPos[2] - camera.pos[2], newDist); camera.phi *= (float)(180.0f / M_PI); } // modify Z coordinate camera.pos[2] += dt * dc->pos[2]; float muzzleHeight = BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT); if (camera.pos[2] < muzzleHeight) { camera.pos[2] = muzzleHeight; dc->pos[2] = 0.0f; } // adjust the angles if (!tracking) { camera.theta += dt * dc->theta; camera.phi += dt * dc->phi; } camera.zoom += dt * dc->zoom; if (camera.zoom < BZDB.eval("camera.zoomMin")) { camera.zoom = BZDB.eval("camera.zoomMin"); } else if (camera.zoom > BZDB.eval("camera.zoomMax")) { camera.zoom = BZDB.eval("camera.zoomMax"); } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/scenarios/side_pass/side_pass_scenario.h" #include <fstream> #include <limits> #include <utility> #include "cybertron/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/common/time/time.h" #include "modules/common/util/file.h" #include "modules/common/util/string_tokenizer.h" #include "modules/common/util/string_util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/hdmap/hdmap.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/planning/common/ego_info.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/constraint_checker/constraint_checker.h" #include "modules/planning/toolkits/optimizers/dp_poly_path/dp_poly_path_optimizer.h" #include "modules/planning/toolkits/optimizers/dp_st_speed/dp_st_speed_optimizer.h" #include "modules/planning/toolkits/optimizers/path_decider/path_decider.h" #include "modules/planning/toolkits/optimizers/poly_st_speed/poly_st_speed_optimizer.h" #include "modules/planning/toolkits/optimizers/qp_spline_path/qp_spline_path_optimizer.h" #include "modules/planning/toolkits/optimizers/qp_spline_st_speed/qp_spline_st_speed_optimizer.h" #include "modules/planning/toolkits/optimizers/speed_decider/speed_decider.h" namespace apollo { namespace planning { using common::ErrorCode; using common::SLPoint; using common::SpeedPoint; using common::TrajectoryPoint; using common::math::Vec2d; using common::time::Clock; namespace { constexpr double kPathOptimizationFallbackCost = 2e4; constexpr double kSpeedOptimizationFallbackCost = 2e4; constexpr double kStraightForwardLineCost = 10.0; } // namespace apollo::common::util::Factory< ScenarioConfig::StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config)> SidePassScenario::s_stage_factory_; void SidePassScenario::RegisterStages() { s_stage_factory_.Clear(); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_APPROACH_OBSTACLE, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassApproachObstacle(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_DETECT_SAFETY, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassDetectSafety(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_GENERATE_PATH, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassGeneratePath(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassStopOnWaitPoint(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_PASS_OBSTACLE, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassPassObstacle(config); }); } std::unique_ptr<Stage> SidePassScenario::CreateStage( const ScenarioConfig::StageConfig& stage_config) { if (s_stage_factory_.Empty()) { RegisterStages(); } auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(), stage_config); ptr->SetContext(&context_); return ptr; } bool SidePassScenario::IsTransferable(const Scenario& current_scenario, const common::TrajectoryPoint& ego_point, const Frame& frame) const { if (frame.reference_line_info().size() > 1) { return false; } if (current_scenario.scenario_type() == ScenarioConfig::SIDE_PASS) { return (current_scenario.GetStatus() != Scenario::ScenarioStatus::STATUS_DONE); } else if (current_scenario.scenario_type() != ScenarioConfig::LANE_FOLLOW) { return false; } else { return IsSidePassScenario(ego_point, frame); } } Stage::StageStatus SidePassApproachObstacle::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame); if (!plan_ok) { return Stage::ERROR; } if (frame->vehicle_state().linear_velocity() < 1.0e-5) { return Stage::FINISHED; } return Stage::RUNNING; } Stage::StageStatus SidePassGeneratePath::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { if (PlanningOnReferenceLine(planning_start_point, frame)) { return Stage::FINISHED; } else { return Stage::ERROR; } } Stage::StageStatus SidePassStopOnWaitPoint::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { return Stage::FINISHED; } Stage::StageStatus SidePassDetectSafety::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { if (PlanningOnReferenceLine(planning_start_point, frame)) { return Stage::ERROR; } bool is_safe = true; const PathDecision& path_decision = frame->reference_line_info().front().path_decision(); for (const auto* path_obstacle : path_decision.path_obstacles().Items()) { if (path_obstacle->obstacle()->IsVirtual()) { is_safe = false; break; } } return is_safe ? Stage::FINISHED : Stage::RUNNING; } Stage::StageStatus SidePassPassObstacle::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame); if (!plan_ok) { return Stage::ERROR; } const SLBoundary& adc_sl_boundary = frame->reference_line_info().front().AdcSlBoundary(); const auto& frenet_frame_path = frame->reference_line_info().front().path_data().frenet_frame_path(); const auto& frenet_frame_point = frenet_frame_path.PointAt(frenet_frame_path.NumOfPoints() - 1); int adc_start_s = adc_sl_boundary.start_s(); int path_end_s = frenet_frame_point.s(); if ((path_end_s - adc_start_s) > 20.0) { return Stage::FINISHED; } return Stage::RUNNING; } bool SidePassScenario::IsSidePassScenario( const common::TrajectoryPoint& planning_start_point, const Frame& frame) const { const SLBoundary& adc_sl_boundary = frame.reference_line_info().front().AdcSlBoundary(); const PathDecision& path_decision = frame.reference_line_info().front().path_decision(); // TODO(lianglia-apollo) return HasBlockingObstacle(adc_sl_boundary, path_decision); } bool SidePassScenario::IsFarFromIntersection(const Frame& frame) { if (frame.reference_line_info().size() > 1) { return false; } const SLBoundary& adc_sl_boundary = frame.reference_line_info().front().AdcSlBoundary(); const auto& first_encounters = frame.reference_line_info().front().FirstEncounteredOverlaps(); const double kClearDistance = 15.0; // in meters for (const auto& encounter : first_encounters) { if (encounter.first != ReferenceLineInfo::SIGNAL || encounter.first != ReferenceLineInfo::STOP_SIGN) { continue; } if (encounter.second.start_s - adc_sl_boundary.end_s() < kClearDistance) { return false; } } return true; } bool SidePassScenario::HasBlockingObstacle( const SLBoundary& adc_sl_boundary, const PathDecision& path_decision) const { // a blocking obstacle is an obstacle blocks the road when it is not blocked // (by other obstacles or traffic rules) for (const auto* path_obstacle : path_decision.path_obstacles().Items()) { if (path_obstacle->obstacle()->IsVirtual() || !path_obstacle->obstacle()->IsStatic()) { continue; } CHECK(path_obstacle->obstacle()->IsStatic()); if (path_obstacle->PerceptionSLBoundary().start_s() <= adc_sl_boundary.end_s()) { // such vehicles are behind the adc. continue; } constexpr double kAdcDistanceThreshold = 15.0; // unit: m if (path_obstacle->PerceptionSLBoundary().start_s() > adc_sl_boundary.end_s() + kAdcDistanceThreshold) { // vehicles are far away continue; } if (path_obstacle->PerceptionSLBoundary().start_l() > 1.0 || path_obstacle->PerceptionSLBoundary().end_l() < -1.0) { continue; } bool is_blocked_by_others = false; for (const auto* other_obstacle : path_decision.path_obstacles().Items()) { if (other_obstacle->Id() == path_obstacle->Id()) { continue; } if (other_obstacle->PerceptionSLBoundary().start_l() > path_obstacle->PerceptionSLBoundary().end_l() || other_obstacle->PerceptionSLBoundary().end_l() < path_obstacle->PerceptionSLBoundary().start_l()) { // not blocking the backside vehicle continue; } double delta_s = other_obstacle->PerceptionSLBoundary().start_s() - path_obstacle->PerceptionSLBoundary().end_s(); if (delta_s < 0.0 || delta_s > kAdcDistanceThreshold) { continue; } else { // TODO(All): fixed the segmentation bug for large vehicles, otherwise // the follow line will be problematic. // is_blocked_by_others = true; break; } } if (!is_blocked_by_others) { return true; } } return false; } } // namespace planning } // namespace apollo <commit_msg>planning: side pass scenario added next stage for each stage.<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/scenarios/side_pass/side_pass_scenario.h" #include <fstream> #include <limits> #include <utility> #include "cybertron/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/common/time/time.h" #include "modules/common/util/file.h" #include "modules/common/util/string_tokenizer.h" #include "modules/common/util/string_util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/hdmap/hdmap.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/planning/common/ego_info.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/constraint_checker/constraint_checker.h" #include "modules/planning/toolkits/optimizers/dp_poly_path/dp_poly_path_optimizer.h" #include "modules/planning/toolkits/optimizers/dp_st_speed/dp_st_speed_optimizer.h" #include "modules/planning/toolkits/optimizers/path_decider/path_decider.h" #include "modules/planning/toolkits/optimizers/poly_st_speed/poly_st_speed_optimizer.h" #include "modules/planning/toolkits/optimizers/qp_spline_path/qp_spline_path_optimizer.h" #include "modules/planning/toolkits/optimizers/qp_spline_st_speed/qp_spline_st_speed_optimizer.h" #include "modules/planning/toolkits/optimizers/speed_decider/speed_decider.h" namespace apollo { namespace planning { using common::ErrorCode; using common::SLPoint; using common::SpeedPoint; using common::TrajectoryPoint; using common::math::Vec2d; using common::time::Clock; namespace { constexpr double kPathOptimizationFallbackCost = 2e4; constexpr double kSpeedOptimizationFallbackCost = 2e4; constexpr double kStraightForwardLineCost = 10.0; } // namespace apollo::common::util::Factory< ScenarioConfig::StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config)> SidePassScenario::s_stage_factory_; void SidePassScenario::RegisterStages() { s_stage_factory_.Clear(); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_APPROACH_OBSTACLE, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassApproachObstacle(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_DETECT_SAFETY, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassDetectSafety(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_GENERATE_PATH, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassGeneratePath(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassStopOnWaitPoint(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_PASS_OBSTACLE, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassPassObstacle(config); }); } std::unique_ptr<Stage> SidePassScenario::CreateStage( const ScenarioConfig::StageConfig& stage_config) { if (s_stage_factory_.Empty()) { RegisterStages(); } auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(), stage_config); ptr->SetContext(&context_); return ptr; } bool SidePassScenario::IsTransferable(const Scenario& current_scenario, const common::TrajectoryPoint& ego_point, const Frame& frame) const { if (frame.reference_line_info().size() > 1) { return false; } if (current_scenario.scenario_type() == ScenarioConfig::SIDE_PASS) { return (current_scenario.GetStatus() != Scenario::ScenarioStatus::STATUS_DONE); } else if (current_scenario.scenario_type() != ScenarioConfig::LANE_FOLLOW) { return false; } else { return IsSidePassScenario(ego_point, frame); } } Stage::StageStatus SidePassApproachObstacle::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame); if (!plan_ok) { return Stage::ERROR; } if (frame->vehicle_state().linear_velocity() < 1.0e-5) { next_stage_ = ScenarioConfig::SIDE_PASS_GENERATE_PATH; return Stage::FINISHED; } return Stage::RUNNING; } Stage::StageStatus SidePassGeneratePath::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { if (PlanningOnReferenceLine(planning_start_point, frame)) { next_stage_ = ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT; return Stage::FINISHED; } else { return Stage::ERROR; } } Stage::StageStatus SidePassStopOnWaitPoint::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY; return Stage::FINISHED; } Stage::StageStatus SidePassDetectSafety::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { if (PlanningOnReferenceLine(planning_start_point, frame)) { return Stage::ERROR; } bool is_safe = true; const PathDecision& path_decision = frame->reference_line_info().front().path_decision(); for (const auto* path_obstacle : path_decision.path_obstacles().Items()) { if (path_obstacle->obstacle()->IsVirtual()) { is_safe = false; break; } } if (is_safe) { next_stage_ = ScenarioConfig::SIDE_PASS_PASS_OBSTACLE; return Stage::FINISHED; } return Stage::RUNNING; } Stage::StageStatus SidePassPassObstacle::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame); if (!plan_ok) { return Stage::ERROR; } const SLBoundary& adc_sl_boundary = frame->reference_line_info().front().AdcSlBoundary(); const auto& frenet_frame_path = frame->reference_line_info().front().path_data().frenet_frame_path(); const auto& frenet_frame_point = frenet_frame_path.PointAt(frenet_frame_path.NumOfPoints() - 1); int adc_start_s = adc_sl_boundary.start_s(); int path_end_s = frenet_frame_point.s(); if ((path_end_s - adc_start_s) > 20.0) { next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } return Stage::RUNNING; } bool SidePassScenario::IsSidePassScenario( const common::TrajectoryPoint& planning_start_point, const Frame& frame) const { const SLBoundary& adc_sl_boundary = frame.reference_line_info().front().AdcSlBoundary(); const PathDecision& path_decision = frame.reference_line_info().front().path_decision(); // TODO(lianglia-apollo) return HasBlockingObstacle(adc_sl_boundary, path_decision); } bool SidePassScenario::IsFarFromIntersection(const Frame& frame) { if (frame.reference_line_info().size() > 1) { return false; } const SLBoundary& adc_sl_boundary = frame.reference_line_info().front().AdcSlBoundary(); const auto& first_encounters = frame.reference_line_info().front().FirstEncounteredOverlaps(); const double kClearDistance = 15.0; // in meters for (const auto& encounter : first_encounters) { if (encounter.first != ReferenceLineInfo::SIGNAL || encounter.first != ReferenceLineInfo::STOP_SIGN) { continue; } if (encounter.second.start_s - adc_sl_boundary.end_s() < kClearDistance) { return false; } } return true; } bool SidePassScenario::HasBlockingObstacle( const SLBoundary& adc_sl_boundary, const PathDecision& path_decision) const { // a blocking obstacle is an obstacle blocks the road when it is not blocked // (by other obstacles or traffic rules) for (const auto* path_obstacle : path_decision.path_obstacles().Items()) { if (path_obstacle->obstacle()->IsVirtual() || !path_obstacle->obstacle()->IsStatic()) { continue; } CHECK(path_obstacle->obstacle()->IsStatic()); if (path_obstacle->PerceptionSLBoundary().start_s() <= adc_sl_boundary.end_s()) { // such vehicles are behind the adc. continue; } constexpr double kAdcDistanceThreshold = 15.0; // unit: m if (path_obstacle->PerceptionSLBoundary().start_s() > adc_sl_boundary.end_s() + kAdcDistanceThreshold) { // vehicles are far away continue; } if (path_obstacle->PerceptionSLBoundary().start_l() > 1.0 || path_obstacle->PerceptionSLBoundary().end_l() < -1.0) { continue; } bool is_blocked_by_others = false; for (const auto* other_obstacle : path_decision.path_obstacles().Items()) { if (other_obstacle->Id() == path_obstacle->Id()) { continue; } if (other_obstacle->PerceptionSLBoundary().start_l() > path_obstacle->PerceptionSLBoundary().end_l() || other_obstacle->PerceptionSLBoundary().end_l() < path_obstacle->PerceptionSLBoundary().start_l()) { // not blocking the backside vehicle continue; } double delta_s = other_obstacle->PerceptionSLBoundary().start_s() - path_obstacle->PerceptionSLBoundary().end_s(); if (delta_s < 0.0 || delta_s > kAdcDistanceThreshold) { continue; } else { // TODO(All): fixed the segmentation bug for large vehicles, otherwise // the follow line will be problematic. // is_blocked_by_others = true; break; } } if (!is_blocked_by_others) { return true; } } return false; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2009-2011 VMware, Inc. * All Rights Reserved. * * 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, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS 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 <stddef.h> #include <llvm-c/Core.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Target/TargetInstrInfo.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/MemoryObject.h> #if HAVE_LLVM >= 0x0300 #include <llvm/Support/TargetRegistry.h> #else /* HAVE_LLVM < 0x0300 */ #include <llvm/Target/TargetRegistry.h> #endif /* HAVE_LLVM < 0x0300 */ #if HAVE_LLVM >= 0x0209 #include <llvm/Support/Host.h> #else /* HAVE_LLVM < 0x0209 */ #include <llvm/System/Host.h> #endif /* HAVE_LLVM < 0x0209 */ #if HAVE_LLVM >= 0x0207 #include <llvm/MC/MCDisassembler.h> #include <llvm/MC/MCAsmInfo.h> #include <llvm/MC/MCInst.h> #include <llvm/MC/MCInstPrinter.h> #endif /* HAVE_LLVM >= 0x0207 */ #if HAVE_LLVM >= 0x0301 #include <llvm/MC/MCRegisterInfo.h> #endif /* HAVE_LLVM >= 0x0301 */ #include "util/u_math.h" #include "util/u_debug.h" #include "lp_bld_debug.h" /** * Check alignment. * * It is important that this check is not implemented as a macro or inlined * function, as the compiler assumptions in respect to alignment of global * and stack variables would often make the check a no op, defeating the * whole purpose of the exercise. */ extern "C" boolean lp_check_alignment(const void *ptr, unsigned alignment) { assert(util_is_power_of_two(alignment)); return ((uintptr_t)ptr & (alignment - 1)) == 0; } class raw_debug_ostream : public llvm::raw_ostream { uint64_t pos; void write_impl(const char *Ptr, size_t Size); #if HAVE_LLVM >= 0x207 uint64_t current_pos() const { return pos; } size_t preferred_buffer_size() const { return 512; } #else uint64_t current_pos() { return pos; } size_t preferred_buffer_size() { return 512; } #endif }; void raw_debug_ostream::write_impl(const char *Ptr, size_t Size) { if (Size > 0) { char *lastPtr = (char *)&Ptr[Size]; char last = *lastPtr; *lastPtr = 0; _debug_printf("%*s", Size, Ptr); *lastPtr = last; pos += Size; } } /** * Same as LLVMDumpValue, but through our debugging channels. */ extern "C" void lp_debug_dump_value(LLVMValueRef value) { #if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED) raw_debug_ostream os; llvm::unwrap(value)->print(os); os.flush(); #else LLVMDumpValue(value); #endif } #if HAVE_LLVM >= 0x0207 /* * MemoryObject wrapper around a buffer of memory, to be used by MC * disassembler. */ class BufferMemoryObject: public llvm::MemoryObject { private: const uint8_t *Bytes; uint64_t Length; public: BufferMemoryObject(const uint8_t *bytes, uint64_t length) : Bytes(bytes), Length(length) { } uint64_t getBase() const { return 0; } uint64_t getExtent() const { return Length; } int readByte(uint64_t addr, uint8_t *byte) const { if (addr > getExtent()) return -1; *byte = Bytes[addr]; return 0; } }; #endif /* HAVE_LLVM >= 0x0207 */ /* * Disassemble a function, using the LLVM MC disassembler. * * See also: * - http://blog.llvm.org/2010/01/x86-disassembler.html * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html */ extern "C" void lp_disassemble(const void* func) { #if HAVE_LLVM >= 0x0207 using namespace llvm; const uint8_t *bytes = (const uint8_t *)func; /* * Limit disassembly to this extent */ const uint64_t extent = 96 * 1024; uint64_t max_pc = 0; /* * Initialize all used objects. */ #if HAVE_LLVM >= 0x0301 std::string Triple = sys::getDefaultTargetTriple(); #else std::string Triple = sys::getHostTriple(); #endif std::string Error; const Target *T = TargetRegistry::lookupTarget(Triple, Error); #if HAVE_LLVM >= 0x0300 OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple)); #else OwningPtr<const MCAsmInfo> AsmInfo(T->createAsmInfo(Triple)); #endif if (!AsmInfo) { debug_printf("error: no assembly info for target %s\n", Triple.c_str()); return; } #if HAVE_LLVM >= 0x0300 const MCSubtargetInfo *STI = T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""); OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI)); #else OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler()); #endif if (!DisAsm) { debug_printf("error: no disassembler for target %s\n", Triple.c_str()); return; } raw_debug_ostream Out; #if HAVE_LLVM >= 0x0300 unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); #else int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); #endif #if HAVE_LLVM >= 0x0301 OwningPtr<const MCRegisterInfo> MRI(T->createMCRegInfo(Triple)); if (!MRI) { debug_printf("error: no register info for target %s\n", Triple.c_str()); return; } OwningPtr<const MCInstrInfo> MII(T->createMCInstrInfo()); if (!MII) { debug_printf("error: no instruction info for target %s\n", Triple.c_str()); return; } #endif #if HAVE_LLVM >= 0x0301 OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI)); #elif HAVE_LLVM == 0x0300 OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *STI)); #elif HAVE_LLVM >= 0x0208 OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo)); #else OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, Out)); #endif if (!Printer) { debug_printf("error: no instruction printer for target %s\n", Triple.c_str()); return; } #if HAVE_LLVM >= 0x0301 TargetOptions options; #if defined(DEBUG) options.JITEmitDebugInfo = true; #endif #if defined(PIPE_ARCH_X86) options.StackAlignmentOverride = 4; #endif #if defined(DEBUG) || defined(PROFILE) options.NoFramePointerElim = true; #endif TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), "", options); #elif HAVE_LLVM == 0x0300 TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), ""); #else TargetMachine *TM = T->createTargetMachine(Triple, ""); #endif const TargetInstrInfo *TII = TM->getInstrInfo(); /* * Wrap the data in a MemoryObject */ BufferMemoryObject memoryObject((const uint8_t *)bytes, extent); uint64_t pc; pc = 0; while (true) { MCInst Inst; uint64_t Size; /* * Print address. We use addresses relative to the start of the function, * so that between runs. */ debug_printf("%6lu:\t", (unsigned long)pc); if (!DisAsm->getInstruction(Inst, Size, memoryObject, pc, #if HAVE_LLVM >= 0x0300 nulls(), nulls())) { #else nulls())) { #endif debug_printf("invalid\n"); pc += 1; } /* * Output the bytes in hexidecimal format. */ if (0) { unsigned i; for (i = 0; i < Size; ++i) { debug_printf("%02x ", ((const uint8_t*)bytes)[pc + i]); } for (; i < 16; ++i) { debug_printf(" "); } } /* * Print the instruction. */ #if HAVE_LLVM >= 0x0300 Printer->printInst(&Inst, Out, ""); #elif HAVE_LLVM >= 0x208 Printer->printInst(&Inst, Out); #else Printer->printInst(&Inst); #endif Out.flush(); /* * Advance. */ pc += Size; #if HAVE_LLVM >= 0x0300 const MCInstrDesc &TID = TII->get(Inst.getOpcode()); #else const TargetInstrDesc &TID = TII->get(Inst.getOpcode()); #endif /* * Keep track of forward jumps to a nearby address. */ if (TID.isBranch()) { for (unsigned i = 0; i < Inst.getNumOperands(); ++i) { const MCOperand &operand = Inst.getOperand(i); if (operand.isImm()) { uint64_t jump; /* * FIXME: Handle both relative and absolute addresses correctly. * EDInstInfo actually has this info, but operandTypes and * operandFlags enums are not exposed in the public interface. */ if (1) { /* * PC relative addr. */ jump = pc + operand.getImm(); } else { /* * Absolute addr. */ jump = (uint64_t)operand.getImm(); } /* * Output the address relative to the function start, given * that MC will print the addresses relative the current pc. */ debug_printf("\t\t; %lu", (unsigned long)jump); /* * Ignore far jumps given it could be actually a tail return to * a random address. */ if (jump > max_pc && jump < extent) { max_pc = jump; } } } } debug_printf("\n"); /* * Stop disassembling on return statements, if there is no record of a * jump to a successive address. */ if (TID.isReturn()) { if (pc > max_pc) { break; } } } /* * Print GDB command, useful to verify output. */ if (0) { debug_printf("disassemble %p %p\n", bytes, bytes + pc); } debug_printf("\n"); #else /* HAVE_LLVM < 0x0207 */ (void)func; #endif /* HAVE_LLVM < 0x0207 */ } <commit_msg>gallivm: Add constructor for raw_debug_ostream.<commit_after>/************************************************************************** * * Copyright 2009-2011 VMware, Inc. * All Rights Reserved. * * 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, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS 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 <stddef.h> #include <llvm-c/Core.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Target/TargetInstrInfo.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/MemoryObject.h> #if HAVE_LLVM >= 0x0300 #include <llvm/Support/TargetRegistry.h> #else /* HAVE_LLVM < 0x0300 */ #include <llvm/Target/TargetRegistry.h> #endif /* HAVE_LLVM < 0x0300 */ #if HAVE_LLVM >= 0x0209 #include <llvm/Support/Host.h> #else /* HAVE_LLVM < 0x0209 */ #include <llvm/System/Host.h> #endif /* HAVE_LLVM < 0x0209 */ #if HAVE_LLVM >= 0x0207 #include <llvm/MC/MCDisassembler.h> #include <llvm/MC/MCAsmInfo.h> #include <llvm/MC/MCInst.h> #include <llvm/MC/MCInstPrinter.h> #endif /* HAVE_LLVM >= 0x0207 */ #if HAVE_LLVM >= 0x0301 #include <llvm/MC/MCRegisterInfo.h> #endif /* HAVE_LLVM >= 0x0301 */ #include "util/u_math.h" #include "util/u_debug.h" #include "lp_bld_debug.h" /** * Check alignment. * * It is important that this check is not implemented as a macro or inlined * function, as the compiler assumptions in respect to alignment of global * and stack variables would often make the check a no op, defeating the * whole purpose of the exercise. */ extern "C" boolean lp_check_alignment(const void *ptr, unsigned alignment) { assert(util_is_power_of_two(alignment)); return ((uintptr_t)ptr & (alignment - 1)) == 0; } class raw_debug_ostream : public llvm::raw_ostream { private: uint64_t pos; public: raw_debug_ostream() : pos(0) { } void write_impl(const char *Ptr, size_t Size); #if HAVE_LLVM >= 0x207 uint64_t current_pos() const { return pos; } size_t preferred_buffer_size() const { return 512; } #else uint64_t current_pos() { return pos; } size_t preferred_buffer_size() { return 512; } #endif }; void raw_debug_ostream::write_impl(const char *Ptr, size_t Size) { if (Size > 0) { char *lastPtr = (char *)&Ptr[Size]; char last = *lastPtr; *lastPtr = 0; _debug_printf("%*s", Size, Ptr); *lastPtr = last; pos += Size; } } /** * Same as LLVMDumpValue, but through our debugging channels. */ extern "C" void lp_debug_dump_value(LLVMValueRef value) { #if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED) raw_debug_ostream os; llvm::unwrap(value)->print(os); os.flush(); #else LLVMDumpValue(value); #endif } #if HAVE_LLVM >= 0x0207 /* * MemoryObject wrapper around a buffer of memory, to be used by MC * disassembler. */ class BufferMemoryObject: public llvm::MemoryObject { private: const uint8_t *Bytes; uint64_t Length; public: BufferMemoryObject(const uint8_t *bytes, uint64_t length) : Bytes(bytes), Length(length) { } uint64_t getBase() const { return 0; } uint64_t getExtent() const { return Length; } int readByte(uint64_t addr, uint8_t *byte) const { if (addr > getExtent()) return -1; *byte = Bytes[addr]; return 0; } }; #endif /* HAVE_LLVM >= 0x0207 */ /* * Disassemble a function, using the LLVM MC disassembler. * * See also: * - http://blog.llvm.org/2010/01/x86-disassembler.html * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html */ extern "C" void lp_disassemble(const void* func) { #if HAVE_LLVM >= 0x0207 using namespace llvm; const uint8_t *bytes = (const uint8_t *)func; /* * Limit disassembly to this extent */ const uint64_t extent = 96 * 1024; uint64_t max_pc = 0; /* * Initialize all used objects. */ #if HAVE_LLVM >= 0x0301 std::string Triple = sys::getDefaultTargetTriple(); #else std::string Triple = sys::getHostTriple(); #endif std::string Error; const Target *T = TargetRegistry::lookupTarget(Triple, Error); #if HAVE_LLVM >= 0x0300 OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple)); #else OwningPtr<const MCAsmInfo> AsmInfo(T->createAsmInfo(Triple)); #endif if (!AsmInfo) { debug_printf("error: no assembly info for target %s\n", Triple.c_str()); return; } #if HAVE_LLVM >= 0x0300 const MCSubtargetInfo *STI = T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""); OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI)); #else OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler()); #endif if (!DisAsm) { debug_printf("error: no disassembler for target %s\n", Triple.c_str()); return; } raw_debug_ostream Out; #if HAVE_LLVM >= 0x0300 unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); #else int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); #endif #if HAVE_LLVM >= 0x0301 OwningPtr<const MCRegisterInfo> MRI(T->createMCRegInfo(Triple)); if (!MRI) { debug_printf("error: no register info for target %s\n", Triple.c_str()); return; } OwningPtr<const MCInstrInfo> MII(T->createMCInstrInfo()); if (!MII) { debug_printf("error: no instruction info for target %s\n", Triple.c_str()); return; } #endif #if HAVE_LLVM >= 0x0301 OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI)); #elif HAVE_LLVM == 0x0300 OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *STI)); #elif HAVE_LLVM >= 0x0208 OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo)); #else OwningPtr<MCInstPrinter> Printer( T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, Out)); #endif if (!Printer) { debug_printf("error: no instruction printer for target %s\n", Triple.c_str()); return; } #if HAVE_LLVM >= 0x0301 TargetOptions options; #if defined(DEBUG) options.JITEmitDebugInfo = true; #endif #if defined(PIPE_ARCH_X86) options.StackAlignmentOverride = 4; #endif #if defined(DEBUG) || defined(PROFILE) options.NoFramePointerElim = true; #endif TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), "", options); #elif HAVE_LLVM == 0x0300 TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), ""); #else TargetMachine *TM = T->createTargetMachine(Triple, ""); #endif const TargetInstrInfo *TII = TM->getInstrInfo(); /* * Wrap the data in a MemoryObject */ BufferMemoryObject memoryObject((const uint8_t *)bytes, extent); uint64_t pc; pc = 0; while (true) { MCInst Inst; uint64_t Size; /* * Print address. We use addresses relative to the start of the function, * so that between runs. */ debug_printf("%6lu:\t", (unsigned long)pc); if (!DisAsm->getInstruction(Inst, Size, memoryObject, pc, #if HAVE_LLVM >= 0x0300 nulls(), nulls())) { #else nulls())) { #endif debug_printf("invalid\n"); pc += 1; } /* * Output the bytes in hexidecimal format. */ if (0) { unsigned i; for (i = 0; i < Size; ++i) { debug_printf("%02x ", ((const uint8_t*)bytes)[pc + i]); } for (; i < 16; ++i) { debug_printf(" "); } } /* * Print the instruction. */ #if HAVE_LLVM >= 0x0300 Printer->printInst(&Inst, Out, ""); #elif HAVE_LLVM >= 0x208 Printer->printInst(&Inst, Out); #else Printer->printInst(&Inst); #endif Out.flush(); /* * Advance. */ pc += Size; #if HAVE_LLVM >= 0x0300 const MCInstrDesc &TID = TII->get(Inst.getOpcode()); #else const TargetInstrDesc &TID = TII->get(Inst.getOpcode()); #endif /* * Keep track of forward jumps to a nearby address. */ if (TID.isBranch()) { for (unsigned i = 0; i < Inst.getNumOperands(); ++i) { const MCOperand &operand = Inst.getOperand(i); if (operand.isImm()) { uint64_t jump; /* * FIXME: Handle both relative and absolute addresses correctly. * EDInstInfo actually has this info, but operandTypes and * operandFlags enums are not exposed in the public interface. */ if (1) { /* * PC relative addr. */ jump = pc + operand.getImm(); } else { /* * Absolute addr. */ jump = (uint64_t)operand.getImm(); } /* * Output the address relative to the function start, given * that MC will print the addresses relative the current pc. */ debug_printf("\t\t; %lu", (unsigned long)jump); /* * Ignore far jumps given it could be actually a tail return to * a random address. */ if (jump > max_pc && jump < extent) { max_pc = jump; } } } } debug_printf("\n"); /* * Stop disassembling on return statements, if there is no record of a * jump to a successive address. */ if (TID.isReturn()) { if (pc > max_pc) { break; } } } /* * Print GDB command, useful to verify output. */ if (0) { debug_printf("disassemble %p %p\n", bytes, bytes + pc); } debug_printf("\n"); #else /* HAVE_LLVM < 0x0207 */ (void)func; #endif /* HAVE_LLVM < 0x0207 */ } <|endoftext|>
<commit_before>/* * DefaultPatternMatchCB.cc * * Copyright (C) 2008,2009,2014 Linas Vepstas * * Author: Linas Vepstas <linasvepstas@gmail.com> February 2008 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "DefaultPatternMatchCB.h" #include "PatternMatchEngine.h" #include <opencog/atomspace/Foreach.h> using namespace opencog; // #define DEBUG 1 #if DEBUG #define dbgprt(f, varargs...) printf(f, ##varargs) #else #define dbgprt(f, varargs...) #endif /* ======================================================== */ // Find a good place to start the search. // // The handle h points to a clause. In principle, it is enough to // simply find a constant in the clause, and just start there. In // practice, this can be an awful way to do things. So, for example, // most "typical" clauses will be of the form // // EvaluationLink // PredicteNode "blah" // ListLink // VariableNode $var // ConceptNode "item" // // Typically, the incoming set to "blah" will be huge, so starting the // search there would be a poor choice. Typically, the incoming set to // "item" will be much smaller, and so makes a better choice. The code // below tries to pass over "blah" and pick "item" instead. It does so // by comparing the size of the incoming sets of the two constants, and // picking the one with the smaller ("thinner") incoming set. Note that // this is a form of "greedy" search. // // Note that the algo performs a full-depth search to find this. That's // OK, because typeical clauses are never deep. // // Note that the size of the incoming set really is a better measure, // and not the depth. So, for example, if "item" has a huge incoming // set, but "blah" does not, then "blah" is a much better place to // start. // // size_t& depth will be set to the depth of the thinnest constant found. // Handle& start will be set to the link containing that constant. // size_t& width will be set to the incoming-set size of the thinnest // constant found. // The returned value will be the constant at which to start the search. // If no constant is found, then the returned value is the undefnied // handle. // Handle DefaultPatternMatchCB::find_starter(Handle h, size_t& depth, Handle& start, size_t& width) { // If its a node, then we are done. Don't modiy either depth or // start. Type t = h->getType(); if (classserver().isNode(t)) { if (t != VARIABLE_NODE) { width = h->getIncomingSetSize(); return h; } return Handle::UNDEFINED; } size_t deepest = depth; start = Handle::UNDEFINED; Handle hdeepest(Handle::UNDEFINED); size_t thinnest = SIZE_MAX; // Iterate over all the handles in the outgoing set. // Find the deepest one that contains a constant, and start // the search there. If there are two at the same depth, // then start with the skinnier one. LinkPtr ll(LinkCast(h)); const std::vector<Handle> &vh = ll->getOutgoingSet(); for (size_t i = 0; i < vh.size(); i++) { size_t brdepth = depth + 1; size_t brwid = SIZE_MAX; Handle sbr(h); Handle s(find_starter(vh[i], brdepth, sbr, brwid)); if (s != Handle::UNDEFINED and (brwid < thinnest or (brwid == thinnest and deepest < brdepth))) { deepest = brdepth; hdeepest = s; start = sbr; thinnest = brwid; } } depth = deepest; width = thinnest; return hdeepest; } /** * Search for solutions/groundings over all of the AtomSpace, using * some "reasonable" assumptions for what might be searched for. Or, * to put it bluntly, this search method *might* miss some possible * solutions, for certain "unusual" search types. The trade-off is * that this search algo should really be quite fast for "normal" * search types. * * This search algo makes the following (important) assumptions: * * 1) If there are no variables in the clauses, then this will search * over all links which have the same type as the first clause. * Clearly, this kind of search can fail if link_match() callback * was prepared to accept other link types as well. * * 2) If there are variables, then the search will begin at the first * non-variable node in the first clause. The search will proceed * by exploring the entire incoming-set for this node, but no farther. * If the node_match() callback is willing to accept a broader range * of node matches, esp for this initial node, then many possible * solutions will be missed. * * 3) If the clauses consist entirely of variables, the same search * as described in 1) will be performed. * * The above describes the limits to the "typical" search that this * algo can do well. In particular, if the constraint of 2) can be met, * then the search can be quite rapid, since incoming sets are often * quite small; and assumption 2) limits the search to "nearby", * connected atoms. * * Note that the default implementation of node_match() and link_match() * in this class does satisfy both 1) and 2), so this algo will work * correctly if these two methods are not overloaded. * * If you overload node_match(), and do so in a way that breaks * assumption 2), then you will scratch your head, thinking * "why did my search fail to find this obvious solution?" The answer * will be for you to create a new search algo, in a new class, that * overloads this one, and does what you want it to. This class should * probably *not* be modified, since it is quite efficient for the * "normal" case. */ void DefaultPatternMatchCB::perform_search(PatternMatchEngine *pme, std::set<Handle> &vars, std::vector<Handle> &clauses, std::vector<Handle> &negations) { // In principle, we could start our search at some node, any node, // that is not a variable. In practice, the search begins by // iterating over the incoming set of the node, and so, if it is // large, a huge amount of effort might be wasted exploring // dead-ends. Thus, it pays off to start the search on the // node with the smallest ("narrowest" or "thinnest") incoming set // possible. Thus, we look at all the clauses, to find the // "thinnest" one. // // Note also: the user is allowed to specify patterns that have // no constants in them at all. In this case, the search is // performed by looping over all links of the given types. size_t thinnest = SIZE_MAX; size_t deepest = 0; size_t bestclause = 0; Handle best_start(Handle::UNDEFINED); _starter_pred = Handle::UNDEFINED; size_t nc = clauses.size(); for (size_t i=0; i < nc; i++) { Handle h(clauses[i]); size_t depth = 0; size_t width = SIZE_MAX; Handle pred(Handle::UNDEFINED); Handle start(find_starter(h, depth, pred, width)); if (start != Handle::UNDEFINED and (width < thinnest or (width == thinnest and depth > deepest))) { thinnest = width; deepest = depth; bestclause = i; best_start = start; _starter_pred = pred; } } if ((Handle::UNDEFINED != best_start) && (0 != vars.size())) { _root = clauses[bestclause]; dbgprt("Search start node: %s\n", best_start->toShortString().c_str()); dbgprt("Start pred is: %s\n", _starter_pred->toShortString().c_str()); IncomingSet iset = get_incoming_set(best_start); size_t sz = iset.size(); for (size_t i = 0; i < sz; i++) { Handle h(iset[i]); dbgprt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"); dbgprt("Loop candidate: %s\n", h->toShortString().c_str()); bool rc = pme->do_candidate(_root, _starter_pred, h); if (rc) break; } } else { _root = clauses[0]; _starter_pred = _root; dbgprt("Start pred is: %s\n", _starter_pred->toShortString().c_str()); // Get type of the first item in the predicate list. Type ptype = _root->getType(); // Plunge into the deep end - start looking at all viable // candidates in the AtomSpace. // XXX TODO -- as a performance optimization, we should try all // the different clauses, and find the one with the smallest number // of atoms of that type, or otherwise try to find a small ("thin") // incoming set to search over. std::list<Handle> handle_set; _atom_space->getHandlesByType(back_inserter(handle_set), ptype); std::list<Handle>::iterator i = handle_set.begin(); std::list<Handle>::iterator iend = handle_set.end(); for (; i != iend; i++) { Handle h(*i); dbgprt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"); dbgprt("Loop candidate: %s\n", h->toShortString().c_str()); bool rc = pme->do_candidate(_root, _starter_pred, h); if (rc) break; } } } /* ======================================================== */ bool DefaultPatternMatchCB::post_link_match(LinkPtr& lpat, LinkPtr& lsoln) { return false; } /* ===================== END OF FILE ===================== */ <commit_msg>spell error fix<commit_after>/* * DefaultPatternMatchCB.cc * * Copyright (C) 2008,2009,2014 Linas Vepstas * * Author: Linas Vepstas <linasvepstas@gmail.com> February 2008 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "DefaultPatternMatchCB.h" #include "PatternMatchEngine.h" #include <opencog/atomspace/Foreach.h> using namespace opencog; // #define DEBUG 1 #if DEBUG #define dbgprt(f, varargs...) printf(f, ##varargs) #else #define dbgprt(f, varargs...) #endif /* ======================================================== */ // Find a good place to start the search. // // The handle h points to a clause. In principle, it is enough to // simply find a constant in the clause, and just start there. In // practice, this can be an awful way to do things. So, for example, // most "typical" clauses will be of the form // // EvaluationLink // PredicateNode "blah" // ListLink // VariableNode $var // ConceptNode "item" // // Typically, the incoming set to "blah" will be huge, so starting the // search there would be a poor choice. Typically, the incoming set to // "item" will be much smaller, and so makes a better choice. The code // below tries to pass over "blah" and pick "item" instead. It does so // by comparing the size of the incoming sets of the two constants, and // picking the one with the smaller ("thinner") incoming set. Note that // this is a form of "greedy" search. // // Note that the algo performs a full-depth search to find this. That's // OK, because typeical clauses are never deep. // // Note that the size of the incoming set really is a better measure, // and not the depth. So, for example, if "item" has a huge incoming // set, but "blah" does not, then "blah" is a much better place to // start. // // size_t& depth will be set to the depth of the thinnest constant found. // Handle& start will be set to the link containing that constant. // size_t& width will be set to the incoming-set size of the thinnest // constant found. // The returned value will be the constant at which to start the search. // If no constant is found, then the returned value is the undefnied // handle. // Handle DefaultPatternMatchCB::find_starter(Handle h, size_t& depth, Handle& start, size_t& width) { // If its a node, then we are done. Don't modiy either depth or // start. Type t = h->getType(); if (classserver().isNode(t)) { if (t != VARIABLE_NODE) { width = h->getIncomingSetSize(); return h; } return Handle::UNDEFINED; } size_t deepest = depth; start = Handle::UNDEFINED; Handle hdeepest(Handle::UNDEFINED); size_t thinnest = SIZE_MAX; // Iterate over all the handles in the outgoing set. // Find the deepest one that contains a constant, and start // the search there. If there are two at the same depth, // then start with the skinnier one. LinkPtr ll(LinkCast(h)); const std::vector<Handle> &vh = ll->getOutgoingSet(); for (size_t i = 0; i < vh.size(); i++) { size_t brdepth = depth + 1; size_t brwid = SIZE_MAX; Handle sbr(h); Handle s(find_starter(vh[i], brdepth, sbr, brwid)); if (s != Handle::UNDEFINED and (brwid < thinnest or (brwid == thinnest and deepest < brdepth))) { deepest = brdepth; hdeepest = s; start = sbr; thinnest = brwid; } } depth = deepest; width = thinnest; return hdeepest; } /** * Search for solutions/groundings over all of the AtomSpace, using * some "reasonable" assumptions for what might be searched for. Or, * to put it bluntly, this search method *might* miss some possible * solutions, for certain "unusual" search types. The trade-off is * that this search algo should really be quite fast for "normal" * search types. * * This search algo makes the following (important) assumptions: * * 1) If there are no variables in the clauses, then this will search * over all links which have the same type as the first clause. * Clearly, this kind of search can fail if link_match() callback * was prepared to accept other link types as well. * * 2) If there are variables, then the search will begin at the first * non-variable node in the first clause. The search will proceed * by exploring the entire incoming-set for this node, but no farther. * If the node_match() callback is willing to accept a broader range * of node matches, esp for this initial node, then many possible * solutions will be missed. * * 3) If the clauses consist entirely of variables, the same search * as described in 1) will be performed. * * The above describes the limits to the "typical" search that this * algo can do well. In particular, if the constraint of 2) can be met, * then the search can be quite rapid, since incoming sets are often * quite small; and assumption 2) limits the search to "nearby", * connected atoms. * * Note that the default implementation of node_match() and link_match() * in this class does satisfy both 1) and 2), so this algo will work * correctly if these two methods are not overloaded. * * If you overload node_match(), and do so in a way that breaks * assumption 2), then you will scratch your head, thinking * "why did my search fail to find this obvious solution?" The answer * will be for you to create a new search algo, in a new class, that * overloads this one, and does what you want it to. This class should * probably *not* be modified, since it is quite efficient for the * "normal" case. */ void DefaultPatternMatchCB::perform_search(PatternMatchEngine *pme, std::set<Handle> &vars, std::vector<Handle> &clauses, std::vector<Handle> &negations) { // In principle, we could start our search at some node, any node, // that is not a variable. In practice, the search begins by // iterating over the incoming set of the node, and so, if it is // large, a huge amount of effort might be wasted exploring // dead-ends. Thus, it pays off to start the search on the // node with the smallest ("narrowest" or "thinnest") incoming set // possible. Thus, we look at all the clauses, to find the // "thinnest" one. // // Note also: the user is allowed to specify patterns that have // no constants in them at all. In this case, the search is // performed by looping over all links of the given types. size_t thinnest = SIZE_MAX; size_t deepest = 0; size_t bestclause = 0; Handle best_start(Handle::UNDEFINED); _starter_pred = Handle::UNDEFINED; size_t nc = clauses.size(); for (size_t i=0; i < nc; i++) { Handle h(clauses[i]); size_t depth = 0; size_t width = SIZE_MAX; Handle pred(Handle::UNDEFINED); Handle start(find_starter(h, depth, pred, width)); if (start != Handle::UNDEFINED and (width < thinnest or (width == thinnest and depth > deepest))) { thinnest = width; deepest = depth; bestclause = i; best_start = start; _starter_pred = pred; } } if ((Handle::UNDEFINED != best_start) && (0 != vars.size())) { _root = clauses[bestclause]; dbgprt("Search start node: %s\n", best_start->toShortString().c_str()); dbgprt("Start pred is: %s\n", _starter_pred->toShortString().c_str()); IncomingSet iset = get_incoming_set(best_start); size_t sz = iset.size(); for (size_t i = 0; i < sz; i++) { Handle h(iset[i]); dbgprt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"); dbgprt("Loop candidate: %s\n", h->toShortString().c_str()); bool rc = pme->do_candidate(_root, _starter_pred, h); if (rc) break; } } else { _root = clauses[0]; _starter_pred = _root; dbgprt("Start pred is: %s\n", _starter_pred->toShortString().c_str()); // Get type of the first item in the predicate list. Type ptype = _root->getType(); // Plunge into the deep end - start looking at all viable // candidates in the AtomSpace. // XXX TODO -- as a performance optimization, we should try all // the different clauses, and find the one with the smallest number // of atoms of that type, or otherwise try to find a small ("thin") // incoming set to search over. std::list<Handle> handle_set; _atom_space->getHandlesByType(back_inserter(handle_set), ptype); std::list<Handle>::iterator i = handle_set.begin(); std::list<Handle>::iterator iend = handle_set.end(); for (; i != iend; i++) { Handle h(*i); dbgprt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"); dbgprt("Loop candidate: %s\n", h->toShortString().c_str()); bool rc = pme->do_candidate(_root, _starter_pred, h); if (rc) break; } } } /* ======================================================== */ bool DefaultPatternMatchCB::post_link_match(LinkPtr& lpat, LinkPtr& lsoln) { return false; } /* ===================== END OF FILE ===================== */ <|endoftext|>
<commit_before>#ifndef SLA_SUPPORTPOINTGENERATOR_HPP #define SLA_SUPPORTPOINTGENERATOR_HPP #include <random> #include <libslic3r/SLA/SupportPoint.hpp> #include <libslic3r/SLA/IndexedMesh.hpp> #include <libslic3r/BoundingBox.hpp> #include <libslic3r/ClipperUtils.hpp> #include <libslic3r/Point.hpp> #include <boost/container/small_vector.hpp> // #define SLA_SUPPORTPOINTGEN_DEBUG namespace Slic3r { namespace sla { class SupportPointGenerator { public: struct Config { float density_relative {1.f}; float minimal_distance {1.f}; float head_diameter {0.4f}; /////////////// inline float support_force() const { return 7.7f / density_relative; } // a force one point can support (arbitrary force unit) inline float tear_pressure() const { return 1.f; } // pressure that the display exerts (the force unit per mm2) }; SupportPointGenerator(const IndexedMesh& emesh, const std::vector<ExPolygons>& slices, const std::vector<float>& heights, const Config& config, std::function<void(void)> throw_on_cancel, std::function<void(int)> statusfn); SupportPointGenerator(const IndexedMesh& emesh, const Config& config, std::function<void(void)> throw_on_cancel, std::function<void(int)> statusfn); const std::vector<SupportPoint>& output() const { return m_output; } std::vector<SupportPoint>& output() { return m_output; } struct MyLayer; struct Structure { Structure(MyLayer &layer, const ExPolygon& poly, const BoundingBox &bbox, const Vec2f &centroid, float area, float h) : layer(&layer), polygon(&poly), bbox(bbox), centroid(centroid), area(area), zlevel(h) #ifdef SLA_SUPPORTPOINTGEN_DEBUG , unique_id(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())) #endif /* SLA_SUPPORTPOINTGEN_DEBUG */ {} MyLayer *layer; const ExPolygon* polygon = nullptr; const BoundingBox bbox; const Vec2f centroid = Vec2f::Zero(); const float area = 0.f; float zlevel = 0; // How well is this ExPolygon held to the print base? // Positive number, the higher the better. float supports_force_this_layer = 0.f; float supports_force_inherited = 0.f; float supports_force_total() const { return this->supports_force_this_layer + this->supports_force_inherited; } #ifdef SLA_SUPPORTPOINTGEN_DEBUG std::chrono::milliseconds unique_id; #endif /* SLA_SUPPORTPOINTGEN_DEBUG */ struct Link { Link(Structure *island, float overlap_area) : island(island), overlap_area(overlap_area) {} Structure *island; float overlap_area; }; #ifdef NDEBUG // In release mode, use the optimized container. boost::container::small_vector<Link, 4> islands_above; boost::container::small_vector<Link, 4> islands_below; #else // In debug mode, use the standard vector, which is well handled by debugger visualizer. std::vector<Link> islands_above; std::vector<Link> islands_below; #endif // Overhangs, that are dangling considerably. ExPolygons dangling_areas; // Complete overhands. ExPolygons overhangs; // Overhangs, where the surface must slope. ExPolygons overhangs_slopes; float overhangs_area = 0.f; bool overlaps(const Structure &rhs) const { return this->bbox.overlap(rhs.bbox) && (this->polygon->overlaps(*rhs.polygon) || rhs.polygon->overlaps(*this->polygon)); } float overlap_area(const Structure &rhs) const { double out = 0.; if (this->bbox.overlap(rhs.bbox)) { Polygons polys = intersection(to_polygons(*this->polygon), to_polygons(*rhs.polygon), false); for (const Polygon &poly : polys) out += poly.area(); } return float(out); } float area_below() const { float area = 0.f; for (const Link &below : this->islands_below) area += below.island->area; return area; } Polygons polygons_below() const { size_t cnt = 0; for (const Link &below : this->islands_below) cnt += 1 + below.island->polygon->holes.size(); Polygons out; out.reserve(cnt); for (const Link &below : this->islands_below) { out.emplace_back(below.island->polygon->contour); append(out, below.island->polygon->holes); } return out; } ExPolygons expolygons_below() const { ExPolygons out; out.reserve(this->islands_below.size()); for (const Link &below : this->islands_below) out.emplace_back(*below.island->polygon); return out; } // Positive deficit of the supports. If negative, this area is well supported. If positive, more supports need to be added. float support_force_deficit(const float tear_pressure) const { return this->area * tear_pressure - this->supports_force_total(); } }; struct MyLayer { MyLayer(const size_t layer_id, coordf_t print_z) : layer_id(layer_id), print_z(print_z) {} size_t layer_id; coordf_t print_z; std::vector<Structure> islands; }; struct RichSupportPoint { Vec3f position; Structure *island; }; struct PointGrid3D { struct GridHash { std::size_t operator()(const Vec3i &cell_id) const { return std::hash<int>()(cell_id.x()) ^ std::hash<int>()(cell_id.y() * 593) ^ std::hash<int>()(cell_id.z() * 7919); } }; typedef std::unordered_multimap<Vec3i, RichSupportPoint, GridHash> Grid; Vec3f cell_size; Grid grid; Vec3i cell_id(const Vec3f &pos) { return Vec3i(int(floor(pos.x() / cell_size.x())), int(floor(pos.y() / cell_size.y())), int(floor(pos.z() / cell_size.z()))); } void insert(const Vec2f &pos, Structure *island) { RichSupportPoint pt; pt.position = Vec3f(pos.x(), pos.y(), float(island->layer->print_z)); pt.island = island; grid.emplace(cell_id(pt.position), pt); } bool collides_with(const Vec2f &pos, float print_z, float radius) { Vec3f pos3d(pos.x(), pos.y(), print_z); Vec3i cell = cell_id(pos3d); std::pair<Grid::const_iterator, Grid::const_iterator> it_pair = grid.equal_range(cell); if (collides_with(pos3d, radius, it_pair.first, it_pair.second)) return true; for (int i = -1; i < 2; ++ i) for (int j = -1; j < 2; ++ j) for (int k = -1; k < 1; ++ k) { if (i == 0 && j == 0 && k == 0) continue; it_pair = grid.equal_range(cell + Vec3i(i, j, k)); if (collides_with(pos3d, radius, it_pair.first, it_pair.second)) return true; } return false; } private: bool collides_with(const Vec3f &pos, float radius, Grid::const_iterator it_begin, Grid::const_iterator it_end) { for (Grid::const_iterator it = it_begin; it != it_end; ++ it) { float dist2 = (it->second.position - pos).squaredNorm(); if (dist2 < radius * radius) return true; } return false; } }; void execute(const std::vector<ExPolygons> &slices, const std::vector<float> & heights); void seed(std::mt19937::result_type s) { m_rng.seed(s); } private: std::vector<SupportPoint> m_output; SupportPointGenerator::Config m_config; void process(const std::vector<ExPolygons>& slices, const std::vector<float>& heights); public: enum IslandCoverageFlags : uint8_t { icfNone = 0x0, icfIsNew = 0x1, icfBoundaryOnly = 0x2 }; private: void uniformly_cover(const ExPolygons& islands, Structure& structure, float deficit, PointGrid3D &grid3d, IslandCoverageFlags flags = icfNone); void add_support_points(Structure& structure, PointGrid3D &grid3d); void project_onto_mesh(std::vector<SupportPoint>& points) const; #ifdef SLA_SUPPORTPOINTGEN_DEBUG static void output_expolygons(const ExPolygons& expolys, const std::string &filename); static void output_structures(const std::vector<Structure> &structures); #endif // SLA_SUPPORTPOINTGEN_DEBUG const IndexedMesh& m_emesh; std::function<void(void)> m_throw_on_cancel; std::function<void(int)> m_statusfn; std::mt19937 m_rng; }; void remove_bottom_points(std::vector<SupportPoint> &pts, float lvl); std::vector<Vec2f> sample_expolygon(const ExPolygon &expoly, float samples_per_mm2, std::mt19937 &rng); void sample_expolygon_boundary(const ExPolygon &expoly, float samples_per_mm, std::vector<Vec2f> &out, std::mt19937 &rng); }} // namespace Slic3r::sla #endif // SUPPORTPOINTGENERATOR_HPP <commit_msg>Calibration changes to address new algorithm behavior.<commit_after>#ifndef SLA_SUPPORTPOINTGENERATOR_HPP #define SLA_SUPPORTPOINTGENERATOR_HPP #include <random> #include <libslic3r/SLA/SupportPoint.hpp> #include <libslic3r/SLA/IndexedMesh.hpp> #include <libslic3r/BoundingBox.hpp> #include <libslic3r/ClipperUtils.hpp> #include <libslic3r/Point.hpp> #include <boost/container/small_vector.hpp> // #define SLA_SUPPORTPOINTGEN_DEBUG namespace Slic3r { namespace sla { class SupportPointGenerator { public: struct Config { float density_relative {1.f}; float minimal_distance {1.f}; float head_diameter {0.4f}; // Originally calibrated to 7.7f, reduced density by Tamas to 70% which is 11.1 (7.7 / 0.7) to adjust for new algorithm changes in tm_suppt_gen_improve inline float support_force() const { return 11.1f / density_relative; } // a force one point can support (arbitrary force unit) inline float tear_pressure() const { return 1.f; } // pressure that the display exerts (the force unit per mm2) }; SupportPointGenerator(const IndexedMesh& emesh, const std::vector<ExPolygons>& slices, const std::vector<float>& heights, const Config& config, std::function<void(void)> throw_on_cancel, std::function<void(int)> statusfn); SupportPointGenerator(const IndexedMesh& emesh, const Config& config, std::function<void(void)> throw_on_cancel, std::function<void(int)> statusfn); const std::vector<SupportPoint>& output() const { return m_output; } std::vector<SupportPoint>& output() { return m_output; } struct MyLayer; struct Structure { Structure(MyLayer &layer, const ExPolygon& poly, const BoundingBox &bbox, const Vec2f &centroid, float area, float h) : layer(&layer), polygon(&poly), bbox(bbox), centroid(centroid), area(area), zlevel(h) #ifdef SLA_SUPPORTPOINTGEN_DEBUG , unique_id(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch())) #endif /* SLA_SUPPORTPOINTGEN_DEBUG */ {} MyLayer *layer; const ExPolygon* polygon = nullptr; const BoundingBox bbox; const Vec2f centroid = Vec2f::Zero(); const float area = 0.f; float zlevel = 0; // How well is this ExPolygon held to the print base? // Positive number, the higher the better. float supports_force_this_layer = 0.f; float supports_force_inherited = 0.f; float supports_force_total() const { return this->supports_force_this_layer + this->supports_force_inherited; } #ifdef SLA_SUPPORTPOINTGEN_DEBUG std::chrono::milliseconds unique_id; #endif /* SLA_SUPPORTPOINTGEN_DEBUG */ struct Link { Link(Structure *island, float overlap_area) : island(island), overlap_area(overlap_area) {} Structure *island; float overlap_area; }; #ifdef NDEBUG // In release mode, use the optimized container. boost::container::small_vector<Link, 4> islands_above; boost::container::small_vector<Link, 4> islands_below; #else // In debug mode, use the standard vector, which is well handled by debugger visualizer. std::vector<Link> islands_above; std::vector<Link> islands_below; #endif // Overhangs, that are dangling considerably. ExPolygons dangling_areas; // Complete overhands. ExPolygons overhangs; // Overhangs, where the surface must slope. ExPolygons overhangs_slopes; float overhangs_area = 0.f; bool overlaps(const Structure &rhs) const { return this->bbox.overlap(rhs.bbox) && (this->polygon->overlaps(*rhs.polygon) || rhs.polygon->overlaps(*this->polygon)); } float overlap_area(const Structure &rhs) const { double out = 0.; if (this->bbox.overlap(rhs.bbox)) { Polygons polys = intersection(to_polygons(*this->polygon), to_polygons(*rhs.polygon), false); for (const Polygon &poly : polys) out += poly.area(); } return float(out); } float area_below() const { float area = 0.f; for (const Link &below : this->islands_below) area += below.island->area; return area; } Polygons polygons_below() const { size_t cnt = 0; for (const Link &below : this->islands_below) cnt += 1 + below.island->polygon->holes.size(); Polygons out; out.reserve(cnt); for (const Link &below : this->islands_below) { out.emplace_back(below.island->polygon->contour); append(out, below.island->polygon->holes); } return out; } ExPolygons expolygons_below() const { ExPolygons out; out.reserve(this->islands_below.size()); for (const Link &below : this->islands_below) out.emplace_back(*below.island->polygon); return out; } // Positive deficit of the supports. If negative, this area is well supported. If positive, more supports need to be added. float support_force_deficit(const float tear_pressure) const { return this->area * tear_pressure - this->supports_force_total(); } }; struct MyLayer { MyLayer(const size_t layer_id, coordf_t print_z) : layer_id(layer_id), print_z(print_z) {} size_t layer_id; coordf_t print_z; std::vector<Structure> islands; }; struct RichSupportPoint { Vec3f position; Structure *island; }; struct PointGrid3D { struct GridHash { std::size_t operator()(const Vec3i &cell_id) const { return std::hash<int>()(cell_id.x()) ^ std::hash<int>()(cell_id.y() * 593) ^ std::hash<int>()(cell_id.z() * 7919); } }; typedef std::unordered_multimap<Vec3i, RichSupportPoint, GridHash> Grid; Vec3f cell_size; Grid grid; Vec3i cell_id(const Vec3f &pos) { return Vec3i(int(floor(pos.x() / cell_size.x())), int(floor(pos.y() / cell_size.y())), int(floor(pos.z() / cell_size.z()))); } void insert(const Vec2f &pos, Structure *island) { RichSupportPoint pt; pt.position = Vec3f(pos.x(), pos.y(), float(island->layer->print_z)); pt.island = island; grid.emplace(cell_id(pt.position), pt); } bool collides_with(const Vec2f &pos, float print_z, float radius) { Vec3f pos3d(pos.x(), pos.y(), print_z); Vec3i cell = cell_id(pos3d); std::pair<Grid::const_iterator, Grid::const_iterator> it_pair = grid.equal_range(cell); if (collides_with(pos3d, radius, it_pair.first, it_pair.second)) return true; for (int i = -1; i < 2; ++ i) for (int j = -1; j < 2; ++ j) for (int k = -1; k < 1; ++ k) { if (i == 0 && j == 0 && k == 0) continue; it_pair = grid.equal_range(cell + Vec3i(i, j, k)); if (collides_with(pos3d, radius, it_pair.first, it_pair.second)) return true; } return false; } private: bool collides_with(const Vec3f &pos, float radius, Grid::const_iterator it_begin, Grid::const_iterator it_end) { for (Grid::const_iterator it = it_begin; it != it_end; ++ it) { float dist2 = (it->second.position - pos).squaredNorm(); if (dist2 < radius * radius) return true; } return false; } }; void execute(const std::vector<ExPolygons> &slices, const std::vector<float> & heights); void seed(std::mt19937::result_type s) { m_rng.seed(s); } private: std::vector<SupportPoint> m_output; SupportPointGenerator::Config m_config; void process(const std::vector<ExPolygons>& slices, const std::vector<float>& heights); public: enum IslandCoverageFlags : uint8_t { icfNone = 0x0, icfIsNew = 0x1, icfBoundaryOnly = 0x2 }; private: void uniformly_cover(const ExPolygons& islands, Structure& structure, float deficit, PointGrid3D &grid3d, IslandCoverageFlags flags = icfNone); void add_support_points(Structure& structure, PointGrid3D &grid3d); void project_onto_mesh(std::vector<SupportPoint>& points) const; #ifdef SLA_SUPPORTPOINTGEN_DEBUG static void output_expolygons(const ExPolygons& expolys, const std::string &filename); static void output_structures(const std::vector<Structure> &structures); #endif // SLA_SUPPORTPOINTGEN_DEBUG const IndexedMesh& m_emesh; std::function<void(void)> m_throw_on_cancel; std::function<void(int)> m_statusfn; std::mt19937 m_rng; }; void remove_bottom_points(std::vector<SupportPoint> &pts, float lvl); std::vector<Vec2f> sample_expolygon(const ExPolygon &expoly, float samples_per_mm2, std::mt19937 &rng); void sample_expolygon_boundary(const ExPolygon &expoly, float samples_per_mm, std::vector<Vec2f> &out, std::mt19937 &rng); }} // namespace Slic3r::sla #endif // SUPPORTPOINTGENERATOR_HPP <|endoftext|>
<commit_before>/* cclive * Copyright (C) 2010-2013 Toni Gundogdu <legatvs@gmail.com> * * This file is part of cclive <http://cclive.sourceforge.net/>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <ccinternal> #include <iomanip> #include <cstdio> #include <ctime> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/filesystem.hpp> #include <ccquvi> #include <ccoptions> #include <ccfile> #include <cclog> #if defined(SIGWINCH) && defined(TIOCGWINSZ) #define WITH_RESIZE #endif namespace cc { #ifdef WITH_RESIZE static volatile sig_atomic_t recv_sigwinch; static void handle_sigwinch(int s) { recv_sigwinch = 1; } static size_t get_term_width() { const int fd = fileno(stderr); winsize wsz; if (ioctl(fd, TIOCGWINSZ, &wsz) < 0) return 0; return wsz.ws_col; } #endif // WITH_RESIZE namespace po = boost::program_options; progressbar::progressbar(const file& f, const quvi::media& m, const po::variables_map& vm) : _update_interval(1), _expected_bytes(m.content_length()), _initial_bytes(f.initial_length()), _time_started(0), _last_update(0), _term_width(0), _dot_count(0), _count(0), _width(0), _file(f), _done(false), _mode(normal) { if (_initial_bytes > _expected_bytes) _expected_bytes = _initial_bytes; #ifdef WITH_RESIZE signal(SIGWINCH, handle_sigwinch); if (!_term_width || recv_sigwinch) { _term_width = get_term_width(); if (!_term_width) _term_width = default_term_width; } #else _term_width = default_term_width; #endif _width = _term_width; time(&_time_started); ifn_optsw_given(vm, OPT__BACKGROUND) _mode = vm[OPT__PROGRESSBAR].as<cc::progressbar_mode>().value(); else _mode = dotline; const int n = vm[OPT__UPDATE_INTERVAL].as<update_interval>().value(); _update_interval = fabs(static_cast<double>(n)); } static double to_mb(const double bytes) { return bytes/(1024*1024); } namespace pt = boost::posix_time; static std::string to_s(const int secs) { pt::time_duration td = pt::seconds(secs); return pt::to_simple_string(td); } static std::string to_unit(double& rate) { std::string units = "K/s"; if (rate >= 1024.0*1024.0*1024.0) { rate /= 1024.0*1024.0*1024.0; units = "G/s"; } else if (rate >= 1024.0*1024.0) { rate /= 1024.0*1024.0; units = "M/s"; } else rate /= 1024.0; return units; } namespace fs = boost::filesystem; int progressbar::update(double now) { time_t tnow; time(&tnow); const time_t elapsed = tnow - _time_started; bool force_update = false; #ifdef WITH_RESIZE if (recv_sigwinch && _mode == normal) { const size_t old_term_width = _term_width; _term_width = get_term_width(); if (!_term_width) _term_width = default_term_width; if (_term_width != old_term_width) { _width = _term_width; force_update = true; } recv_sigwinch = 0; } #endif // WITH_RESIZE const bool inactive = now == 0; if (!_done) { if ((elapsed - _last_update) < _update_interval && !force_update) { return 0; } } else now = _expected_bytes; // Current size. const double size = (!_done) ? _initial_bytes + now : now; std::stringstream size_s; size_s.setf(std::ios::fixed); size_s << std::setprecision(1) << to_mb(size) << "M"; // Rate. double rate = elapsed ? (now/elapsed):0; std::stringstream rate_s, eta_s; rate_s.setf(std::ios::fixed); eta_s.setf(std::ios::fixed); if (!inactive) { // ETA. std::string eta; if (!_done) { const double left = (_expected_bytes - (now + _initial_bytes)) / rate; eta = to_s(static_cast<int>(left+0.5)); } else { rate = (_expected_bytes - _initial_bytes) / elapsed; eta = to_s(elapsed); } std::string unit = to_unit(rate); rate_s << std::setw(4) << std::setprecision(1) << rate << unit; eta_s << std::setw(6) << eta; } else // ETA: inactive (default). { rate_s << "--.-K/s"; eta_s << "--:--:--"; } // Percent. std::stringstream percent_s; int percent = 0; if (_expected_bytes > 0) { percent = static_cast<int>(100.0*size/_expected_bytes); if (percent < 100) percent_s << std::setw(2) << percent << "%"; else percent_s << "100%"; } // Filename. fs::path p = fs::system_complete(_file.path()); #if BOOST_FILESYSTEM_VERSION > 2 std::string fname = p.filename().string(); #else std::string fname = p.filename(); #endif switch (_mode) { default: case normal: _normal(size_s, rate_s, eta_s, percent, percent_s); break; case dotline: _dotline(size_s, rate_s, eta_s, percent_s); break; case simple: _simple(size_s, percent_s); break; } _last_update = elapsed; _count = now; return 0; } void progressbar::_normal(const std::stringstream& size_s, const std::stringstream& rate_s, const std::stringstream& eta_s, const int percent, const std::stringstream& percent_s) { std::stringstream info; info.setf(std::ios::fixed); info << " " << percent_s.str() << " " << std::setw(4) << size_s.str() << " " << rate_s.str() << " " << eta_s.str(); const size_t space_left = _width - info.str().length() - 1; if (_width <= space_left) return; std::stringstream bar; _render_meter(bar, percent, space_left); bar << info.str(); cc::log << bar.str() << "\r" << std::flush; } void progressbar::_dotline(const std::stringstream& size_s, const std::stringstream& rate_s, const std::stringstream& eta_s, const std::stringstream& percent_s) { #define details \ " " \ << std::setw(6) \ << size_s.str() \ << " " \ << rate_s.str() \ << " " \ << eta_s.str() \ << " " \ << percent_s.str() #define dot \ do { \ cc::log \ << "." \ << (_dot_count % 3 == 0 ? " ":"") \ << std::flush; \ } while (0) ++_dot_count; if (_done) { for (; _dot_count < 31; ++_dot_count) dot; cc::log << details << std::flush; return; } if (_dot_count >= 31) { cc::log << details << std::endl; _dot_count = 0; } #undef details else dot; #undef dot } void progressbar::_simple(const std::stringstream& size_s, const std::stringstream& percent_s) const { cc::log << percent_s.str() << " - " << size_s.str() << " received\r" << std::flush; } void progressbar::_render_meter(std::stringstream& bar, const int percent, const size_t space_left) { const int m = static_cast<int>(space_left*percent/100.0); bar << "["; int i = 0; while (bar.str().length() < space_left) { bar << (i<m ? "#":"-"); ++i; } bar << "]"; } void progressbar::finish() { if (_expected_bytes > 0 && _count + _initial_bytes > _expected_bytes) { _expected_bytes = _initial_bytes + _count; } _done = true; update(-1); } } // namespace cc // vim: set ts=2 sw=2 tw=72 expandtab: <commit_msg>cc::progressbar: Remove unused code<commit_after>/* cclive * Copyright (C) 2010-2013 Toni Gundogdu <legatvs@gmail.com> * * This file is part of cclive <http://cclive.sourceforge.net/>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <ccinternal> #include <iomanip> #include <cstdio> #include <ctime> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/program_options/variables_map.hpp> #include <ccquvi> #include <ccoptions> #include <ccfile> #include <cclog> #if defined(SIGWINCH) && defined(TIOCGWINSZ) #define WITH_RESIZE #endif namespace cc { #ifdef WITH_RESIZE static volatile sig_atomic_t recv_sigwinch; static void handle_sigwinch(int s) { recv_sigwinch = 1; } static size_t get_term_width() { const int fd = fileno(stderr); winsize wsz; if (ioctl(fd, TIOCGWINSZ, &wsz) < 0) return 0; return wsz.ws_col; } #endif // WITH_RESIZE namespace po = boost::program_options; progressbar::progressbar(const file& f, const quvi::media& m, const po::variables_map& vm) : _update_interval(1), _expected_bytes(m.content_length()), _initial_bytes(f.initial_length()), _time_started(0), _last_update(0), _term_width(0), _dot_count(0), _count(0), _width(0), _file(f), _done(false), _mode(normal) { if (_initial_bytes > _expected_bytes) _expected_bytes = _initial_bytes; #ifdef WITH_RESIZE signal(SIGWINCH, handle_sigwinch); if (!_term_width || recv_sigwinch) { _term_width = get_term_width(); if (!_term_width) _term_width = default_term_width; } #else _term_width = default_term_width; #endif _width = _term_width; time(&_time_started); ifn_optsw_given(vm, OPT__BACKGROUND) _mode = vm[OPT__PROGRESSBAR].as<cc::progressbar_mode>().value(); else _mode = dotline; const int n = vm[OPT__UPDATE_INTERVAL].as<update_interval>().value(); _update_interval = fabs(static_cast<double>(n)); } static double to_mb(const double bytes) { return bytes/(1024*1024); } namespace pt = boost::posix_time; static std::string to_s(const int secs) { pt::time_duration td = pt::seconds(secs); return pt::to_simple_string(td); } static std::string to_unit(double& rate) { std::string units = "K/s"; if (rate >= 1024.0*1024.0*1024.0) { rate /= 1024.0*1024.0*1024.0; units = "G/s"; } else if (rate >= 1024.0*1024.0) { rate /= 1024.0*1024.0; units = "M/s"; } else rate /= 1024.0; return units; } namespace fs = boost::filesystem; int progressbar::update(double now) { time_t tnow; time(&tnow); const time_t elapsed = tnow - _time_started; bool force_update = false; #ifdef WITH_RESIZE if (recv_sigwinch && _mode == normal) { const size_t old_term_width = _term_width; _term_width = get_term_width(); if (!_term_width) _term_width = default_term_width; if (_term_width != old_term_width) { _width = _term_width; force_update = true; } recv_sigwinch = 0; } #endif // WITH_RESIZE const bool inactive = now == 0; if (!_done) { if ((elapsed - _last_update) < _update_interval && !force_update) { return 0; } } else now = _expected_bytes; // Current size. const double size = (!_done) ? _initial_bytes + now : now; std::stringstream size_s; size_s.setf(std::ios::fixed); size_s << std::setprecision(1) << to_mb(size) << "M"; // Rate. double rate = elapsed ? (now/elapsed):0; std::stringstream rate_s, eta_s; rate_s.setf(std::ios::fixed); eta_s.setf(std::ios::fixed); if (!inactive) { // ETA. std::string eta; if (!_done) { const double left = (_expected_bytes - (now + _initial_bytes)) / rate; eta = to_s(static_cast<int>(left+0.5)); } else { rate = (_expected_bytes - _initial_bytes) / elapsed; eta = to_s(elapsed); } std::string unit = to_unit(rate); rate_s << std::setw(4) << std::setprecision(1) << rate << unit; eta_s << std::setw(6) << eta; } else // ETA: inactive (default). { rate_s << "--.-K/s"; eta_s << "--:--:--"; } // Percent. std::stringstream percent_s; int percent = 0; if (_expected_bytes > 0) { percent = static_cast<int>(100.0*size/_expected_bytes); if (percent < 100) percent_s << std::setw(2) << percent << "%"; else percent_s << "100%"; } switch (_mode) { default: case normal: _normal(size_s, rate_s, eta_s, percent, percent_s); break; case dotline: _dotline(size_s, rate_s, eta_s, percent_s); break; case simple: _simple(size_s, percent_s); break; } _last_update = elapsed; _count = now; return 0; } void progressbar::_normal(const std::stringstream& size_s, const std::stringstream& rate_s, const std::stringstream& eta_s, const int percent, const std::stringstream& percent_s) { std::stringstream info; info.setf(std::ios::fixed); info << " " << percent_s.str() << " " << std::setw(4) << size_s.str() << " " << rate_s.str() << " " << eta_s.str(); const size_t space_left = _width - info.str().length() - 1; if (_width <= space_left) return; std::stringstream bar; _render_meter(bar, percent, space_left); bar << info.str(); cc::log << bar.str() << "\r" << std::flush; } void progressbar::_dotline(const std::stringstream& size_s, const std::stringstream& rate_s, const std::stringstream& eta_s, const std::stringstream& percent_s) { #define details \ " " \ << std::setw(6) \ << size_s.str() \ << " " \ << rate_s.str() \ << " " \ << eta_s.str() \ << " " \ << percent_s.str() #define dot \ do { \ cc::log \ << "." \ << (_dot_count % 3 == 0 ? " ":"") \ << std::flush; \ } while (0) ++_dot_count; if (_done) { for (; _dot_count < 31; ++_dot_count) dot; cc::log << details << std::flush; return; } if (_dot_count >= 31) { cc::log << details << std::endl; _dot_count = 0; } #undef details else dot; #undef dot } void progressbar::_simple(const std::stringstream& size_s, const std::stringstream& percent_s) const { cc::log << percent_s.str() << " - " << size_s.str() << " received\r" << std::flush; } void progressbar::_render_meter(std::stringstream& bar, const int percent, const size_t space_left) { const int m = static_cast<int>(space_left*percent/100.0); bar << "["; int i = 0; while (bar.str().length() < space_left) { bar << (i<m ? "#":"-"); ++i; } bar << "]"; } void progressbar::finish() { if (_expected_bytes > 0 && _count + _initial_bytes > _expected_bytes) { _expected_bytes = _initial_bytes + _count; } _done = true; update(-1); } } // namespace cc // vim: set ts=2 sw=2 tw=72 expandtab: <|endoftext|>
<commit_before>//===-- X86AsmPrinter.cpp - Convert X86 LLVM IR to X86 assembly -----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file the shared super class printer that converts from our internal // representation of machine-dependent LLVM code to Intel and AT&T format // assembly language. // This printer is the output mechanism used by `llc'. // //===----------------------------------------------------------------------===// #include "X86ATTAsmPrinter.h" #include "X86IntelAsmPrinter.h" #include "X86Subtarget.h" #include "X86.h" #include "llvm/Constants.h" #include "llvm/Module.h" #include "llvm/Type.h" #include "llvm/Assembly/Writer.h" #include "llvm/Support/Mangler.h" #include "llvm/Support/CommandLine.h" using namespace llvm; using namespace x86; Statistic<> llvm::x86::EmittedInsts("asm-printer", "Number of machine instrs printed"); enum AsmWriterFlavorTy { att, intel }; cl::opt<AsmWriterFlavorTy> AsmWriterFlavor("x86-asm-syntax", cl::desc("Choose style of code to emit from X86 backend:"), cl::values( clEnumVal(att, " Emit AT&T-style assembly"), clEnumVal(intel, " Emit Intel-style assembly"), clEnumValEnd), cl::init(att)); /// doInitialization bool X86SharedAsmPrinter::doInitialization(Module &M) { const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>(); forDarwin = false; switch (Subtarget->TargetType) { case X86Subtarget::isDarwin: AlignmentIsInBytes = false; GlobalPrefix = "_"; Data64bitsDirective = 0; // we can't emit a 64-bit unit ZeroDirective = "\t.space\t"; // ".space N" emits N zeros. PrivateGlobalPrefix = "L"; // Marker for constant pool idxs ConstantPoolSection = "\t.const\n"; LCOMMDirective = "\t.lcomm\t"; COMMDirectiveTakesAlignment = false; HasDotTypeDotSizeDirective = false; forDarwin = true; StaticCtorsSection = ".mod_init_func"; StaticDtorsSection = ".mod_term_func"; break; case X86Subtarget::isCygwin: GlobalPrefix = "_"; COMMDirectiveTakesAlignment = false; HasDotTypeDotSizeDirective = false; break; case X86Subtarget::isWindows: GlobalPrefix = "_"; HasDotTypeDotSizeDirective = false; break; default: break; } return AsmPrinter::doInitialization(M); } bool X86SharedAsmPrinter::doFinalization(Module &M) { const TargetData &TD = TM.getTargetData(); // Print out module-level global variables here. for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) { if (!I->hasInitializer()) continue; // External global require no code // Check to see if this is a special global used by LLVM, if so, emit it. if (I->hasAppendingLinkage() && EmitSpecialLLVMGlobal(I)) continue; std::string name = Mang->getValueName(I); Constant *C = I->getInitializer(); unsigned Size = TD.getTypeSize(C->getType()); unsigned Align = getPreferredAlignmentLog(I); if (C->isNullValue() && /* FIXME: Verify correct */ (I->hasInternalLinkage() || I->hasWeakLinkage() || I->hasLinkOnceLinkage())) { if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. if (forDarwin) { SwitchSection(".data", I); if (I->hasInternalLinkage()) O << LCOMMDirective << name << "," << Size << "," << Align; else O << COMMDirective << name << "," << Size; } else { SwitchSection(".local", I); O << COMMDirective << name << "," << Size; if (COMMDirectiveTakesAlignment) O << "," << (AlignmentIsInBytes ? (1 << Align) : Align); } O << "\t\t" << CommentString << " '" << I->getName() << "'\n"; } else { switch (I->getLinkage()) { case GlobalValue::LinkOnceLinkage: case GlobalValue::WeakLinkage: if (forDarwin) { O << "\t.globl " << name << '\n' << "\t.weak_definition " << name << '\n'; SwitchSection(".section __DATA,__datacoal_nt,coalesced", I); } else { O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n"; O << "\t.weak " << name << "\n"; } break; case GlobalValue::AppendingLinkage: // FIXME: appending linkage variables should go into a section of // their name or something. For now, just emit them as external. case GlobalValue::ExternalLinkage: // If external or appending, declare as a global symbol O << "\t.globl " << name << "\n"; // FALL THROUGH case GlobalValue::InternalLinkage: SwitchSection(".data", I); break; default: assert(0 && "Unknown linkage type!"); } EmitAlignment(Align, I); O << name << ":\t\t\t\t" << CommentString << " '" << I->getName() << "'\n"; EmitGlobalConstant(C); O << '\n'; } } if (forDarwin) { SwitchSection("", 0); // Output stubs for dynamically-linked functions unsigned j = 1; for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end(); i != e; ++i, ++j) { SwitchSection(".section __IMPORT,__jump_table,symbol_stubs," "self_modifying_code+pure_instructions,5", 0); O << "L" << *i << "$stub:\n"; O << "\t.indirect_symbol " << *i << "\n"; O << "\thlt ; hlt ; hlt ; hlt ; hlt\n"; } O << "\n"; // Output stubs for external and common global variables. if (GVStubs.begin() != GVStubs.end()) SwitchSection(".section __IMPORT,__pointers,non_lazy_symbol_pointers", 0); for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end(); i != e; ++i) { O << "L" << *i << "$non_lazy_ptr:\n"; O << "\t.indirect_symbol " << *i << "\n"; O << "\t.long\t0\n"; } } AsmPrinter::doFinalization(M); return false; // success } /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code /// for a MachineFunction to the given output stream, using the given target /// machine description. /// FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){ switch (AsmWriterFlavor) { default: assert(0 && "Unknown asm flavor!"); case intel: return new X86IntelAsmPrinter(o, tm); case att: return new X86ATTAsmPrinter(o, tm); } } <commit_msg>Fixed a local common symbol bug.<commit_after>//===-- X86AsmPrinter.cpp - Convert X86 LLVM IR to X86 assembly -----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file the shared super class printer that converts from our internal // representation of machine-dependent LLVM code to Intel and AT&T format // assembly language. // This printer is the output mechanism used by `llc'. // //===----------------------------------------------------------------------===// #include "X86ATTAsmPrinter.h" #include "X86IntelAsmPrinter.h" #include "X86Subtarget.h" #include "X86.h" #include "llvm/Constants.h" #include "llvm/Module.h" #include "llvm/Type.h" #include "llvm/Assembly/Writer.h" #include "llvm/Support/Mangler.h" #include "llvm/Support/CommandLine.h" using namespace llvm; using namespace x86; Statistic<> llvm::x86::EmittedInsts("asm-printer", "Number of machine instrs printed"); enum AsmWriterFlavorTy { att, intel }; cl::opt<AsmWriterFlavorTy> AsmWriterFlavor("x86-asm-syntax", cl::desc("Choose style of code to emit from X86 backend:"), cl::values( clEnumVal(att, " Emit AT&T-style assembly"), clEnumVal(intel, " Emit Intel-style assembly"), clEnumValEnd), cl::init(att)); /// doInitialization bool X86SharedAsmPrinter::doInitialization(Module &M) { const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>(); forDarwin = false; switch (Subtarget->TargetType) { case X86Subtarget::isDarwin: AlignmentIsInBytes = false; GlobalPrefix = "_"; Data64bitsDirective = 0; // we can't emit a 64-bit unit ZeroDirective = "\t.space\t"; // ".space N" emits N zeros. PrivateGlobalPrefix = "L"; // Marker for constant pool idxs ConstantPoolSection = "\t.const\n"; LCOMMDirective = "\t.lcomm\t"; COMMDirectiveTakesAlignment = false; HasDotTypeDotSizeDirective = false; forDarwin = true; StaticCtorsSection = ".mod_init_func"; StaticDtorsSection = ".mod_term_func"; break; case X86Subtarget::isCygwin: GlobalPrefix = "_"; COMMDirectiveTakesAlignment = false; HasDotTypeDotSizeDirective = false; break; case X86Subtarget::isWindows: GlobalPrefix = "_"; HasDotTypeDotSizeDirective = false; break; default: break; } return AsmPrinter::doInitialization(M); } bool X86SharedAsmPrinter::doFinalization(Module &M) { const TargetData &TD = TM.getTargetData(); // Print out module-level global variables here. for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) { if (!I->hasInitializer()) continue; // External global require no code // Check to see if this is a special global used by LLVM, if so, emit it. if (I->hasAppendingLinkage() && EmitSpecialLLVMGlobal(I)) continue; std::string name = Mang->getValueName(I); Constant *C = I->getInitializer(); unsigned Size = TD.getTypeSize(C->getType()); unsigned Align = getPreferredAlignmentLog(I); if (C->isNullValue() && /* FIXME: Verify correct */ (I->hasInternalLinkage() || I->hasWeakLinkage() || I->hasLinkOnceLinkage())) { if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. SwitchSection(".data", I); if (LCOMMDirective != NULL) { if (I->hasInternalLinkage()) { O << LCOMMDirective << name << "," << Size; if (forDarwin) O << "," << (AlignmentIsInBytes ? (1 << Align) : Align); } else O << COMMDirective << name << "," << Size; } else { if (I->hasInternalLinkage()) O <<"\t.local\t" << name << "\n"; O << COMMDirective << name << "," << Size; if (COMMDirectiveTakesAlignment) O << "," << (AlignmentIsInBytes ? (1 << Align) : Align); } O << "\t\t" << CommentString << " " << I->getName() << "\n"; } else { switch (I->getLinkage()) { case GlobalValue::LinkOnceLinkage: case GlobalValue::WeakLinkage: if (forDarwin) { O << "\t.globl " << name << "\n" << "\t.weak_definition " << name << "\n"; SwitchSection(".section __DATA,__datacoal_nt,coalesced", I); } else { O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n"; O << "\t.weak " << name << "\n"; } break; case GlobalValue::AppendingLinkage: // FIXME: appending linkage variables should go into a section of // their name or something. For now, just emit them as external. case GlobalValue::ExternalLinkage: // If external or appending, declare as a global symbol O << "\t.globl " << name << "\n"; // FALL THROUGH case GlobalValue::InternalLinkage: SwitchSection(".data", I); break; default: assert(0 && "Unknown linkage type!"); } EmitAlignment(Align, I); O << name << ":\t\t\t\t" << CommentString << " " << I->getName() << "\n"; if (HasDotTypeDotSizeDirective) O << "\t.size " << name << ", " << Size << "\n"; EmitGlobalConstant(C); O << '\n'; } } if (forDarwin) { SwitchSection("", 0); // Output stubs for dynamically-linked functions unsigned j = 1; for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end(); i != e; ++i, ++j) { SwitchSection(".section __IMPORT,__jump_table,symbol_stubs," "self_modifying_code+pure_instructions,5", 0); O << "L" << *i << "$stub:\n"; O << "\t.indirect_symbol " << *i << "\n"; O << "\thlt ; hlt ; hlt ; hlt ; hlt\n"; } O << "\n"; // Output stubs for external and common global variables. if (GVStubs.begin() != GVStubs.end()) SwitchSection(".section __IMPORT,__pointers,non_lazy_symbol_pointers", 0); for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end(); i != e; ++i) { O << "L" << *i << "$non_lazy_ptr:\n"; O << "\t.indirect_symbol " << *i << "\n"; O << "\t.long\t0\n"; } } AsmPrinter::doFinalization(M); return false; // success } /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code /// for a MachineFunction to the given output stream, using the given target /// machine description. /// FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){ switch (AsmWriterFlavor) { default: assert(0 && "Unknown asm flavor!"); case intel: return new X86IntelAsmPrinter(o, tm); case att: return new X86ATTAsmPrinter(o, tm); } } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #define GLOG_NO_ABBREVIATED_SEVERITIES #include "paddle/fluid/memory/detail/system_allocator.h" #ifdef _WIN32 #include <malloc.h> #include <windows.h> // VirtualLock/VirtualUnlock #else #include <sys/mman.h> // for mlock and munlock #endif #include <stdlib.h> // for malloc and free #include <algorithm> // for std::max #include <string> #include <utility> #include "gflags/gflags.h" #include "paddle/fluid/memory/allocation/allocator.h" #include "paddle/fluid/platform/cpu_info.h" #include "paddle/fluid/platform/enforce.h" #include "paddle/fluid/platform/gpu_info.h" #ifdef PADDLE_WITH_CUDA #include "paddle/fluid/platform/cuda_device_guard.h" #endif DECLARE_bool(use_pinned_memory); DECLARE_double(fraction_of_gpu_memory_to_use); DECLARE_uint64(initial_gpu_memory_in_mb); DECLARE_uint64(reallocate_gpu_memory_in_mb); namespace paddle { namespace memory { namespace detail { void* AlignedMalloc(size_t size) { void* p = nullptr; size_t alignment = 32ul; #ifdef PADDLE_WITH_MKLDNN // refer to https://github.com/01org/mkl-dnn/blob/master/include/mkldnn.hpp // memory alignment alignment = 4096ul; #endif #ifdef _WIN32 p = _aligned_malloc(size, alignment); #else PADDLE_ENFORCE_EQ(posix_memalign(&p, alignment, size), 0, "Alloc %ld error!", size); #endif PADDLE_ENFORCE_NOT_NULL(p, "Fail to allocate CPU memory: size = %d .", size); return p; } void* CPUAllocator::Alloc(size_t* index, size_t size) { // According to http://www.cplusplus.com/reference/cstdlib/malloc/, // malloc might not return nullptr if size is zero, but the returned // pointer shall not be dereferenced -- so we make it nullptr. if (size <= 0) return nullptr; *index = 0; // unlock memory void* p = AlignedMalloc(size); if (p != nullptr) { if (FLAGS_use_pinned_memory) { *index = 1; #ifdef _WIN32 VirtualLock(p, size); #else mlock(p, size); // lock memory #endif } } return p; } void CPUAllocator::Free(void* p, size_t size, size_t index) { if (p != nullptr && index == 1) { #ifdef _WIN32 VirtualUnlock(p, size); #else munlock(p, size); #endif } #ifdef _WIN32 _aligned_free(p); #else free(p); #endif } bool CPUAllocator::UseGpu() const { return false; } #ifdef PADDLE_WITH_CUDA void* GPUAllocator::Alloc(size_t* index, size_t size) { // CUDA documentation doesn't explain if cudaMalloc returns nullptr // if size is 0. We just make sure it does. if (size <= 0) return nullptr; paddle::platform::CUDADeviceGuard guard(gpu_id_); void* p; cudaError_t result = cudaMalloc(&p, size); if (result == cudaSuccess) { *index = 0; gpu_alloc_size_ += size; return p; } else { PADDLE_ENFORCE_NE(cudaGetLastError(), cudaSuccess); size_t avail, total; platform::GpuMemoryUsage(&avail, &total); PADDLE_THROW_BAD_ALLOC( "\n\nOut of memory error on GPU %d. " "Cannot allocate %s memory on GPU %d, " "available memory is only %s.\n\n" "Please check whether there is any other process using GPU %d.\n" "1. If yes, please stop them, or start PaddlePaddle on another GPU.\n" "2. If no, please try one of the following suggestions:\n" " 1) Decrease the batch size of your model.\n" " 2) FLAGS_fraction_of_gpu_memory_to_use is %.2lf now, " "please set it to a higher value but less than 1.0.\n" " The command is " "`export FLAGS_fraction_of_gpu_memory_to_use=xxx`.\n\n", gpu_id_, string::HumanReadableSize(size), gpu_id_, string::HumanReadableSize(avail), gpu_id_, FLAGS_fraction_of_gpu_memory_to_use); } } void GPUAllocator::Free(void* p, size_t size, size_t index) { cudaError_t err; PADDLE_ENFORCE_EQ(index, 0); PADDLE_ENFORCE_GE(gpu_alloc_size_, size); gpu_alloc_size_ -= size; err = cudaFree(p); // Purposefully allow cudaErrorCudartUnloading, because // that is returned if you ever call cudaFree after the // driver has already shutdown. This happens only if the // process is terminating, in which case we don't care if // cudaFree succeeds. if (err != cudaErrorCudartUnloading) { PADDLE_ENFORCE(err, "cudaFree{Host} failed in GPUAllocator::Free."); } } bool GPUAllocator::UseGpu() const { return true; } // PINNED memory allows direct DMA transfers by the GPU to and from system // memory. It’s locked to a physical address. void* CUDAPinnedAllocator::Alloc(size_t* index, size_t size) { if (size <= 0) return nullptr; // NOTE: here, we use CUDAPinnedMaxAllocSize as the maximum memory size // of host pinned allocation. Allocates too much would reduce // the amount of memory available to the underlying system for paging. size_t usable = paddle::platform::CUDAPinnedMaxAllocSize() - cuda_pinnd_alloc_size_; if (size > usable) { LOG(WARNING) << "Cannot malloc " << size / 1024.0 / 1024.0 << " MB pinned memory." << ", available " << usable / 1024.0 / 1024.0 << " MB"; return nullptr; } void* p; // PINNED memory is visible to all CUDA contexts. cudaError_t result = cudaHostAlloc(&p, size, cudaHostAllocPortable); if (result == cudaSuccess) { *index = 1; // PINNED memory cuda_pinnd_alloc_size_ += size; return p; } else { LOG(WARNING) << "cudaHostAlloc failed."; return nullptr; } return nullptr; } void CUDAPinnedAllocator::Free(void* p, size_t size, size_t index) { cudaError_t err; PADDLE_ENFORCE_EQ(index, 1); PADDLE_ENFORCE_GE(cuda_pinnd_alloc_size_, size); cuda_pinnd_alloc_size_ -= size; err = cudaFreeHost(p); // Purposefully allow cudaErrorCudartUnloading, because // that is returned if you ever call cudaFreeHost after the // driver has already shutdown. This happens only if the // process is terminating, in which case we don't care if // cudaFreeHost succeeds. if (err != cudaErrorCudartUnloading) { PADDLE_ENFORCE(err, "cudaFreeHost failed in GPUPinnedAllocator::Free."); } } bool CUDAPinnedAllocator::UseGpu() const { return false; } #endif } // namespace detail } // namespace memory } // namespace paddle <commit_msg>refine err msg of allocator, test=develop (#20804)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #define GLOG_NO_ABBREVIATED_SEVERITIES #include "paddle/fluid/memory/detail/system_allocator.h" #ifdef _WIN32 #include <malloc.h> #include <windows.h> // VirtualLock/VirtualUnlock #else #include <sys/mman.h> // for mlock and munlock #endif #include <stdlib.h> // for malloc and free #include <algorithm> // for std::max #include <string> #include <utility> #include "gflags/gflags.h" #include "paddle/fluid/memory/allocation/allocator.h" #include "paddle/fluid/platform/cpu_info.h" #include "paddle/fluid/platform/enforce.h" #include "paddle/fluid/platform/gpu_info.h" #ifdef PADDLE_WITH_CUDA #include "paddle/fluid/platform/cuda_device_guard.h" #endif DECLARE_bool(use_pinned_memory); DECLARE_double(fraction_of_gpu_memory_to_use); DECLARE_uint64(initial_gpu_memory_in_mb); DECLARE_uint64(reallocate_gpu_memory_in_mb); namespace paddle { namespace memory { namespace detail { void* AlignedMalloc(size_t size) { void* p = nullptr; size_t alignment = 32ul; #ifdef PADDLE_WITH_MKLDNN // refer to https://github.com/01org/mkl-dnn/blob/master/include/mkldnn.hpp // memory alignment alignment = 4096ul; #endif #ifdef _WIN32 p = _aligned_malloc(size, alignment); #else PADDLE_ENFORCE_EQ(posix_memalign(&p, alignment, size), 0, "Alloc %ld error!", size); #endif PADDLE_ENFORCE_NOT_NULL(p, "Fail to allocate CPU memory: size = %d .", size); return p; } void* CPUAllocator::Alloc(size_t* index, size_t size) { // According to http://www.cplusplus.com/reference/cstdlib/malloc/, // malloc might not return nullptr if size is zero, but the returned // pointer shall not be dereferenced -- so we make it nullptr. if (size <= 0) return nullptr; *index = 0; // unlock memory void* p = AlignedMalloc(size); if (p != nullptr) { if (FLAGS_use_pinned_memory) { *index = 1; #ifdef _WIN32 VirtualLock(p, size); #else mlock(p, size); // lock memory #endif } } return p; } void CPUAllocator::Free(void* p, size_t size, size_t index) { if (p != nullptr && index == 1) { #ifdef _WIN32 VirtualUnlock(p, size); #else munlock(p, size); #endif } #ifdef _WIN32 _aligned_free(p); #else free(p); #endif } bool CPUAllocator::UseGpu() const { return false; } #ifdef PADDLE_WITH_CUDA void* GPUAllocator::Alloc(size_t* index, size_t size) { // CUDA documentation doesn't explain if cudaMalloc returns nullptr // if size is 0. We just make sure it does. if (size <= 0) return nullptr; paddle::platform::CUDADeviceGuard guard(gpu_id_); void* p; cudaError_t result = cudaMalloc(&p, size); if (result == cudaSuccess) { *index = 0; gpu_alloc_size_ += size; return p; } else { if (result == cudaErrorMemoryAllocation) { result = cudaSuccess; } PADDLE_ENFORCE_CUDA_SUCCESS(result); result = cudaGetLastError(); if (result == cudaErrorMemoryAllocation) { result = cudaSuccess; } PADDLE_ENFORCE_CUDA_SUCCESS(result); size_t avail, total; platform::GpuMemoryUsage(&avail, &total); PADDLE_THROW_BAD_ALLOC( "\n\nOut of memory error on GPU %d. " "Cannot allocate %s memory on GPU %d, " "available memory is only %s.\n\n" "Please check whether there is any other process using GPU %d.\n" "1. If yes, please stop them, or start PaddlePaddle on another GPU.\n" "2. If no, please try one of the following suggestions:\n" " 1) Decrease the batch size of your model.\n" " 2) FLAGS_fraction_of_gpu_memory_to_use is %.2lf now, " "please set it to a higher value but less than 1.0.\n" " The command is " "`export FLAGS_fraction_of_gpu_memory_to_use=xxx`.\n\n", gpu_id_, string::HumanReadableSize(size), gpu_id_, string::HumanReadableSize(avail), gpu_id_, FLAGS_fraction_of_gpu_memory_to_use); } } void GPUAllocator::Free(void* p, size_t size, size_t index) { cudaError_t err; PADDLE_ENFORCE_EQ(index, 0); PADDLE_ENFORCE_GE(gpu_alloc_size_, size); gpu_alloc_size_ -= size; err = cudaFree(p); // Purposefully allow cudaErrorCudartUnloading, because // that is returned if you ever call cudaFree after the // driver has already shutdown. This happens only if the // process is terminating, in which case we don't care if // cudaFree succeeds. if (err != cudaErrorCudartUnloading) { PADDLE_ENFORCE(err, "cudaFree{Host} failed in GPUAllocator::Free."); } } bool GPUAllocator::UseGpu() const { return true; } // PINNED memory allows direct DMA transfers by the GPU to and from system // memory. It’s locked to a physical address. void* CUDAPinnedAllocator::Alloc(size_t* index, size_t size) { if (size <= 0) return nullptr; // NOTE: here, we use CUDAPinnedMaxAllocSize as the maximum memory size // of host pinned allocation. Allocates too much would reduce // the amount of memory available to the underlying system for paging. size_t usable = paddle::platform::CUDAPinnedMaxAllocSize() - cuda_pinnd_alloc_size_; if (size > usable) { LOG(WARNING) << "Cannot malloc " << size / 1024.0 / 1024.0 << " MB pinned memory." << ", available " << usable / 1024.0 / 1024.0 << " MB"; return nullptr; } void* p; // PINNED memory is visible to all CUDA contexts. cudaError_t result = cudaHostAlloc(&p, size, cudaHostAllocPortable); if (result == cudaSuccess) { *index = 1; // PINNED memory cuda_pinnd_alloc_size_ += size; return p; } else { LOG(WARNING) << "cudaHostAlloc failed."; return nullptr; } return nullptr; } void CUDAPinnedAllocator::Free(void* p, size_t size, size_t index) { cudaError_t err; PADDLE_ENFORCE_EQ(index, 1); PADDLE_ENFORCE_GE(cuda_pinnd_alloc_size_, size); cuda_pinnd_alloc_size_ -= size; err = cudaFreeHost(p); // Purposefully allow cudaErrorCudartUnloading, because // that is returned if you ever call cudaFreeHost after the // driver has already shutdown. This happens only if the // process is terminating, in which case we don't care if // cudaFreeHost succeeds. if (err != cudaErrorCudartUnloading) { PADDLE_ENFORCE(err, "cudaFreeHost failed in GPUPinnedAllocator::Free."); } } bool CUDAPinnedAllocator::UseGpu() const { return false; } #endif } // namespace detail } // namespace memory } // namespace paddle <|endoftext|>
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/message_center/views/message_popup_collection.h" #include <set> #include "base/bind.h" #include "base/memory/weak_ptr.h" #include "base/timer.h" #include "ui/gfx/screen.h" #include "ui/message_center/message_center.h" #include "ui/message_center/message_center_constants.h" #include "ui/message_center/notification.h" #include "ui/message_center/notification_list.h" #include "ui/message_center/views/notification_view.h" #include "ui/views/background.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace message_center { namespace { const int kToastMargin = kMarginBetweenItems; gfx::Size GetToastSize(views::View* view) { int width = kNotificationWidth + view->GetInsets().width(); return gfx::Size(width, view->GetHeightForWidth(width)); } } class ToastContentsView : public views::WidgetDelegateView { public: ToastContentsView(const Notification* notification, base::WeakPtr<MessagePopupCollection> collection, MessageCenter* message_center) : id_(notification->id()), collection_(collection), message_center_(message_center) { DCHECK(collection_); set_notify_enter_exit_on_child(true); // Sets the transparent background. Then, when the message view is slid out, // the whole toast seems to slide although the actual bound of the widget // remains. This is hacky but easier to keep the consistency. set_background(views::Background::CreateSolidBackground(0, 0, 0, 0)); ResetTimeout(notification->priority()); // Creates the timer only when it does the timeout (i.e. not never-timeout). if (!notification->never_timeout()) timer_.reset(new base::OneShotTimer<views::Widget>); } views::Widget* CreateWidget(gfx::NativeView parent) { views::Widget::InitParams params( views::Widget::InitParams::TYPE_POPUP); params.keep_on_top = true; if (parent) params.parent = parent; else params.top_level = true; params.transparent = true; params.delegate = this; views::Widget* widget = new views::Widget(); widget->set_focus_on_creation(false); widget->Init(params); return widget; } void SetContents(MessageView* view) { RemoveAllChildViews(true); AddChildView(view); views::Widget* widget = GetWidget(); if (widget) { gfx::Rect bounds = widget->GetWindowBoundsInScreen(); bounds.set_size(GetToastSize(view)); widget->SetBounds(bounds); } Layout(); } void ResetTimeout(int priority) { int seconds = kAutocloseDefaultDelaySeconds; if (priority > DEFAULT_PRIORITY) seconds = kAutocloseHighPriorityDelaySeconds; timeout_ = base::TimeDelta::FromSeconds(seconds); } void SuspendTimer() { if (timer_.get()) timer_->Stop(); } void RestartTimer() { if (!timer_.get()) return; passed_ += base::Time::Now() - start_time_; if (timeout_ <= passed_) GetWidget()->Close(); else StartTimer(); } void StartTimer() { if (!timer_.get()) return; start_time_ = base::Time::Now(); timer_->Start(FROM_HERE, timeout_ - passed_, base::Bind(&views::Widget::Close, base::Unretained(GetWidget()))); } // Overridden from views::WidgetDelegate: virtual views::View* GetContentsView() OVERRIDE { return this; } virtual void WindowClosing() OVERRIDE { if (timer_.get() && timer_->IsRunning()) SuspendTimer(); } virtual bool CanActivate() const OVERRIDE { #if defined(OS_WIN) && defined(USE_AURA) return true; #else return false; #endif } // Overridden from views::View: virtual void OnMouseEntered(const ui::MouseEvent& event) OVERRIDE { if (collection_) collection_->OnMouseEntered(); } virtual void OnMouseExited(const ui::MouseEvent& event) OVERRIDE { if (collection_) collection_->OnMouseExited(); } virtual void Layout() OVERRIDE { if (child_count() > 0) child_at(0)->SetBounds(x(), y(), width(), height()); } virtual gfx::Size GetPreferredSize() OVERRIDE { return child_count() ? GetToastSize(child_at(0)) : gfx::Size(); } private: std::string id_; base::TimeDelta timeout_; base::TimeDelta passed_; base::Time start_time_; scoped_ptr<base::OneShotTimer<views::Widget> > timer_; base::WeakPtr<MessagePopupCollection> collection_; MessageCenter* message_center_; DISALLOW_COPY_AND_ASSIGN(ToastContentsView); }; MessagePopupCollection::MessagePopupCollection(gfx::NativeView parent, MessageCenter* message_center) : parent_(parent), message_center_(message_center) { DCHECK(message_center_); UpdateWidgets(); message_center_->AddObserver(this); } MessagePopupCollection::~MessagePopupCollection() { message_center_->RemoveObserver(this); CloseAllWidgets(); } void MessagePopupCollection::UpdateWidgets() { NotificationList::PopupNotifications popups = message_center_->GetPopupNotifications(); if (popups.empty()) { CloseAllWidgets(); return; } gfx::Point base_position = GetWorkAreaBottomRight(); int bottom = widgets_.empty() ? base_position.y() : widgets_.back()->GetWindowBoundsInScreen().y(); bottom -= kToastMargin; // Iterate in the reverse order to keep the oldest toasts on screen. Newer // items may be ignored if there are no room to place them. for (NotificationList::PopupNotifications::const_reverse_iterator iter = popups.rbegin(); iter != popups.rend(); ++iter) { MessageView* view = NotificationView::Create(*(*iter), message_center_, true); int view_height = GetToastSize(view).height(); if (bottom - view_height - kToastMargin < 0) { delete view; break; } if (toasts_.find((*iter)->id()) != toasts_.end()) { delete view; continue; } ToastContentsView* toast = new ToastContentsView( *iter, AsWeakPtr(), message_center_); views::Widget* widget = toast->CreateWidget(parent_); toast->SetContents(view); widget->AddObserver(this); toast->StartTimer(); toasts_[(*iter)->id()] = toast; widgets_.push_back(widget); // Place/move the toast widgets. Currently it stacks the widgets from the // right-bottom of the work area. // TODO(mukai): allow to specify the placement policy from outside of this // class. The policy should be specified from preference on Windows, or // the launcher alignment on ChromeOS. gfx::Rect bounds(widget->GetWindowBoundsInScreen()); bounds.set_origin(gfx::Point( base_position.x() - bounds.width() - kToastMargin, bottom - bounds.height())); widget->SetBounds(bounds); widget->Show(); bottom -= view_height + kToastMargin; } } void MessagePopupCollection::OnMouseEntered() { for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { iter->second->SuspendTimer(); } } void MessagePopupCollection::OnMouseExited() { for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { iter->second->RestartTimer(); } reposition_target_ = gfx::Rect(); RepositionWidgets(); // Reposition could create extra space which allows additional widgets. UpdateWidgets(); } void MessagePopupCollection::CloseAllWidgets() { for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { iter->second->SuspendTimer(); views::Widget* widget = iter->second->GetWidget(); widget->RemoveObserver(this); widget->Close(); } toasts_.clear(); widgets_.clear(); } void MessagePopupCollection::OnWidgetDestroying(views::Widget* widget) { widget->RemoveObserver(this); widgets_.erase(std::find(widgets_.begin(), widgets_.end(), widget)); bool widget_went_empty = widgets_.empty(); for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { if (iter->second->GetWidget() == widget) { std::string id = iter->first; toasts_.erase(iter); message_center_->MarkSinglePopupAsShown(id, false); break; } } // MarkSinglePopupAsShown can delete this if there are no longer // any toasts. if (widget_went_empty) return; RepositionWidgets(); UpdateWidgets(); } gfx::Point MessagePopupCollection::GetWorkAreaBottomRight() { if (!work_area_.IsEmpty()) return work_area_.bottom_right(); if (!parent_) { // On Win+Aura, we don't have a parent since the popups currently show up // on the Windows desktop, not in the Aura/Ash desktop. This code will // display the popups on the primary display. gfx::Screen* screen = gfx::Screen::GetNativeScreen(); work_area_ = screen->GetPrimaryDisplay().work_area(); } else { gfx::Screen* screen = gfx::Screen::GetScreenFor(parent_); work_area_ = screen->GetDisplayNearestWindow(parent_).work_area(); } return work_area_.bottom_right(); } void MessagePopupCollection::RepositionWidgets() { if (!reposition_target_.IsEmpty()) { RepositionWidgetsWithTarget(); return; } int bottom = GetWorkAreaBottomRight().y() - kToastMargin; for (std::list<views::Widget*>::iterator iter = widgets_.begin(); iter != widgets_.end(); ++iter) { gfx::Rect bounds((*iter)->GetWindowBoundsInScreen()); bounds.set_y(bottom - bounds.height()); (*iter)->SetBounds(bounds); bottom -= bounds.height() + kToastMargin; } } void MessagePopupCollection::RepositionWidgetsWithTarget() { if (widgets_.empty()) return; if (widgets_.back()->GetWindowBoundsInScreen().y() > reposition_target_.y()) { // No widgets are above, thus slides up the widgets. int slide_length = widgets_.back()->GetWindowBoundsInScreen().y() - reposition_target_.y(); for (std::list<views::Widget*>::iterator iter = widgets_.begin(); iter != widgets_.end(); ++iter) { gfx::Rect bounds((*iter)->GetWindowBoundsInScreen()); bounds.set_y(bounds.y() - slide_length); (*iter)->SetBounds(bounds); } } else { std::list<views::Widget*>::reverse_iterator iter = widgets_.rbegin(); for (; iter != widgets_.rend(); ++iter) { if ((*iter)->GetWindowBoundsInScreen().y() > reposition_target_.y()) break; } --iter; int slide_length = reposition_target_.y() - (*iter)->GetWindowBoundsInScreen().y(); for (; ; --iter) { gfx::Rect bounds((*iter)->GetWindowBoundsInScreen()); bounds.set_y(bounds.y() + slide_length); (*iter)->SetBounds(bounds); if (iter == widgets_.rbegin()) break; } } } void MessagePopupCollection::OnNotificationAdded( const std::string& notification_id) { UpdateWidgets(); } void MessagePopupCollection::OnNotificationRemoved( const std::string& notification_id, bool by_user) { ToastContainer::iterator iter = toasts_.find(notification_id); if (iter == toasts_.end()) return; views::Widget* widget = iter->second->GetWidget(); if (by_user) reposition_target_ = widget->GetWindowBoundsInScreen(); widget->RemoveObserver(this); widget->Close(); widgets_.erase(std::find(widgets_.begin(), widgets_.end(), widget)); toasts_.erase(iter); bool widgets_went_empty = widgets_.empty(); RepositionWidgets(); // A notification removal may create extra space which allows appearing // other notifications. UpdateWidgets(); // Also, if the removed notification is the last one but removing that enables // other notifications appearing, the newly created widgets also have to be // repositioned. if (by_user && widgets_went_empty) RepositionWidgets(); } void MessagePopupCollection::OnNotificationUpdated( const std::string& notification_id) { ToastContainer::iterator toast_iter = toasts_.find(notification_id); if (toast_iter == toasts_.end()) return; NotificationList::PopupNotifications notifications = message_center_->GetPopupNotifications(); bool updated = false; for (NotificationList::PopupNotifications::iterator iter = notifications.begin(); iter != notifications.end(); ++iter) { if ((*iter)->id() != notification_id) continue; MessageView* view = NotificationView::Create( *(*iter), message_center_, true); toast_iter->second->SetContents(view); toast_iter->second->ResetTimeout((*iter)->priority()); toast_iter->second->RestartTimer(); updated = true; } // OnNotificationUpdated() can be called when a notification is excluded from // the popup notification list but still remains in the full notification // list. In that case the widget for the notification has to be closed here. if (!updated) { views::Widget* widget = toast_iter->second->GetWidget(); widget->RemoveObserver(this); widgets_.erase(std::find(widgets_.begin(), widgets_.end(), widget)); widget->Close(); toasts_.erase(toast_iter); } RepositionWidgets(); // Reposition could create extra space which allows additional widgets. UpdateWidgets(); } void MessagePopupCollection::SetWorkAreaForTest(const gfx::Rect& work_area) { work_area_ = work_area; } views::Widget* MessagePopupCollection::GetWidgetForId(const std::string& id) { ToastContainer::const_iterator iter = toasts_.find(id); return (iter == toasts_.end()) ? NULL : iter->second->GetWidget(); } } // namespace message_center <commit_msg>Fixes the widget positions.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/message_center/views/message_popup_collection.h" #include <set> #include "base/bind.h" #include "base/memory/weak_ptr.h" #include "base/timer.h" #include "ui/gfx/screen.h" #include "ui/message_center/message_center.h" #include "ui/message_center/message_center_constants.h" #include "ui/message_center/notification.h" #include "ui/message_center/notification_list.h" #include "ui/message_center/views/notification_view.h" #include "ui/views/background.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace message_center { namespace { const int kToastMargin = kMarginBetweenItems; gfx::Size GetToastSize(views::View* view) { int width = kNotificationWidth + view->GetInsets().width(); return gfx::Size(width, view->GetHeightForWidth(width)); } } class ToastContentsView : public views::WidgetDelegateView { public: ToastContentsView(const Notification* notification, base::WeakPtr<MessagePopupCollection> collection, MessageCenter* message_center) : id_(notification->id()), collection_(collection), message_center_(message_center) { DCHECK(collection_); set_notify_enter_exit_on_child(true); // Sets the transparent background. Then, when the message view is slid out, // the whole toast seems to slide although the actual bound of the widget // remains. This is hacky but easier to keep the consistency. set_background(views::Background::CreateSolidBackground(0, 0, 0, 0)); ResetTimeout(notification->priority()); // Creates the timer only when it does the timeout (i.e. not never-timeout). if (!notification->never_timeout()) timer_.reset(new base::OneShotTimer<views::Widget>); } views::Widget* CreateWidget(gfx::NativeView parent) { views::Widget::InitParams params( views::Widget::InitParams::TYPE_POPUP); params.keep_on_top = true; if (parent) params.parent = parent; else params.top_level = true; params.transparent = true; params.delegate = this; views::Widget* widget = new views::Widget(); widget->set_focus_on_creation(false); widget->Init(params); return widget; } void SetContents(MessageView* view) { RemoveAllChildViews(true); AddChildView(view); views::Widget* widget = GetWidget(); if (widget) { gfx::Rect bounds = widget->GetWindowBoundsInScreen(); bounds.set_size(GetToastSize(view)); widget->SetBounds(bounds); } Layout(); } void ResetTimeout(int priority) { int seconds = kAutocloseDefaultDelaySeconds; if (priority > DEFAULT_PRIORITY) seconds = kAutocloseHighPriorityDelaySeconds; timeout_ = base::TimeDelta::FromSeconds(seconds); } void SuspendTimer() { if (timer_.get()) timer_->Stop(); } void RestartTimer() { if (!timer_.get()) return; passed_ += base::Time::Now() - start_time_; if (timeout_ <= passed_) GetWidget()->Close(); else StartTimer(); } void StartTimer() { if (!timer_.get()) return; start_time_ = base::Time::Now(); timer_->Start(FROM_HERE, timeout_ - passed_, base::Bind(&views::Widget::Close, base::Unretained(GetWidget()))); } // Overridden from views::WidgetDelegate: virtual views::View* GetContentsView() OVERRIDE { return this; } virtual void WindowClosing() OVERRIDE { if (timer_.get() && timer_->IsRunning()) SuspendTimer(); } virtual bool CanActivate() const OVERRIDE { #if defined(OS_WIN) && defined(USE_AURA) return true; #else return false; #endif } // Overridden from views::View: virtual void OnMouseEntered(const ui::MouseEvent& event) OVERRIDE { if (collection_) collection_->OnMouseEntered(); } virtual void OnMouseExited(const ui::MouseEvent& event) OVERRIDE { if (collection_) collection_->OnMouseExited(); } virtual void Layout() OVERRIDE { if (child_count() > 0) child_at(0)->SetBounds(x(), y(), width(), height()); } virtual gfx::Size GetPreferredSize() OVERRIDE { return child_count() ? GetToastSize(child_at(0)) : gfx::Size(); } private: std::string id_; base::TimeDelta timeout_; base::TimeDelta passed_; base::Time start_time_; scoped_ptr<base::OneShotTimer<views::Widget> > timer_; base::WeakPtr<MessagePopupCollection> collection_; MessageCenter* message_center_; DISALLOW_COPY_AND_ASSIGN(ToastContentsView); }; MessagePopupCollection::MessagePopupCollection(gfx::NativeView parent, MessageCenter* message_center) : parent_(parent), message_center_(message_center) { DCHECK(message_center_); UpdateWidgets(); message_center_->AddObserver(this); } MessagePopupCollection::~MessagePopupCollection() { message_center_->RemoveObserver(this); CloseAllWidgets(); } void MessagePopupCollection::UpdateWidgets() { NotificationList::PopupNotifications popups = message_center_->GetPopupNotifications(); if (popups.empty()) { CloseAllWidgets(); return; } gfx::Point base_position = GetWorkAreaBottomRight(); int bottom = widgets_.empty() ? base_position.y() : widgets_.back()->GetWindowBoundsInScreen().y(); bottom -= kToastMargin; // Iterate in the reverse order to keep the oldest toasts on screen. Newer // items may be ignored if there are no room to place them. for (NotificationList::PopupNotifications::const_reverse_iterator iter = popups.rbegin(); iter != popups.rend(); ++iter) { if (toasts_.find((*iter)->id()) != toasts_.end()) continue; MessageView* view = NotificationView::Create(*(*iter), message_center_, true); int view_height = GetToastSize(view).height(); if (bottom - view_height - kToastMargin < 0) { delete view; break; } ToastContentsView* toast = new ToastContentsView( *iter, AsWeakPtr(), message_center_); views::Widget* widget = toast->CreateWidget(parent_); toast->SetContents(view); widget->AddObserver(this); toast->StartTimer(); toasts_[(*iter)->id()] = toast; widgets_.push_back(widget); // Place/move the toast widgets. Currently it stacks the widgets from the // right-bottom of the work area. // TODO(mukai): allow to specify the placement policy from outside of this // class. The policy should be specified from preference on Windows, or // the launcher alignment on ChromeOS. gfx::Rect bounds(widget->GetWindowBoundsInScreen()); bounds.set_origin(gfx::Point( base_position.x() - bounds.width() - kToastMargin, bottom - bounds.height())); widget->SetBounds(bounds); widget->Show(); bottom -= view_height + kToastMargin; } } void MessagePopupCollection::OnMouseEntered() { for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { iter->second->SuspendTimer(); } } void MessagePopupCollection::OnMouseExited() { for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { iter->second->RestartTimer(); } reposition_target_ = gfx::Rect(); RepositionWidgets(); // Reposition could create extra space which allows additional widgets. UpdateWidgets(); } void MessagePopupCollection::CloseAllWidgets() { for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { iter->second->SuspendTimer(); views::Widget* widget = iter->second->GetWidget(); widget->RemoveObserver(this); widget->Close(); } toasts_.clear(); widgets_.clear(); } void MessagePopupCollection::OnWidgetDestroying(views::Widget* widget) { widget->RemoveObserver(this); widgets_.erase(std::find(widgets_.begin(), widgets_.end(), widget)); bool widget_went_empty = widgets_.empty(); for (ToastContainer::iterator iter = toasts_.begin(); iter != toasts_.end(); ++iter) { if (iter->second->GetWidget() == widget) { std::string id = iter->first; toasts_.erase(iter); message_center_->MarkSinglePopupAsShown(id, false); break; } } // MarkSinglePopupAsShown can delete this if there are no longer // any toasts. if (widget_went_empty) return; RepositionWidgets(); UpdateWidgets(); } gfx::Point MessagePopupCollection::GetWorkAreaBottomRight() { if (!work_area_.IsEmpty()) return work_area_.bottom_right(); if (!parent_) { // On Win+Aura, we don't have a parent since the popups currently show up // on the Windows desktop, not in the Aura/Ash desktop. This code will // display the popups on the primary display. gfx::Screen* screen = gfx::Screen::GetNativeScreen(); work_area_ = screen->GetPrimaryDisplay().work_area(); } else { gfx::Screen* screen = gfx::Screen::GetScreenFor(parent_); work_area_ = screen->GetDisplayNearestWindow(parent_).work_area(); } return work_area_.bottom_right(); } void MessagePopupCollection::RepositionWidgets() { if (!reposition_target_.IsEmpty()) { RepositionWidgetsWithTarget(); return; } int bottom = GetWorkAreaBottomRight().y() - kToastMargin; for (std::list<views::Widget*>::iterator iter = widgets_.begin(); iter != widgets_.end(); ++iter) { gfx::Rect bounds((*iter)->GetWindowBoundsInScreen()); bounds.set_y(bottom - bounds.height()); (*iter)->SetBounds(bounds); bottom -= bounds.height() + kToastMargin; } } void MessagePopupCollection::RepositionWidgetsWithTarget() { if (widgets_.empty()) return; if (widgets_.back()->GetWindowBoundsInScreen().y() > reposition_target_.y()) { // No widgets are above, thus slides up the widgets. int slide_length = widgets_.back()->GetWindowBoundsInScreen().y() - reposition_target_.y(); for (std::list<views::Widget*>::iterator iter = widgets_.begin(); iter != widgets_.end(); ++iter) { gfx::Rect bounds((*iter)->GetWindowBoundsInScreen()); bounds.set_y(bounds.y() - slide_length); (*iter)->SetBounds(bounds); } } else { std::list<views::Widget*>::reverse_iterator iter = widgets_.rbegin(); for (; iter != widgets_.rend(); ++iter) { if ((*iter)->GetWindowBoundsInScreen().y() > reposition_target_.y()) break; } --iter; int slide_length = reposition_target_.y() - (*iter)->GetWindowBoundsInScreen().y(); for (; ; --iter) { gfx::Rect bounds((*iter)->GetWindowBoundsInScreen()); bounds.set_y(bounds.y() + slide_length); (*iter)->SetBounds(bounds); if (iter == widgets_.rbegin()) break; } } } void MessagePopupCollection::OnNotificationAdded( const std::string& notification_id) { UpdateWidgets(); } void MessagePopupCollection::OnNotificationRemoved( const std::string& notification_id, bool by_user) { ToastContainer::iterator iter = toasts_.find(notification_id); if (iter == toasts_.end()) return; views::Widget* widget = iter->second->GetWidget(); if (by_user) reposition_target_ = widget->GetWindowBoundsInScreen(); widget->RemoveObserver(this); widget->Close(); widgets_.erase(std::find(widgets_.begin(), widgets_.end(), widget)); toasts_.erase(iter); bool widgets_went_empty = widgets_.empty(); RepositionWidgets(); // A notification removal may create extra space which allows appearing // other notifications. UpdateWidgets(); // Also, if the removed notification is the last one but removing that enables // other notifications appearing, the newly created widgets also have to be // repositioned. if (by_user && widgets_went_empty) RepositionWidgets(); } void MessagePopupCollection::OnNotificationUpdated( const std::string& notification_id) { ToastContainer::iterator toast_iter = toasts_.find(notification_id); if (toast_iter == toasts_.end()) return; NotificationList::PopupNotifications notifications = message_center_->GetPopupNotifications(); bool updated = false; for (NotificationList::PopupNotifications::iterator iter = notifications.begin(); iter != notifications.end(); ++iter) { if ((*iter)->id() != notification_id) continue; MessageView* view = NotificationView::Create( *(*iter), message_center_, true); toast_iter->second->SetContents(view); toast_iter->second->ResetTimeout((*iter)->priority()); toast_iter->second->RestartTimer(); updated = true; } // OnNotificationUpdated() can be called when a notification is excluded from // the popup notification list but still remains in the full notification // list. In that case the widget for the notification has to be closed here. if (!updated) { views::Widget* widget = toast_iter->second->GetWidget(); widget->RemoveObserver(this); widgets_.erase(std::find(widgets_.begin(), widgets_.end(), widget)); widget->Close(); toasts_.erase(toast_iter); } RepositionWidgets(); // Reposition could create extra space which allows additional widgets. UpdateWidgets(); } void MessagePopupCollection::SetWorkAreaForTest(const gfx::Rect& work_area) { work_area_ = work_area; } views::Widget* MessagePopupCollection::GetWidgetForId(const std::string& id) { ToastContainer::const_iterator iter = toasts_.find(id); return (iter == toasts_.end()) ? NULL : iter->second->GetWidget(); } } // namespace message_center <|endoftext|>
<commit_before>//===-- AssemblerTest.cpp ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "../Common/AssemblerUtils.h" #include "X86InstrInfo.h" namespace exegesis { namespace { using llvm::MCInstBuilder; using llvm::X86::EAX; using llvm::X86::MOV32ri; using llvm::X86::MOV64ri32; using llvm::X86::RAX; using llvm::X86::XOR32rr; class X86MachineFunctionGeneratorTest : public MachineFunctionGeneratorBaseTest { protected: X86MachineFunctionGeneratorTest() : MachineFunctionGeneratorBaseTest("x86_64-unknown-linux", "haswell") {} static void SetUpTestCase() { LLVMInitializeX86TargetInfo(); LLVMInitializeX86TargetMC(); LLVMInitializeX86Target(); LLVMInitializeX86AsmPrinter(); } }; TEST_F(X86MachineFunctionGeneratorTest, JitFunction) { Check(llvm::MCInst(), 0xc3); } TEST_F(X86MachineFunctionGeneratorTest, JitFunctionXOR32rr) { Check(MCInstBuilder(XOR32rr).addReg(EAX).addReg(EAX).addReg(EAX), 0x31, 0xc0, 0xc3); } TEST_F(X86MachineFunctionGeneratorTest, JitFunctionMOV64ri) { Check(MCInstBuilder(MOV64ri32).addReg(RAX).addImm(42), 0x48, 0xc7, 0xc0, 0x2a, 0x00, 0x00, 0x00, 0xc3); } TEST_F(X86MachineFunctionGeneratorTest, JitFunctionMOV32ri) { Check(MCInstBuilder(MOV32ri).addReg(EAX).addImm(42), 0xb8, 0x2a, 0x00, 0x00, 0x00, 0xc3); } } // namespace } // namespace exegesis <commit_msg>[llvm-exegesis] Disable the tests failing on buildbots while we investigate.<commit_after>//===-- AssemblerTest.cpp ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "../Common/AssemblerUtils.h" #include "X86InstrInfo.h" namespace exegesis { namespace { using llvm::MCInstBuilder; using llvm::X86::EAX; using llvm::X86::MOV32ri; using llvm::X86::MOV64ri32; using llvm::X86::RAX; using llvm::X86::XOR32rr; class X86MachineFunctionGeneratorTest : public MachineFunctionGeneratorBaseTest { protected: X86MachineFunctionGeneratorTest() : MachineFunctionGeneratorBaseTest("x86_64-unknown-linux", "haswell") {} static void SetUpTestCase() { LLVMInitializeX86TargetInfo(); LLVMInitializeX86TargetMC(); LLVMInitializeX86Target(); LLVMInitializeX86AsmPrinter(); } }; TEST_F(X86MachineFunctionGeneratorTest, DISABLED_JitFunction) { Check(llvm::MCInst(), 0xc3); } TEST_F(X86MachineFunctionGeneratorTest, DISABLED_JitFunctionXOR32rr) { Check(MCInstBuilder(XOR32rr).addReg(EAX).addReg(EAX).addReg(EAX), 0x31, 0xc0, 0xc3); } TEST_F(X86MachineFunctionGeneratorTest, DISABLED_JitFunctionMOV64ri) { Check(MCInstBuilder(MOV64ri32).addReg(RAX).addImm(42), 0x48, 0xc7, 0xc0, 0x2a, 0x00, 0x00, 0x00, 0xc3); } TEST_F(X86MachineFunctionGeneratorTest, DISABLED_JitFunctionMOV32ri) { Check(MCInstBuilder(MOV32ri).addReg(EAX).addImm(42), 0xb8, 0x2a, 0x00, 0x00, 0x00, 0xc3); } } // namespace } // namespace exegesis <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <math.h> #include <cstdlib> #include "AsciiWriter.h" #include "../intField.h" #include "../doubleField.h" #include "../progressBar.h" AsciiWriter::AsciiWriter(){} AsciiWriter::~AsciiWriter(){} void AsciiWriter::Write(std::string fname, std::map<std::string, std::string> parameters, double *positions, std::vector<IntField*> intFields, std::vector<DoubleField*> doubleFields, int dim, long numParticles ) { std::map<std::string, std::string>::iterator it; int progress = 1; int j = 0; if(numParticles == 0) { std::cout << "Error: Number of particles is 0, exiting" << std::endl; std::exit(1); } ProgressBar pb(intFields.size()+doubleFields.size()+parameters.size()+1,"Writing output"); std::ofstream outfile((char*)fname.c_str(), std::ios::out); if(outfile.is_open()) { std::cout << "Writing to output file..." << std::flush; outfile << "numParticles" << std::endl; outfile << numParticles << std::endl; // Number of particles for ( it = parameters.begin(); it != parameters.end(); it++ ) // All the parameters defined int he python script { outfile << it->first << std::endl; outfile << it->second << std::endl; } outfile << "Position0" << " " << "Position1" << " " << "Position2"; for (long intf=0; intf < intFields.size(); intf++) { IntField *thisField = intFields[intf]; for( int i=0; i<thisField->dim; i++) { outfile << " " << thisField->name << i; } } for (long intf=0; intf < doubleFields.size(); intf++) { DoubleField *thisField = doubleFields[intf]; for( int i=0; i<thisField->dim; i++) { outfile << " " << thisField->name << i; } } outfile << std::endl; for ( int i = 0; i<numParticles; i++ ) // All positions, duplicate this loop to write extra arrays { j = 3*i; outfile << positions[j] << " " << positions[j+1] << " " << positions[j+2]; for (long intf=0; intf < intFields.size(); intf++) { IntField *thisField = intFields[intf]; outfile << " " << thisField->data[i]; } for (long intf=0; intf < doubleFields.size(); intf++) { DoubleField *thisField = doubleFields[intf]; outfile << " " << thisField->data[i]; } outfile << std::endl; } outfile.close(); pb.Finish(); } } <commit_msg>Updated asciiwriter.cpp. Corrected bug.<commit_after>#include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <math.h> #include <cstdlib> #include "AsciiWriter.h" #include "../intField.h" #include "../doubleField.h" #include "../progressBar.h" AsciiWriter::AsciiWriter(){} AsciiWriter::~AsciiWriter(){} void AsciiWriter::Write(std::string fname, std::map<std::string, std::string> parameters, double *positions, std::vector<IntField*> intFields, std::vector<DoubleField*> doubleFields, int dim, long numParticles ) { std::map<std::string, std::string>::iterator it; int progress = 1; int j = 0; int k = 0; if(numParticles == 0) { std::cout << "Error: Number of particles is 0, exiting" << std::endl; std::exit(1); } ProgressBar pb(intFields.size()+doubleFields.size()+parameters.size()+1,"Writing output"); std::ofstream outfile((char*)fname.c_str(), std::ios::out); if(outfile.is_open()) { std::cout << "Writing to output file..." << std::flush; outfile << "numParticles" << std::endl; outfile << numParticles << std::endl; // Number of particles for ( it = parameters.begin(); it != parameters.end(); it++ ) // All the parameters defined int he python script { outfile << it->first << std::endl; outfile << it->second << std::endl; } outfile << "Position0" << " " << "Position1" << " " << "Position2"; for (long intf=0; intf < intFields.size(); intf++) { IntField *thisField = intFields[intf]; for( int i=0; i<thisField->dim; i++) { outfile << " " << thisField->name << i; } } for (long intf=0; intf < doubleFields.size(); intf++) { DoubleField *thisField = doubleFields[intf]; for( int i=0; i<thisField->dim; i++) { outfile << " " << thisField->name << i; } } outfile << std::endl; for ( int i = 0; i<numParticles; i++ ) // All positions, duplicate this loop to write extra arrays { j = 3*i; outfile << positions[j] << " " << positions[j+1] << " " << positions[j+2]; for (long intf=0; intf < intFields.size(); intf++) { IntField *thisField = intFields[intf]; k= thisField->dim * i; for( int l=0; l<thisField->dim; l++) { outfile << " " << thisField->data[k+l]; } } for (long intf=0; intf < doubleFields.size(); intf++) { DoubleField *thisField = doubleFields[intf]; k= thisField->dim * i; for( int l=0; l<thisField->dim; l++) { outfile << " " << thisField->data[k+l]; } } outfile << std::endl; } outfile.close(); pb.Finish(); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ManifestImport.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: mtg $ $Date: 2001-05-08 13:56:22 $ * * 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): Martin Gallwey (gallwey@sun.com) * * ************************************************************************/ #ifndef _MANIFEST_IMPORT_HXX #define _MANIFEST_IMPORT_HXX #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> // helper for implementations #endif #ifndef _COM_SUN_STAR_XML_SAX_XDUCUMENTHANDLER_HPP_ #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_ #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #include <vector> #include <stack> enum ElementNames { e_Manifest, e_FileEntry, e_EncryptionData, e_Algorithm, e_KeyDerivation }; class ManifestImport : public cppu::WeakImplHelper1 < com::sun::star::xml::sax::XDocumentHandler > { protected: com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > aSequence; sal_Int16 nNumProperty; ::std::stack < ElementNames > aStack; sal_Bool bIgnoreEncryptData; ::std::vector < ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue > > & rManVector; const ::rtl::OUString sFileEntryElement; const ::rtl::OUString sManifestElement; const ::rtl::OUString sEncryptionDataElement; const ::rtl::OUString sAlgorithmElement; const ::rtl::OUString sKeyDerivationElement; const ::rtl::OUString sCdataAttribute; const ::rtl::OUString sMediaTypeAttribute; const ::rtl::OUString sFullPathAttribute; const ::rtl::OUString sSizeAttribute; const ::rtl::OUString sSaltAttribute; const ::rtl::OUString sInitialisationVectorAttribute; const ::rtl::OUString sIterationCountAttribute; const ::rtl::OUString sAlgorithmNameAttribute; const ::rtl::OUString sKeyDerivationNameAttribute; const ::rtl::OUString sFullPathProperty; const ::rtl::OUString sMediaTypeProperty; const ::rtl::OUString sIterationCountProperty; const ::rtl::OUString sSaltProperty; const ::rtl::OUString sInitialisationVectorProperty; const ::rtl::OUString sSizeProperty; const ::rtl::OUString sWhiteSpace; const ::rtl::OUString sBlowfish; const ::rtl::OUString sPBKDF2; public: ManifestImport( std::vector < ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue > > & rNewVector ); ~ManifestImport( void ); virtual void SAL_CALL startDocument( ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL endDocument( ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL startElement( const ::rtl::OUString& aName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttribs ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL endElement( const ::rtl::OUString& aName ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL characters( const ::rtl::OUString& aChars ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL ignorableWhitespace( const ::rtl::OUString& aWhitespaces ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL processingInstruction( const ::rtl::OUString& aTarget, const ::rtl::OUString& aData ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDocumentLocator( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator >& xLocator ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); }; #endif <commit_msg>#90699# add new strings for MD5 import<commit_after>/************************************************************************* * * $RCSfile: ManifestImport.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: mtg $ $Date: 2001-09-05 19:26:06 $ * * 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): Martin Gallwey (gallwey@sun.com) * * ************************************************************************/ #ifndef _MANIFEST_IMPORT_HXX #define _MANIFEST_IMPORT_HXX #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> // helper for implementations #endif #ifndef _COM_SUN_STAR_XML_SAX_XDUCUMENTHANDLER_HPP_ #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_ #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #include <vector> #include <stack> enum ElementNames { e_Manifest, e_FileEntry, e_EncryptionData, e_Algorithm, e_KeyDerivation }; class ManifestImport : public cppu::WeakImplHelper1 < com::sun::star::xml::sax::XDocumentHandler > { protected: com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > aSequence; sal_Int16 nNumProperty; ::std::stack < ElementNames > aStack; sal_Bool bIgnoreEncryptData; ::std::vector < ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue > > & rManVector; const ::rtl::OUString sFileEntryElement; const ::rtl::OUString sManifestElement; const ::rtl::OUString sEncryptionDataElement; const ::rtl::OUString sAlgorithmElement; const ::rtl::OUString sKeyDerivationElement; const ::rtl::OUString sCdataAttribute; const ::rtl::OUString sMediaTypeAttribute; const ::rtl::OUString sFullPathAttribute; const ::rtl::OUString sSizeAttribute; const ::rtl::OUString sSaltAttribute; const ::rtl::OUString sInitialisationVectorAttribute; const ::rtl::OUString sIterationCountAttribute; const ::rtl::OUString sAlgorithmNameAttribute; const ::rtl::OUString sKeyDerivationNameAttribute; const ::rtl::OUString sChecksumAttribute; const ::rtl::OUString sChecksumTypeAttribute; const ::rtl::OUString sFullPathProperty; const ::rtl::OUString sMediaTypeProperty; const ::rtl::OUString sIterationCountProperty; const ::rtl::OUString sSaltProperty; const ::rtl::OUString sInitialisationVectorProperty; const ::rtl::OUString sSizeProperty; const ::rtl::OUString sDigestProperty; const ::rtl::OUString sWhiteSpace; const ::rtl::OUString sBlowfish; const ::rtl::OUString sPBKDF2; const ::rtl::OUString sMD5; public: ManifestImport( std::vector < ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue > > & rNewVector ); ~ManifestImport( void ); virtual void SAL_CALL startDocument( ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL endDocument( ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL startElement( const ::rtl::OUString& aName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttribs ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL endElement( const ::rtl::OUString& aName ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL characters( const ::rtl::OUString& aChars ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL ignorableWhitespace( const ::rtl::OUString& aWhitespaces ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL processingInstruction( const ::rtl::OUString& aTarget, const ::rtl::OUString& aData ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDocumentLocator( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator >& xLocator ) throw(::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); }; #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include <cassert> #include <iostream> #include <utility> #include <sysexits.h> #include <getopt.h> #include <stats.hh> #include <kvstore.hh> #include <item.hh> #include <callbacks.hh> using namespace std; static KVStore *getStore(EPStats &st, const char *path, const char *strategyName) { db_type dbStrategy; if (!KVStore::stringToType(strategyName, dbStrategy)) { cerr << "Unable to parse strategy type: " << strategyName << endl; exit(EX_USAGE); } const char *shardPattern("%d/%b-%i.sqlite"); const char *initFile(NULL); const char *postInitFile(NULL); size_t nVBuckets(1024); size_t dbShards(4); KVStoreConfig conf(path, shardPattern, initFile, postInitFile, nVBuckets, dbShards); return KVStore::create(dbStrategy, st, conf); } class MutationVerifier : public Callback<mutation_result> { public: void callback(mutation_result &mutation) { assert(mutation.first == 1); } }; class Mover : public Callback<GetValue> { public: Mover(KVStore *d, bool kc, size_t re, size_t ts) : dest(d), transferred(0), txnSize(ts), reportEvery(re), killCrlf(kc) { assert(dest); dest->begin(); } ~Mover() { dest->commit(); } void callback(GetValue &gv) { Item *i = gv.getValue(); adjust(&i); dest->set(*i, 0, mv); delete i; if (++transferred % txnSize == 0) { dest->commit(); } if (transferred % reportEvery == 0) { cout << "." << flush; } } size_t getTransferred() { return transferred; } private: void adjust(Item **i) { Item *input(*i); if (killCrlf) { assert(input->getData()[input->getNBytes() - 2] == '\r'); assert(input->getData()[input->getNBytes() - 1] == '\n'); *i = new Item(input->getKey(), input->getFlags(), input->getExptime(), input->getData(), input->getNBytes() - 2, 0, -1, input->getVBucketId()); delete input; } else { input->setId(-1); } } MutationVerifier mv; KVStore *dest; size_t transferred; size_t txnSize; size_t reportEvery; bool killCrlf; }; static void usage(const char *cmd) { cerr << "Usage: " << cmd << " [args] srcPath destPath" << endl << endl << "Optional arguments:" << endl << " --src-strategy=someStrategy (default=multiDB)" << endl << " --dest-strategy=someStrategy (default=multiMTVBDB)" << endl << " --remove-crlf" << endl << " --txn-size=someNumber (default=10000)" << endl << " --report-every=someNumber (default=10000)" << endl; exit(EX_USAGE); } int main(int argc, char **argv) { const char *cmd(argv[0]); const char *srcPath(NULL), *srcStrategy("multiDB"); const char *destPath(NULL), *destStrategy("multiMTVBDB"); size_t txnSize(10000), reportEvery(10000); int killCrlf(0); /* options descriptor */ static struct option longopts[] = { { "src-strategy", required_argument, NULL, 's' }, { "dest-strategy", required_argument, NULL, 'S' }, { "remove-crlf", no_argument, &killCrlf, 'x' }, { "txn-size", required_argument, NULL, 't' }, { "report-every", required_argument, NULL, 'r' }, { NULL, 0, NULL, 0 } }; int ch(0); while ((ch = getopt_long(argc, argv, "s:S:x", longopts, NULL)) != -1) { switch (ch) { case 's': srcStrategy = optarg; break; case 'S': destStrategy = optarg; break; case 't': txnSize = static_cast<size_t>(atoi(optarg)); break; case 'r': reportEvery = static_cast<size_t>(atoi(optarg)); break; case 0: // Path for automatically handled cases (e.g. remove-crlf) break; default: usage(cmd); } } argc -= optind; argv += optind; if (argc != 2) { usage(cmd); } srcPath = argv[0]; destPath = argv[1]; cout << "src = " << srcStrategy << "@" << srcPath << endl; cout << "dest = " << destStrategy << "@" << destPath << endl; EPStats srcStats, destStats; KVStore *src(getStore(srcStats, srcPath, srcStrategy)); KVStore *dest(getStore(destStats, destPath, destStrategy)); Mover mover(dest, txnSize, killCrlf, reportEvery); cout << "Each . represents " << reportEvery << " items moved." << endl; src->dump(mover); cout << endl << "Moved " << mover.getTransferred() << " items." << endl; } <commit_msg>Allow configuration of shard patterns in dbconvert.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include <cassert> #include <iostream> #include <utility> #include <sysexits.h> #include <getopt.h> #include <stats.hh> #include <kvstore.hh> #include <item.hh> #include <callbacks.hh> using namespace std; static KVStore *getStore(EPStats &st, const char *path, const char *strategyName, const char *shardPattern) { db_type dbStrategy; if (!KVStore::stringToType(strategyName, dbStrategy)) { cerr << "Unable to parse strategy type: " << strategyName << endl; exit(EX_USAGE); } const char *initFile(NULL); const char *postInitFile(NULL); size_t nVBuckets(1024); size_t dbShards(4); KVStoreConfig conf(path, shardPattern, initFile, postInitFile, nVBuckets, dbShards); return KVStore::create(dbStrategy, st, conf); } class MutationVerifier : public Callback<mutation_result> { public: void callback(mutation_result &mutation) { assert(mutation.first == 1); } }; class Mover : public Callback<GetValue> { public: Mover(KVStore *d, bool kc, size_t re, size_t ts) : dest(d), transferred(0), txnSize(ts), reportEvery(re), killCrlf(kc) { assert(dest); dest->begin(); } ~Mover() { dest->commit(); } void callback(GetValue &gv) { Item *i = gv.getValue(); adjust(&i); dest->set(*i, 0, mv); delete i; if (++transferred % txnSize == 0) { dest->commit(); } if (transferred % reportEvery == 0) { cout << "." << flush; } } size_t getTransferred() { return transferred; } private: void adjust(Item **i) { Item *input(*i); if (killCrlf) { assert(input->getData()[input->getNBytes() - 2] == '\r'); assert(input->getData()[input->getNBytes() - 1] == '\n'); *i = new Item(input->getKey(), input->getFlags(), input->getExptime(), input->getData(), input->getNBytes() - 2, 0, -1, input->getVBucketId()); delete input; } else { input->setId(-1); } } MutationVerifier mv; KVStore *dest; size_t transferred; size_t txnSize; size_t reportEvery; bool killCrlf; }; static void usage(const char *cmd) { cerr << "Usage: " << cmd << " [args] srcPath destPath" << endl << endl << "Optional arguments:" << endl << " --src-strategy=someStrategy (default=multiDB)" << endl << " --src-pattern=shardPattern (default=%d/%b-%i.sqlite)" << endl << " --dest-strategy=someStrategy (default=multiMTVBDB)" << endl << " --dest-pattern=somePattern (default=%d/%b-%i.mb)" << endl << " --remove-crlf" << endl << " --txn-size=someNumber (default=10000)" << endl << " --report-every=someNumber (default=10000)" << endl; exit(EX_USAGE); } int main(int argc, char **argv) { const char *cmd(argv[0]); const char *srcPath(NULL), *srcStrategy("multiDB"); const char *destPath(NULL), *destStrategy("multiMTVBDB"); const char *srcShardPattern("%d/%b-%i.sqlite"); const char *destShardPattern("%d/%b-%i.mb"); size_t txnSize(10000), reportEvery(10000); int killCrlf(0); /* options descriptor */ static struct option longopts[] = { { "src-strategy", required_argument, NULL, 's' }, { "src-pattern", required_argument, NULL, 'p' }, { "dest-strategy", required_argument, NULL, 'S' }, { "dest-pattern", required_argument, NULL, 'P' }, { "remove-crlf", no_argument, &killCrlf, 'x' }, { "txn-size", required_argument, NULL, 't' }, { "report-every", required_argument, NULL, 'r' }, { NULL, 0, NULL, 0 } }; int ch(0); while ((ch = getopt_long(argc, argv, "s:S:x", longopts, NULL)) != -1) { switch (ch) { case 's': srcStrategy = optarg; break; case 'p': srcShardPattern = optarg; break; case 'S': destStrategy = optarg; break; case 'P': destShardPattern = optarg; break; case 't': txnSize = static_cast<size_t>(atoi(optarg)); break; case 'r': reportEvery = static_cast<size_t>(atoi(optarg)); break; case 0: // Path for automatically handled cases (e.g. remove-crlf) break; default: usage(cmd); } } argc -= optind; argv += optind; if (argc != 2) { usage(cmd); } srcPath = argv[0]; destPath = argv[1]; cout << "src = " << srcStrategy << "@" << srcPath << endl; cout << "dest = " << destStrategy << "@" << destPath << endl; EPStats srcStats, destStats; KVStore *src(getStore(srcStats, srcPath, srcStrategy, srcShardPattern)); KVStore *dest(getStore(destStats, destPath, destStrategy, destShardPattern)); Mover mover(dest, txnSize, killCrlf, reportEvery); cout << "Each . represents " << reportEvery << " items moved." << endl; src->dump(mover); cout << endl << "Moved " << mover.getTransferred() << " items." << endl; } <|endoftext|>
<commit_before>/* * Copyright 2010, 2011 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "html/HTMLParser.h" #include <org/w3c/dom/Comment.h> #include <org/w3c/dom/Element.h> #include <org/w3c/dom/DocumentType.h> #include <org/w3c/dom/Text.h> #include <fstream> #include <iostream> #include <sstream> #include <assert.h> #include "utf.h" #include "css/CSSSerialize.h" #include "DOMImplementationImp.h" #include "Test.util.h" using namespace org::w3c::dom; char data[128*1024]; void test(std::ostream& result, const char* data) { std::istringstream stream(data); HTMLInputStream htmlInputStream(stream, "utf-8"); HTMLTokenizer tokenizer(&htmlInputStream); Document document = bootstrap::getDOMImplementation()->createDocument(u"", u"", 0); HTMLParser parser(document, &tokenizer); parser.mainLoop(); dumpTree(result, document); } const char* load(std::ifstream& stream, char* data) { static char type[256]; char c = 0; char last = '\n'; char*p = data; *p = 0; while (stream.get(c) && (c != '#' || last != '\n')) last = c; if (c != '#' || !stream.getline(type, sizeof type)) return 0; while (stream.get(c)) { if (c == '#' && last == '\n') { stream.unget(); break; } *p++ = c; last = c; } while (data < p && p[-1] == '\n') --p; *p= 0; return type; } int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "usage: " << argv[0] << " [test.dat]...\n"; exit(EXIT_FAILURE); } int rc = EXIT_SUCCESS; for (int i = 1; i < argc; ++i) { std::ifstream stream(argv[i]); if (!stream) { std::cerr << "error: cannot open " << argv[i] << ".\n"; continue; } std::ostringstream result; while (const char* type = load(stream, data)) { std::cout << '#' << type << '\n' << data << '\n'; if (strcmp(type, "data") == 0) test(result, data); else if (strcmp(type, "document") == 0) { if (result.str().substr(10, result.str().length() - 11) == data) std::cout << "PASS\n"; else { std::cout << "#result\n" << result.str().substr(10) << '\n'; std::cout << "FAIL\n"; } result.str(""); result.clear(); result << std::dec; } } } return rc; } <commit_msg>(load) : Clean up.<commit_after>/* * Copyright 2010, 2011 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "html/HTMLParser.h" #include <org/w3c/dom/Comment.h> #include <org/w3c/dom/Element.h> #include <org/w3c/dom/DocumentType.h> #include <org/w3c/dom/Text.h> #include <fstream> #include <iostream> #include <sstream> #include <assert.h> #include "utf.h" #include "css/CSSSerialize.h" #include "DOMImplementationImp.h" #include "Test.util.h" using namespace org::w3c::dom; char data[128*1024]; void test(std::ostream& result, const char* data) { std::istringstream stream(data); HTMLInputStream htmlInputStream(stream, "utf-8"); HTMLTokenizer tokenizer(&htmlInputStream); Document document = bootstrap::getDOMImplementation()->createDocument(u"", u"", 0); HTMLParser parser(document, &tokenizer); parser.mainLoop(); dumpTree(result, document); } const char* load(std::ifstream& stream, char* data) { static char type[256]; char c = 0; char last = '\n'; char*p = data; *p = 0; while (stream.get(c) && (c != '#' || last != '\n')) last = c; if (c != '#' || !stream.getline(type, sizeof type)) return 0; while (stream.get(c)) { if (c == '#' && last == '\n') { stream.unget(); break; } *p++ = c; last = c; } while (data < p && p[-1] == '\n') --p; *p= 0; return type; } int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "usage: " << argv[0] << " [test.dat]...\n"; exit(EXIT_FAILURE); } int rc = EXIT_SUCCESS; for (int i = 1; i < argc; ++i) { std::ifstream stream(argv[i]); if (!stream) { std::cerr << "error: cannot open " << argv[i] << ".\n"; continue; } std::ostringstream result; while (const char* type = load(stream, data)) { std::cout << '#' << type << '\n' << data << '\n'; if (strcmp(type, "data") == 0) test(result, data); else if (strcmp(type, "document") == 0) { if (result.str().substr(10, result.str().length() - 11) == data) std::cout << "PASS\n"; else { std::cout << "#result\n" << result.str().substr(10) << '\n'; std::cout << "FAIL\n"; } result.str(""); result.clear(); result << std::dec; } } } return rc; } <|endoftext|>
<commit_before>/* * Copyright (C) 2020 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/>. */ #include "sstables-format-selector.hh" #include "database.hh" #include "gms/gossiper.hh" #include "gms/feature_service.hh" #include "gms/versioned_value.hh" #include "db/system_keyspace.hh" namespace db { static const sstring SSTABLE_FORMAT_PARAM_NAME = "sstable_format"; void feature_enabled_listener::on_enabled() { if (!_started) { _started = true; // FIXME -- discarded future (void)_selector.maybe_select_format(_format); } } sstables_format_selector::sstables_format_selector(gms::gossiper& g, sharded<gms::feature_service>& f, sharded<database>& db) : _gossiper(g) , _features(f) , _db(db) , _mc_feature_listener(*this, sstables::sstable_version_types::mc) { } future<> sstables_format_selector::maybe_select_format(sstables::sstable_version_types new_format) { return with_gate(_sel, [this, new_format] { return do_maybe_select_format(new_format); }); } future<> sstables_format_selector::do_maybe_select_format(sstables::sstable_version_types new_format) { return with_semaphore(_sem, 1, [this, new_format] { if (!sstables::is_later(new_format, _selected_format)) { return make_ready_future<bool>(false); } return db::system_keyspace::set_scylla_local_param(SSTABLE_FORMAT_PARAM_NAME, to_string(new_format)).then([this, new_format] { return select_format(new_format); }).then([] { return true; }); }).then([this] (bool update_features) { if (!update_features) { return make_ready_future<>(); } return _gossiper.add_local_application_state(gms::application_state::SUPPORTED_FEATURES, gms::versioned_value::supported_features(join(",", _features.local().supported_feature_set()))); }); } future<> sstables_format_selector::start() { assert(this_shard_id() == 0); return read_sstables_format().then([this] { _features.local().cluster_supports_mc_sstable().when_enabled(_mc_feature_listener); return make_ready_future<>(); }); } future<> sstables_format_selector::stop() { return _sel.close(); } future<> sstables_format_selector::read_sstables_format() { return db::system_keyspace::get_scylla_local_param(SSTABLE_FORMAT_PARAM_NAME).then([this] (std::optional<sstring> format_opt) { if (format_opt) { sstables::sstable_version_types format = sstables::from_string(*format_opt); return select_format(format); } return make_ready_future<>(); }); } future<> sstables_format_selector::select_format(sstables::sstable_version_types format) { _selected_format = format; return _db.invoke_on_all([this] (database& db) { db.set_format(_selected_format); if (sstables::is_later(_selected_format, sstables::sstable_version_types::la)) { _features.local().support(gms::features::UNBOUNDED_RANGE_TOMBSTONES); } }); } } // namespace sstables <commit_msg>format_selector: Log which format is being selected<commit_after>/* * Copyright (C) 2020 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/>. */ #include "sstables-format-selector.hh" #include "log.hh" #include "database.hh" #include "gms/gossiper.hh" #include "gms/feature_service.hh" #include "gms/versioned_value.hh" #include "db/system_keyspace.hh" namespace db { static logging::logger logger("format_selector"); static const sstring SSTABLE_FORMAT_PARAM_NAME = "sstable_format"; void feature_enabled_listener::on_enabled() { if (!_started) { _started = true; // FIXME -- discarded future (void)_selector.maybe_select_format(_format); } } sstables_format_selector::sstables_format_selector(gms::gossiper& g, sharded<gms::feature_service>& f, sharded<database>& db) : _gossiper(g) , _features(f) , _db(db) , _mc_feature_listener(*this, sstables::sstable_version_types::mc) { } future<> sstables_format_selector::maybe_select_format(sstables::sstable_version_types new_format) { return with_gate(_sel, [this, new_format] { return do_maybe_select_format(new_format); }); } future<> sstables_format_selector::do_maybe_select_format(sstables::sstable_version_types new_format) { return with_semaphore(_sem, 1, [this, new_format] { if (!sstables::is_later(new_format, _selected_format)) { return make_ready_future<bool>(false); } return db::system_keyspace::set_scylla_local_param(SSTABLE_FORMAT_PARAM_NAME, to_string(new_format)).then([this, new_format] { return select_format(new_format); }).then([] { return true; }); }).then([this] (bool update_features) { if (!update_features) { return make_ready_future<>(); } return _gossiper.add_local_application_state(gms::application_state::SUPPORTED_FEATURES, gms::versioned_value::supported_features(join(",", _features.local().supported_feature_set()))); }); } future<> sstables_format_selector::start() { assert(this_shard_id() == 0); return read_sstables_format().then([this] { _features.local().cluster_supports_mc_sstable().when_enabled(_mc_feature_listener); return make_ready_future<>(); }); } future<> sstables_format_selector::stop() { return _sel.close(); } future<> sstables_format_selector::read_sstables_format() { return db::system_keyspace::get_scylla_local_param(SSTABLE_FORMAT_PARAM_NAME).then([this] (std::optional<sstring> format_opt) { if (format_opt) { sstables::sstable_version_types format = sstables::from_string(*format_opt); return select_format(format); } return make_ready_future<>(); }); } future<> sstables_format_selector::select_format(sstables::sstable_version_types format) { logger.info("Selected {} sstables format", to_string(format)); _selected_format = format; return _db.invoke_on_all([this] (database& db) { db.set_format(_selected_format); if (sstables::is_later(_selected_format, sstables::sstable_version_types::la)) { _features.local().support(gms::features::UNBOUNDED_RANGE_TOMBSTONES); } }); } } // namespace sstables <|endoftext|>
<commit_before>#if __FreeBSD__ >= 10 #include "/usr/local/include/leptonica/allheaders.h" #include "/usr/local/include/tesseract/baseapi.h" #else #include <leptonica/allheaders.h> #include <tesseract/baseapi.h> #endif #include <stdio.h> #include <unistd.h> #include "tessbridge.h" TessBaseAPI Create() { tesseract::TessBaseAPI* api = new tesseract::TessBaseAPI(); return (void*)api; } void Free(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; api->End(); delete api; } void Clear(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; api->Clear(); } void ClearPersistentCache(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; api->ClearPersistentCache(); } int Init(TessBaseAPI a, char* tessdataprefix, char* languages) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; return api->Init(tessdataprefix, languages); } int Init(TessBaseAPI a, char* tessdataprefix, char* languages, char* configfilepath, char* errbuf) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; // {{{ Redirect STDERR to given buffer fflush(stderr); int original_stderr; original_stderr = dup(STDERR_FILENO); (void)freopen("/dev/null", "a", stderr); setbuf(stderr, errbuf); // }}} int ret; if (configfilepath != NULL) { char* configs[] = {configfilepath}; int configs_size = 1; ret = api->Init(tessdataprefix, languages, tesseract::OEM_DEFAULT, configs, configs_size, NULL, NULL, false); } else { ret = api->Init(tessdataprefix, languages); } // {{{ Restore default stderr (void)freopen("/dev/null", "a", stderr); dup2(original_stderr, STDERR_FILENO); setbuf(stderr, NULL); // }}} return ret; } bool SetVariable(TessBaseAPI a, char* name, char* value) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; return api->SetVariable(name, value); } void SetPixImage(TessBaseAPI a, PixImage pix) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; Pix* image = (Pix*)pix; api->SetImage(image); if (api->GetSourceYResolution() < 70) { api->SetSourceResolution(70); } } void SetPageSegMode(TessBaseAPI a, int m) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; tesseract::PageSegMode mode = (tesseract::PageSegMode)m; api->SetPageSegMode(mode); } int GetPageSegMode(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; return api->GetPageSegMode(); } char* UTF8Text(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; return api->GetUTF8Text(); } char* HOCRText(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; return api->GetHOCRText(0); } bounding_boxes* GetBoundingBoxesVerbose(TessBaseAPI a) { using namespace tesseract; tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; struct bounding_boxes* box_array; box_array = (bounding_boxes*)malloc(sizeof(bounding_boxes)); // linearly resize boxes array int realloc_threshold = 900; int realloc_raise = 1000; int capacity = 1000; box_array->boxes = (bounding_box*)malloc(capacity * sizeof(bounding_box)); box_array->length = 0; api->Recognize(NULL); int block_num = 0; int par_num = 0; int line_num = 0; int word_num = 0; ResultIterator* res_it = api->GetIterator(); while (!res_it->Empty(RIL_BLOCK)) { if (res_it->Empty(RIL_WORD)) { res_it->Next(RIL_WORD); continue; } // Add rows for any new block/paragraph/textline. if (res_it->IsAtBeginningOf(RIL_BLOCK)) { block_num++; par_num = 0; line_num = 0; word_num = 0; } if (res_it->IsAtBeginningOf(RIL_PARA)) { par_num++; line_num = 0; word_num = 0; } if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) { line_num++; word_num = 0; } word_num++; if (box_array->length >= realloc_threshold) { capacity += realloc_raise; box_array->boxes = (bounding_box*)realloc(box_array->boxes, capacity * sizeof(bounding_box)); realloc_threshold += realloc_raise; } box_array->boxes[box_array->length].word = res_it->GetUTF8Text(RIL_WORD); box_array->boxes[box_array->length].confidence = res_it->Confidence(RIL_WORD); res_it->BoundingBox(RIL_WORD, &box_array->boxes[box_array->length].x1, &box_array->boxes[box_array->length].y1, &box_array->boxes[box_array->length].x2, &box_array->boxes[box_array->length].y2); // block, para, line, word numbers box_array->boxes[box_array->length].block_num = block_num; box_array->boxes[box_array->length].par_num = par_num; box_array->boxes[box_array->length].line_num = line_num; box_array->boxes[box_array->length].word_num = word_num; box_array->length++; res_it->Next(RIL_WORD); } return box_array; } bounding_boxes* GetBoundingBoxes(TessBaseAPI a, int pageIteratorLevel) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; struct bounding_boxes* box_array; box_array = (bounding_boxes*)malloc(sizeof(bounding_boxes)); // linearly resize boxes array int realloc_threshold = 900; int realloc_raise = 1000; int capacity = 1000; box_array->boxes = (bounding_box*)malloc(capacity * sizeof(bounding_box)); box_array->length = 0; api->Recognize(NULL); tesseract::ResultIterator* ri = api->GetIterator(); tesseract::PageIteratorLevel level = (tesseract::PageIteratorLevel)pageIteratorLevel; if (ri != 0) { do { if (box_array->length >= realloc_threshold) { capacity += realloc_raise; box_array->boxes = (bounding_box*)realloc(box_array->boxes, capacity * sizeof(bounding_box)); realloc_threshold += realloc_raise; } box_array->boxes[box_array->length].word = ri->GetUTF8Text(level); box_array->boxes[box_array->length].confidence = ri->Confidence(level); ri->BoundingBox(level, &box_array->boxes[box_array->length].x1, &box_array->boxes[box_array->length].y1, &box_array->boxes[box_array->length].x2, &box_array->boxes[box_array->length].y2); box_array->length++; } while (ri->Next(level)); } return box_array; } const char* Version(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; const char* v = api->Version(); return v; } PixImage CreatePixImageByFilePath(char* imagepath) { Pix* image = pixRead(imagepath); return (void*)image; } PixImage CreatePixImageFromBytes(unsigned char* data, int size) { Pix* image = pixReadMem(data, (size_t)size); return (void*)image; } void DestroyPixImage(PixImage pix) { Pix* img = (Pix*)pix; pixDestroy(&img); } const char* GetDataPath() { static tesseract::TessBaseAPI api; api.Init(nullptr, nullptr); return api.GetDatapath(); } <commit_msg>Close duped file number after use: fix #178<commit_after>#if __FreeBSD__ >= 10 #include "/usr/local/include/leptonica/allheaders.h" #include "/usr/local/include/tesseract/baseapi.h" #else #include <leptonica/allheaders.h> #include <tesseract/baseapi.h> #endif #include <stdio.h> #include <unistd.h> #include "tessbridge.h" TessBaseAPI Create() { tesseract::TessBaseAPI* api = new tesseract::TessBaseAPI(); return (void*)api; } void Free(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; api->End(); delete api; } void Clear(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; api->Clear(); } void ClearPersistentCache(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; api->ClearPersistentCache(); } int Init(TessBaseAPI a, char* tessdataprefix, char* languages) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; return api->Init(tessdataprefix, languages); } int Init(TessBaseAPI a, char* tessdataprefix, char* languages, char* configfilepath, char* errbuf) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; // {{{ Redirect STDERR to given buffer fflush(stderr); int original_stderr; original_stderr = dup(STDERR_FILENO); (void)freopen("/dev/null", "a", stderr); setbuf(stderr, errbuf); // }}} int ret; if (configfilepath != NULL) { char* configs[] = {configfilepath}; int configs_size = 1; ret = api->Init(tessdataprefix, languages, tesseract::OEM_DEFAULT, configs, configs_size, NULL, NULL, false); } else { ret = api->Init(tessdataprefix, languages); } // {{{ Restore default stderr (void)freopen("/dev/null", "a", stderr); dup2(original_stderr, STDERR_FILENO); close(original_stderr); setbuf(stderr, NULL); // }}} return ret; } bool SetVariable(TessBaseAPI a, char* name, char* value) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; return api->SetVariable(name, value); } void SetPixImage(TessBaseAPI a, PixImage pix) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; Pix* image = (Pix*)pix; api->SetImage(image); if (api->GetSourceYResolution() < 70) { api->SetSourceResolution(70); } } void SetPageSegMode(TessBaseAPI a, int m) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; tesseract::PageSegMode mode = (tesseract::PageSegMode)m; api->SetPageSegMode(mode); } int GetPageSegMode(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; return api->GetPageSegMode(); } char* UTF8Text(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; return api->GetUTF8Text(); } char* HOCRText(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; return api->GetHOCRText(0); } bounding_boxes* GetBoundingBoxesVerbose(TessBaseAPI a) { using namespace tesseract; tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; struct bounding_boxes* box_array; box_array = (bounding_boxes*)malloc(sizeof(bounding_boxes)); // linearly resize boxes array int realloc_threshold = 900; int realloc_raise = 1000; int capacity = 1000; box_array->boxes = (bounding_box*)malloc(capacity * sizeof(bounding_box)); box_array->length = 0; api->Recognize(NULL); int block_num = 0; int par_num = 0; int line_num = 0; int word_num = 0; ResultIterator* res_it = api->GetIterator(); while (!res_it->Empty(RIL_BLOCK)) { if (res_it->Empty(RIL_WORD)) { res_it->Next(RIL_WORD); continue; } // Add rows for any new block/paragraph/textline. if (res_it->IsAtBeginningOf(RIL_BLOCK)) { block_num++; par_num = 0; line_num = 0; word_num = 0; } if (res_it->IsAtBeginningOf(RIL_PARA)) { par_num++; line_num = 0; word_num = 0; } if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) { line_num++; word_num = 0; } word_num++; if (box_array->length >= realloc_threshold) { capacity += realloc_raise; box_array->boxes = (bounding_box*)realloc(box_array->boxes, capacity * sizeof(bounding_box)); realloc_threshold += realloc_raise; } box_array->boxes[box_array->length].word = res_it->GetUTF8Text(RIL_WORD); box_array->boxes[box_array->length].confidence = res_it->Confidence(RIL_WORD); res_it->BoundingBox(RIL_WORD, &box_array->boxes[box_array->length].x1, &box_array->boxes[box_array->length].y1, &box_array->boxes[box_array->length].x2, &box_array->boxes[box_array->length].y2); // block, para, line, word numbers box_array->boxes[box_array->length].block_num = block_num; box_array->boxes[box_array->length].par_num = par_num; box_array->boxes[box_array->length].line_num = line_num; box_array->boxes[box_array->length].word_num = word_num; box_array->length++; res_it->Next(RIL_WORD); } return box_array; } bounding_boxes* GetBoundingBoxes(TessBaseAPI a, int pageIteratorLevel) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; struct bounding_boxes* box_array; box_array = (bounding_boxes*)malloc(sizeof(bounding_boxes)); // linearly resize boxes array int realloc_threshold = 900; int realloc_raise = 1000; int capacity = 1000; box_array->boxes = (bounding_box*)malloc(capacity * sizeof(bounding_box)); box_array->length = 0; api->Recognize(NULL); tesseract::ResultIterator* ri = api->GetIterator(); tesseract::PageIteratorLevel level = (tesseract::PageIteratorLevel)pageIteratorLevel; if (ri != 0) { do { if (box_array->length >= realloc_threshold) { capacity += realloc_raise; box_array->boxes = (bounding_box*)realloc(box_array->boxes, capacity * sizeof(bounding_box)); realloc_threshold += realloc_raise; } box_array->boxes[box_array->length].word = ri->GetUTF8Text(level); box_array->boxes[box_array->length].confidence = ri->Confidence(level); ri->BoundingBox(level, &box_array->boxes[box_array->length].x1, &box_array->boxes[box_array->length].y1, &box_array->boxes[box_array->length].x2, &box_array->boxes[box_array->length].y2); box_array->length++; } while (ri->Next(level)); } return box_array; } const char* Version(TessBaseAPI a) { tesseract::TessBaseAPI* api = (tesseract::TessBaseAPI*)a; const char* v = api->Version(); return v; } PixImage CreatePixImageByFilePath(char* imagepath) { Pix* image = pixRead(imagepath); return (void*)image; } PixImage CreatePixImageFromBytes(unsigned char* data, int size) { Pix* image = pixReadMem(data, (size_t)size); return (void*)image; } void DestroyPixImage(PixImage pix) { Pix* img = (Pix*)pix; pixDestroy(&img); } const char* GetDataPath() { static tesseract::TessBaseAPI api; api.Init(nullptr, nullptr); return api.GetDatapath(); } <|endoftext|>
<commit_before>// @(#)root/meta:$Id$ // Author: Bianca-Cristina Cristescu 10/07/13 /************************************************************************* * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // The TEnum class implements the enum type. // // // ////////////////////////////////////////////////////////////////////////// #include <iostream> #include "TEnum.h" #include "TEnumConstant.h" #include "TInterpreter.h" #include "TClass.h" #include "TClassEdit.h" #include "TClassTable.h" #include "TProtoClass.h" #include "TROOT.h" ClassImp(TEnum) //______________________________________________________________________________ TEnum::TEnum(const char *name, void *info, TClass *cls) : fInfo(info), fClass(cls) { //Constructor for TEnum class. //It take the name of the TEnum type, specification if it is global //and interpreter info. //Constant List is owner if enum not on global scope (thus constants not //in TROOT::GetListOfGlobals). SetNameTitle(name, "An enum type"); if (cls) { fConstantList.SetOwner(kTRUE); } // Determine fQualName if (0 != strcmp("",GetTitle())){ // It comes from a protoclass fQualName = std::string(GetTitle()) + "::" + GetName(); } else if (GetClass()){ // It comes from a class/ns fQualName = std::string(GetClass()->GetName()) + "::" + GetName(); } else { // it is in the global scope fQualName = GetName(); } } //______________________________________________________________________________ TEnum::~TEnum() { //Destructor } //______________________________________________________________________________ void TEnum::AddConstant(TEnumConstant *constant) { //Add a EnumConstant to the list of constants of the Enum Type. fConstantList.Add(constant); } //______________________________________________________________________________ Bool_t TEnum::IsValid() { // Return true if this enum object is pointing to a currently // loaded enum. If a enum is unloaded after the TEnum // is created, the TEnum will be set to be invalid. // Register the transaction when checking the validity of the object. if (!fInfo && UpdateInterpreterStateMarker()) { DeclId_t newId = gInterpreter->GetEnum(fClass, fName); if (newId) { Update(newId); } return newId != 0; } return fInfo != 0; } //______________________________________________________________________________ Long_t TEnum::Property() const { // Get property description word. For meaning of bits see EProperty. return kIsEnum; } //______________________________________________________________________________ void TEnum::Update(DeclId_t id) { fInfo = (void *)id; } //______________________________________________________________________________ TEnum *TEnum::GetEnum(const std::type_info &ti, ESearchAction sa) { int errorCode = 0; char *demangledEnumName = TClassEdit::DemangleName(ti.name(), errorCode); if (errorCode != 0) { if (!demangledEnumName) { free(demangledEnumName); } std::cerr << "ERROR TEnum::GetEnum - A problem occurred while demangling name.\n"; return nullptr; } const char *constDemangledEnumName = demangledEnumName; TEnum *en = TEnum::GetEnum(constDemangledEnumName, sa); free(demangledEnumName); return en; } //______________________________________________________________________________ TEnum *TEnum::GetEnum(const char *enumName, ESearchAction sa) { // Static function to retrieve enumerator from the ROOT's typesystem. // It has no side effect, except when the load flag is true. In this case, // the load of the library containing the scope of the enumerator is attempted. // There are two top level code paths: the enumerator is scoped or isn't. // If it is not, a lookup in the list of global enums is performed. // If it is, two lookups are carried out for its scope: one in the list of // classes and one in the list of protoclasses. If a scope with the desired name // is found, the enum is searched. If the scope is not found, and the load flag is // true, the aforementioned two steps are performed again after an autoload attempt // with the name of the scope as key is tried out. // If the interpreter lookup flag is false, the ListOfEnums objects are not treated // as such, but rather as THashList objects. This prevents any flow of information // from the interpreter into the ROOT's typesystem: a snapshot of the typesystem // status is taken. // Potential optimisation: reduce number of branches using partial specialisation of // helper functions. TEnum *theEnum = nullptr; // Wrap some gymnastic around the enum finding. The special treatment of the // ListOfEnums objects is located in this routine. auto findEnumInList = [](const TCollection * l, const char * enName, ESearchAction sa_local) { TObject *obj; if (sa_local & kInterpLookup) { obj = l->FindObject(enName); } else { auto enumTable = dynamic_cast<const THashList *>(l); obj = enumTable->THashList::FindObject(enName); } return static_cast<TEnum *>(obj); }; // Helper routine to look fo the scope::enum in the typesystem. // If autoload and interpreter lookup is allowed, TClass::GetClass is called. // If not, the list of classes and the list of protoclasses is inspected. auto searchEnum = [&theEnum, findEnumInList](const char * scopeName, const char * enName, ESearchAction sa_local) { // Check if the scope is a class if (sa_local == (kALoadAndInterpLookup)) { auto scope = TClass::GetClass(scopeName, true); TEnum *en = nullptr; if (scope) en = findEnumInList(scope->GetListOfEnums(), enName, sa_local); return en; } if (auto tClassScope = static_cast<TClass *>(gROOT->GetListOfClasses()->FindObject(scopeName))) { // If this is a class, load only if the user allowed interpreter lookup // If this is a namespace and the user did not allow for interpreter lookup, load but before disable // autoparsing if enabled. bool canLoadEnums (sa_local & kInterpLookup); const bool scopeIsNamespace (tClassScope->Property() & kIsNamespace); const bool oldAutoparseVal = gInterpreter->SetClassAutoparsing(true); if (!oldAutoparseVal) gInterpreter->SetClassAutoparsing(oldAutoparseVal); if (scopeIsNamespace && oldAutoparseVal){ gInterpreter->SetClassAutoparsing(false); canLoadEnums=true; } auto listOfEnums = tClassScope->GetListOfEnums(canLoadEnums); gInterpreter->SetClassAutoparsing(oldAutoparseVal); theEnum = findEnumInList(listOfEnums, enName, sa_local); } // Check if the scope is still a protoclass else if (auto tProtoClassscope = static_cast<TProtoClass *>((gClassTable->GetProtoNorm(scopeName)))) { auto listOfEnums = tProtoClassscope->GetListOfEnums(); if (listOfEnums) theEnum = findEnumInList(listOfEnums, enName, sa_local); } return theEnum; }; const auto lastPos = strrchr(enumName, ':'); if (lastPos != nullptr) { // We have a scope // All of this C gymnastic is to avoid allocations on the heap const auto enName = lastPos + 1; const auto scopeNameSize = ((Long64_t)lastPos - (Long64_t)enumName) / sizeof(decltype(*lastPos)) - 1; char scopeName[scopeNameSize + 1]; // on the stack, +1 for the terminating character '\0' strncpy(scopeName, enumName, scopeNameSize); scopeName[scopeNameSize] = '\0'; // Three levels of search theEnum = searchEnum(scopeName, enName, kNone); if (!theEnum && (sa & kAutoload)) { const auto libsLoaded = gInterpreter->AutoLoad(scopeName); // It could be an enum in a scope which is not selected if (libsLoaded == 0){ gInterpreter->AutoLoad(enumName); } theEnum = searchEnum(scopeName, enName, kAutoload); } if (!theEnum && (sa == kALoadAndInterpLookup)) { if (gDebug > 0) { printf("TEnum::GetEnum: Header Parsing - The enumerator %s is not known to the typesystem: an interpreter lookup will be performed. This can imply parsing of headers. This can be avoided selecting the numerator in the linkdef/selection file.\n", enumName); } theEnum = searchEnum(scopeName, enName, kALoadAndInterpLookup); } } else { // We don't have any scope: this is a global enum theEnum = findEnumInList(gROOT->GetListOfEnums(), enumName, kNone); if (!theEnum && (sa == kAutoload)) { gInterpreter->AutoLoad(enumName); theEnum = findEnumInList(gROOT->GetListOfEnums(), enumName, kAutoload); } if (!theEnum && (sa & kALoadAndInterpLookup)) { if (gDebug > 0) { printf("TEnum::GetEnum: Header Parsing - The enumerator %s is not known to the typesystem: an interpreter lookup will be performed. This can imply parsing of headers. This can be avoided selecting the numerator in the linkdef/selection file.\n", enumName); } theEnum = findEnumInList(gROOT->GetListOfEnums(), enumName, kALoadAndInterpLookup); } } return theEnum; } <commit_msg>Remove dummy title from TEnums<commit_after>// @(#)root/meta:$Id$ // Author: Bianca-Cristina Cristescu 10/07/13 /************************************************************************* * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // The TEnum class implements the enum type. // // // ////////////////////////////////////////////////////////////////////////// #include <iostream> #include "TEnum.h" #include "TEnumConstant.h" #include "TInterpreter.h" #include "TClass.h" #include "TClassEdit.h" #include "TClassTable.h" #include "TProtoClass.h" #include "TROOT.h" ClassImp(TEnum) //______________________________________________________________________________ TEnum::TEnum(const char *name, void *info, TClass *cls) : fInfo(info), fClass(cls) { //Constructor for TEnum class. //It take the name of the TEnum type, specification if it is global //and interpreter info. //Constant List is owner if enum not on global scope (thus constants not //in TROOT::GetListOfGlobals). SetName(name); if (cls) { fConstantList.SetOwner(kTRUE); } // Determine fQualName if (0 != strcmp("",GetTitle())){ // It comes from a protoclass fQualName = std::string(GetTitle()) + "::" + GetName(); } else if (GetClass()){ // It comes from a class/ns fQualName = std::string(GetClass()->GetName()) + "::" + GetName(); } else { // it is in the global scope fQualName = GetName(); } } //______________________________________________________________________________ TEnum::~TEnum() { //Destructor } //______________________________________________________________________________ void TEnum::AddConstant(TEnumConstant *constant) { //Add a EnumConstant to the list of constants of the Enum Type. fConstantList.Add(constant); } //______________________________________________________________________________ Bool_t TEnum::IsValid() { // Return true if this enum object is pointing to a currently // loaded enum. If a enum is unloaded after the TEnum // is created, the TEnum will be set to be invalid. // Register the transaction when checking the validity of the object. if (!fInfo && UpdateInterpreterStateMarker()) { DeclId_t newId = gInterpreter->GetEnum(fClass, fName); if (newId) { Update(newId); } return newId != 0; } return fInfo != 0; } //______________________________________________________________________________ Long_t TEnum::Property() const { // Get property description word. For meaning of bits see EProperty. return kIsEnum; } //______________________________________________________________________________ void TEnum::Update(DeclId_t id) { fInfo = (void *)id; } //______________________________________________________________________________ TEnum *TEnum::GetEnum(const std::type_info &ti, ESearchAction sa) { int errorCode = 0; char *demangledEnumName = TClassEdit::DemangleName(ti.name(), errorCode); if (errorCode != 0) { if (!demangledEnumName) { free(demangledEnumName); } std::cerr << "ERROR TEnum::GetEnum - A problem occurred while demangling name.\n"; return nullptr; } const char *constDemangledEnumName = demangledEnumName; TEnum *en = TEnum::GetEnum(constDemangledEnumName, sa); free(demangledEnumName); return en; } //______________________________________________________________________________ TEnum *TEnum::GetEnum(const char *enumName, ESearchAction sa) { // Static function to retrieve enumerator from the ROOT's typesystem. // It has no side effect, except when the load flag is true. In this case, // the load of the library containing the scope of the enumerator is attempted. // There are two top level code paths: the enumerator is scoped or isn't. // If it is not, a lookup in the list of global enums is performed. // If it is, two lookups are carried out for its scope: one in the list of // classes and one in the list of protoclasses. If a scope with the desired name // is found, the enum is searched. If the scope is not found, and the load flag is // true, the aforementioned two steps are performed again after an autoload attempt // with the name of the scope as key is tried out. // If the interpreter lookup flag is false, the ListOfEnums objects are not treated // as such, but rather as THashList objects. This prevents any flow of information // from the interpreter into the ROOT's typesystem: a snapshot of the typesystem // status is taken. // Potential optimisation: reduce number of branches using partial specialisation of // helper functions. TEnum *theEnum = nullptr; // Wrap some gymnastic around the enum finding. The special treatment of the // ListOfEnums objects is located in this routine. auto findEnumInList = [](const TCollection * l, const char * enName, ESearchAction sa_local) { TObject *obj; if (sa_local & kInterpLookup) { obj = l->FindObject(enName); } else { auto enumTable = dynamic_cast<const THashList *>(l); obj = enumTable->THashList::FindObject(enName); } return static_cast<TEnum *>(obj); }; // Helper routine to look fo the scope::enum in the typesystem. // If autoload and interpreter lookup is allowed, TClass::GetClass is called. // If not, the list of classes and the list of protoclasses is inspected. auto searchEnum = [&theEnum, findEnumInList](const char * scopeName, const char * enName, ESearchAction sa_local) { // Check if the scope is a class if (sa_local == (kALoadAndInterpLookup)) { auto scope = TClass::GetClass(scopeName, true); TEnum *en = nullptr; if (scope) en = findEnumInList(scope->GetListOfEnums(), enName, sa_local); return en; } if (auto tClassScope = static_cast<TClass *>(gROOT->GetListOfClasses()->FindObject(scopeName))) { // If this is a class, load only if the user allowed interpreter lookup // If this is a namespace and the user did not allow for interpreter lookup, load but before disable // autoparsing if enabled. bool canLoadEnums (sa_local & kInterpLookup); const bool scopeIsNamespace (tClassScope->Property() & kIsNamespace); const bool oldAutoparseVal = gInterpreter->SetClassAutoparsing(true); if (!oldAutoparseVal) gInterpreter->SetClassAutoparsing(oldAutoparseVal); if (scopeIsNamespace && oldAutoparseVal){ gInterpreter->SetClassAutoparsing(false); canLoadEnums=true; } auto listOfEnums = tClassScope->GetListOfEnums(canLoadEnums); gInterpreter->SetClassAutoparsing(oldAutoparseVal); theEnum = findEnumInList(listOfEnums, enName, sa_local); } // Check if the scope is still a protoclass else if (auto tProtoClassscope = static_cast<TProtoClass *>((gClassTable->GetProtoNorm(scopeName)))) { auto listOfEnums = tProtoClassscope->GetListOfEnums(); if (listOfEnums) theEnum = findEnumInList(listOfEnums, enName, sa_local); } return theEnum; }; const auto lastPos = strrchr(enumName, ':'); if (lastPos != nullptr) { // We have a scope // All of this C gymnastic is to avoid allocations on the heap const auto enName = lastPos + 1; const auto scopeNameSize = ((Long64_t)lastPos - (Long64_t)enumName) / sizeof(decltype(*lastPos)) - 1; char scopeName[scopeNameSize + 1]; // on the stack, +1 for the terminating character '\0' strncpy(scopeName, enumName, scopeNameSize); scopeName[scopeNameSize] = '\0'; // Three levels of search theEnum = searchEnum(scopeName, enName, kNone); if (!theEnum && (sa & kAutoload)) { const auto libsLoaded = gInterpreter->AutoLoad(scopeName); // It could be an enum in a scope which is not selected if (libsLoaded == 0){ gInterpreter->AutoLoad(enumName); } theEnum = searchEnum(scopeName, enName, kAutoload); } if (!theEnum && (sa == kALoadAndInterpLookup)) { if (gDebug > 0) { printf("TEnum::GetEnum: Header Parsing - The enumerator %s is not known to the typesystem: an interpreter lookup will be performed. This can imply parsing of headers. This can be avoided selecting the numerator in the linkdef/selection file.\n", enumName); } theEnum = searchEnum(scopeName, enName, kALoadAndInterpLookup); } } else { // We don't have any scope: this is a global enum theEnum = findEnumInList(gROOT->GetListOfEnums(), enumName, kNone); if (!theEnum && (sa == kAutoload)) { gInterpreter->AutoLoad(enumName); theEnum = findEnumInList(gROOT->GetListOfEnums(), enumName, kAutoload); } if (!theEnum && (sa & kALoadAndInterpLookup)) { if (gDebug > 0) { printf("TEnum::GetEnum: Header Parsing - The enumerator %s is not known to the typesystem: an interpreter lookup will be performed. This can imply parsing of headers. This can be avoided selecting the numerator in the linkdef/selection file.\n", enumName); } theEnum = findEnumInList(gROOT->GetListOfEnums(), enumName, kALoadAndInterpLookup); } } return theEnum; } <|endoftext|>
<commit_before>/* * Process.cpp * OpenLieroX * * Created by Albert Zeyer on 10.02.09. * code under LGPL * */ #include <cassert> #include "Process.h" #include "Debug.h" #include "FindFile.h" #if ( ! defined(HAVE_BOOST) && defined(WIN32) ) || ( defined(_MSC_VER) && (_MSC_VER <= 1200) ) #include <windows.h> struct ProcessIntern // Stub { int dummy; ProcessIntern(): dummy(0) {}; std::ostream & in(){ return std::cout; }; std::istream & out(){ return std::cin; }; void close() { } bool open( const std::string & cmd, std::vector< std::string > params, const std::string& working_dir ) { errors << "Dedicated server is not compiled into this version of OpenLieroX" << endl; MessageBox( NULL, "ERROR: Dedicated server is not compiled into this version of OpenLieroX", "OpenLieroX", MB_OK ); return false; } }; #elif WIN32 // Install Boost headers for your compiler and #define HAVE_BOOST to compile dedicated server for Win32 // You don't need to link to any lib to compile it, just headers. #ifdef DEBUG // Boost is incompatible with leak detection in MSVC, just disable it for the boost headers #undef new #include <boost/process.hpp> // This one header pulls turdy shitload of Boost headers #define new DEBUG_NEW // Re-enable #else #include <boost/process.hpp> #endif struct ProcessIntern { boost::process::child *p; ProcessIntern(): p(NULL) {}; std::ostream & in() { if (p) return p->get_stdin(); static std::ostringstream os; return os; }; std::istream & out() { if (p) return p->get_stdout(); static std::istringstream is; return is; }; void close() { if (p) { p->get_stdin().close(); } } bool open( const std::string & cmd, std::vector< std::string > params, const std::string& working_dir ) { if(p) delete p; for (std::vector<std::string>::iterator it = params.begin(); it != params.end(); it++) *it = Utf8ToSystemNative(*it); boost::process::context ctx; ctx.m_stdin_behavior = boost::process::capture_stream(); // Pipe for win32 ctx.m_stdout_behavior = boost::process::capture_stream(); ctx.m_stderr_behavior = boost::process::close_stream(); // we don't grap the stderr, it is not outputted anywhere, sadly ctx.m_work_directory = Utf8ToSystemNative(working_dir); try { p = new boost::process::child(boost::process::launch(Utf8ToSystemNative(cmd), params, ctx)); // Throws exception on error } catch( const std::exception & e ) { errors << "Error running command " << cmd << " : " << e.what() << endl; return false; } return true; } ~ProcessIntern(){ close(); if(p) delete p; }; }; #else #include <pstream.h> struct ProcessIntern { ProcessIntern() : p(NULL) {} ~ProcessIntern() { close(); reset(); } redi::pstream* p; std::ostream & in() { return *p; }; std::istream & out() { return p->out(); }; void reset() { if(p) delete p; p = NULL; } void close() { // p << redi::peof; if(p->rdbuf()) p->rdbuf()->kill(); if(p->rdbuf()) p->rdbuf()->kill(SIGKILL); } bool open( const std::string & cmd, std::vector< std::string > params, const std::string& working_dir ) { reset(); p = new redi::pstream(); p->open( cmd, params, redi::pstreams::pstdin | redi::pstreams::pstdout, working_dir ); // we don't grap the stderr, it should directly be forwarded to console return p->rdbuf()->error() == 0; } }; #endif Process::Process() { data = new ProcessIntern(); } Process::~Process() { assert(data != NULL); delete data; data = NULL; } std::ostream& Process::in() { return data->in(); } std::istream& Process::out() { return data->out(); } void Process::close() { data->close(); } #ifdef WIN32 struct SysCommand { std::string exec; std::vector<std::string> params; }; static SysCommand GetExecForScriptInterpreter(const std::string& interpreter) { SysCommand ret; std::string& command = ret.exec; std::vector<std::string>& commandArgs = ret.params; std::string cmdPathRegKey = ""; std::string cmdPathRegValue = ""; // TODO: move that out to an own function! if( interpreter == "python" ) { // TODO: move that out to an own function! command = "python.exe"; commandArgs.clear(); commandArgs.push_back(command); commandArgs.push_back("-u"); cmdPathRegKey = "SOFTWARE\\Python\\PythonCore\\2.5\\InstallPath"; } else if( interpreter == "bash" ) { // TODO: move that out to an own function! command = "bash.exe"; commandArgs.clear(); commandArgs.push_back(command); //commandArgs.push_back("-l"); // Not needed for Cygwin commandArgs.push_back("-c"); cmdPathRegKey = "SOFTWARE\\Cygnus Solutions\\Cygwin\\mounts v2\\/usr/bin"; cmdPathRegValue = "native"; } else if( interpreter == "php" ) { // TODO: move that out to an own function! command = "php.exe"; commandArgs.clear(); commandArgs.push_back(command); commandArgs.push_back("-f"); cmdPathRegKey = "SOFTWARE\\PHP"; cmdPathRegValue = "InstallDir"; } else { command = interpreter + ".exe"; } // TODO: move that out to an own function! if( cmdPathRegKey != "" ) { HKEY hKey; LONG returnStatus; DWORD dwType=REG_SZ; char lszCmdPath[256]=""; DWORD dwSize=255; returnStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, cmdPathRegKey.c_str(), 0L, KEY_READ, &hKey); if (returnStatus != ERROR_SUCCESS) { errors << "registry key " << cmdPathRegKey << "\\" << cmdPathRegValue << " not found - make sure interpreter is installed" << endl; lszCmdPath[0] = '\0'; // Perhaps it is installed in PATH } returnStatus = RegQueryValueEx(hKey, cmdPathRegValue.c_str(), NULL, &dwType,(LPBYTE)lszCmdPath, &dwSize); RegCloseKey(hKey); if (returnStatus != ERROR_SUCCESS) { errors << "registry key " << cmdPathRegKey << "\\" << cmdPathRegValue << " could not be read - make sure interpreter is installed" << endl; lszCmdPath[0] = '\0'; // Perhaps it is installed in PATH } // Add trailing slash if needed std::string path(lszCmdPath); if (path.size()) { if (*path.rbegin() != '\\' && *path.rbegin() != '/') path += '\\'; } command = std::string(lszCmdPath) + command; commandArgs[0] = command; } return ret; } #endif bool Process::open( const std::string & cmd, std::vector< std::string > params, const std::string& working_dir ) { if(params.size() == 0) params.push_back(cmd); std::string realcmd = cmd; #ifdef WIN32 std::string interpreter = GetScriptInterpreterCommandForFile(cmd); if(interpreter != "") { size_t f = interpreter.find(" "); if(f != std::string::npos) interpreter.erase(f); interpreter = GetBaseFilename(interpreter); SysCommand newcmd = GetExecForScriptInterpreter(interpreter); realcmd = newcmd.exec; params.swap( newcmd.params ); params.reserve( params.size() + newcmd.params.size() ); for(std::vector<std::string>::iterator i = newcmd.params.begin(); i != newcmd.params.end(); ++i) params.push_back(*i); notes << "running \"" << realcmd << "\" for script \"" << cmd << "\"" << endl; } #endif return data->open( cmd, params, working_dir ); } <commit_msg>Fixed running ded server on WIN<commit_after>/* * Process.cpp * OpenLieroX * * Created by Albert Zeyer on 10.02.09. * code under LGPL * */ #include <cassert> #include "Process.h" #include "Debug.h" #include "FindFile.h" #if ( ! defined(HAVE_BOOST) && defined(WIN32) ) || ( defined(_MSC_VER) && (_MSC_VER <= 1200) ) #include <windows.h> struct ProcessIntern // Stub { int dummy; ProcessIntern(): dummy(0) {}; std::ostream & in(){ return std::cout; }; std::istream & out(){ return std::cin; }; void close() { } bool open( const std::string & cmd, std::vector< std::string > params, const std::string& working_dir ) { errors << "Dedicated server is not compiled into this version of OpenLieroX" << endl; MessageBox( NULL, "ERROR: Dedicated server is not compiled into this version of OpenLieroX", "OpenLieroX", MB_OK ); return false; } }; #elif WIN32 // Install Boost headers for your compiler and #define HAVE_BOOST to compile dedicated server for Win32 // You don't need to link to any lib to compile it, just headers. #ifdef DEBUG // Boost is incompatible with leak detection in MSVC, just disable it for the boost headers #undef new #include <boost/process.hpp> // This one header pulls turdy shitload of Boost headers #define new DEBUG_NEW // Re-enable #else #include <boost/process.hpp> #endif struct ProcessIntern { boost::process::child *p; ProcessIntern(): p(NULL) {}; std::ostream & in() { if (p) return p->get_stdin(); static std::ostringstream os; return os; }; std::istream & out() { if (p) return p->get_stdout(); static std::istringstream is; return is; }; void close() { if (p) { p->get_stdin().close(); } } bool open( const std::string & cmd, std::vector< std::string > params, const std::string& working_dir ) { if(p) delete p; for (std::vector<std::string>::iterator it = params.begin(); it != params.end(); it++) *it = Utf8ToSystemNative(*it); boost::process::context ctx; ctx.m_stdin_behavior = boost::process::capture_stream(); // Pipe for win32 ctx.m_stdout_behavior = boost::process::capture_stream(); ctx.m_stderr_behavior = boost::process::close_stream(); // we don't grap the stderr, it is not outputted anywhere, sadly ctx.m_work_directory = Utf8ToSystemNative(working_dir); try { p = new boost::process::child(boost::process::launch(Utf8ToSystemNative(cmd), params, ctx)); // Throws exception on error } catch( const std::exception & e ) { errors << "Error running command " << cmd << " : " << e.what() << endl; return false; } return true; } ~ProcessIntern(){ close(); if(p) delete p; }; }; #else #include <pstream.h> struct ProcessIntern { ProcessIntern() : p(NULL) {} ~ProcessIntern() { close(); reset(); } redi::pstream* p; std::ostream & in() { return *p; }; std::istream & out() { return p->out(); }; void reset() { if(p) delete p; p = NULL; } void close() { // p << redi::peof; if(p->rdbuf()) p->rdbuf()->kill(); if(p->rdbuf()) p->rdbuf()->kill(SIGKILL); } bool open( const std::string & cmd, std::vector< std::string > params, const std::string& working_dir ) { reset(); p = new redi::pstream(); p->open( cmd, params, redi::pstreams::pstdin | redi::pstreams::pstdout, working_dir ); // we don't grap the stderr, it should directly be forwarded to console return p->rdbuf()->error() == 0; } }; #endif Process::Process() { data = new ProcessIntern(); } Process::~Process() { assert(data != NULL); delete data; data = NULL; } std::ostream& Process::in() { return data->in(); } std::istream& Process::out() { return data->out(); } void Process::close() { data->close(); } #ifdef WIN32 struct SysCommand { std::string exec; std::vector<std::string> params; }; static SysCommand GetExecForScriptInterpreter(const std::string& interpreter) { SysCommand ret; std::string& command = ret.exec; std::vector<std::string>& commandArgs = ret.params; std::string cmdPathRegKey = ""; std::string cmdPathRegValue = ""; // TODO: move that out to an own function! if( interpreter == "python" ) { // TODO: move that out to an own function! command = "python.exe"; commandArgs.clear(); commandArgs.push_back(command); commandArgs.push_back("-u"); cmdPathRegKey = "SOFTWARE\\Python\\PythonCore\\2.5\\InstallPath"; } else if( interpreter == "bash" ) { // TODO: move that out to an own function! command = "bash.exe"; commandArgs.clear(); commandArgs.push_back(command); //commandArgs.push_back("-l"); // Not needed for Cygwin commandArgs.push_back("-c"); cmdPathRegKey = "SOFTWARE\\Cygnus Solutions\\Cygwin\\mounts v2\\/usr/bin"; cmdPathRegValue = "native"; } else if( interpreter == "php" ) { // TODO: move that out to an own function! command = "php.exe"; commandArgs.clear(); commandArgs.push_back(command); commandArgs.push_back("-f"); cmdPathRegKey = "SOFTWARE\\PHP"; cmdPathRegValue = "InstallDir"; } else { command = interpreter + ".exe"; } // TODO: move that out to an own function! if( cmdPathRegKey != "" ) { HKEY hKey; LONG returnStatus; DWORD dwType=REG_SZ; char lszCmdPath[256]=""; DWORD dwSize=255; returnStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, cmdPathRegKey.c_str(), 0L, KEY_READ, &hKey); if (returnStatus != ERROR_SUCCESS) { errors << "registry key " << cmdPathRegKey << "\\" << cmdPathRegValue << " not found - make sure interpreter is installed" << endl; lszCmdPath[0] = '\0'; // Perhaps it is installed in PATH } returnStatus = RegQueryValueEx(hKey, cmdPathRegValue.c_str(), NULL, &dwType,(LPBYTE)lszCmdPath, &dwSize); RegCloseKey(hKey); if (returnStatus != ERROR_SUCCESS) { errors << "registry key " << cmdPathRegKey << "\\" << cmdPathRegValue << " could not be read - make sure interpreter is installed" << endl; lszCmdPath[0] = '\0'; // Perhaps it is installed in PATH } // Add trailing slash if needed std::string path(lszCmdPath); if (path.size()) { if (*path.rbegin() != '\\' && *path.rbegin() != '/') path += '\\'; } command = std::string(lszCmdPath) + command; commandArgs[0] = command; } return ret; } #endif bool Process::open( const std::string & cmd, std::vector< std::string > params, const std::string& working_dir ) { if(params.size() == 0) params.push_back(cmd); std::string realcmd = cmd; #ifdef WIN32 std::string interpreter = GetScriptInterpreterCommandForFile(cmd); if(interpreter != "") { size_t f = interpreter.find(" "); if(f != std::string::npos) interpreter.erase(f); interpreter = GetBaseFilename(interpreter); SysCommand newcmd = GetExecForScriptInterpreter(interpreter); realcmd = newcmd.exec; params.swap( newcmd.params ); params.reserve( params.size() + newcmd.params.size() ); for(std::vector<std::string>::iterator i = newcmd.params.begin(); i != newcmd.params.end(); ++i) params.push_back(*i); notes << "running \"" << realcmd << "\" for script \"" << cmd << "\"" << endl; } #endif return data->open( realcmd, params, working_dir ); } <|endoftext|>
<commit_before>/********************************** SIGNATURE *********************************\ | ,, | | db `7MM | | ;MM: MM | | ,V^MM. ,pP"Ybd MMpMMMb. .gP"Ya `7Mb,od8 | | ,M `MM 8I `" MM MM ,M' Yb MM' "' | | AbmmmqMA `YMMMa. MM MM 8M"""""" MM | | A' VML L. I8 MM MM YM. , MM | | .AMA. .AMMA.M9mmmP'.JMML JMML.`Mbmmd'.JMML. | | | | | | ,, ,, | | .g8"""bgd `7MM db `7MM | | .dP' `M MM MM | | dM' ` MM `7MM ,p6"bo MM ,MP' | | MM MM MM 6M' OO MM ;Y | | MM. `7MMF' MM MM 8M MM;Mm | | `Mb. MM MM MM YM. , MM `Mb. | | `"bmmmdPY .JMML..JMML.YMbmd'.JMML. YA. | | | \******************************************************************************/ /*********************************** LICENSE **********************************\ | Copyright (c) 2013, Asher Glick | | 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. | \******************************************************************************/ #include <openssl/sha.h> #include <unistd.h> #include <math.h> #include <pwd.h> #include <stdio.h> #include <sys/stat.h> #include <fstream> #include <iostream> #include <iomanip> #include <string> #include <vector> using namespace std; #define HASHSIZE 32 ////////////////////////////////////////////////////////////////////////////// //////////////////////// BASE MODIFICATION FUNCTIONS ///////////////////////// ////////////////////////////////////////////////////////////////////////////// int calculateNewBaseLength(int oldBase, int oldBaseLength, int newBase) { double logOldBase = log(oldBase); double logNewBase = log(newBase); double newBaseLength = oldBaseLength * (logOldBase/logNewBase); int intNewBaseLength = newBaseLength; if (newBaseLength > intNewBaseLength) intNewBaseLength += 1; // round up return intNewBaseLength; } // Trims all of the preceding zeros off a function vector<int> trimNumber(vector<int> v) { vector<int>::iterator i = v.begin(); while (i != v.end()-1) { if (*i != 0) { break; } i++; } return vector<int>(i, v.end()); } // creats a new base number of the old base value of 10 vector<int> tenInOldBase(int oldBase, int newBase) { // int ten[] = {1,0}; int newBaseLength = calculateNewBaseLength(oldBase, 2, newBase); int maxLength = newBaseLength>2?newBaseLength:2; vector <int> newNumber(maxLength, 0); int currentNumber = oldBase; for (int i = maxLength-1; i >=0; i--) { newNumber[i] = currentNumber % newBase; currentNumber = currentNumber / newBase; } newNumber = trimNumber(newNumber); // return calculateNewBase(oldBase, 2, newBase, ten); return newNumber; } // Multiplies two base n numbers together vector <int> multiply(int base, vector<int> firstNumber, vector<int> secondNumber) { int resultLength = firstNumber.size() + secondNumber.size(); vector<int> resultNumber(resultLength, 0); for (int i = firstNumber.size() - 1 ; i >= 0; i--) { for (int j = secondNumber.size() - 1; j >= 0; j--) { resultNumber[i+j + 1] += firstNumber[i] * secondNumber[j]; } } for (int i = resultNumber.size() -1; i > 0; i--) { if (resultNumber[i] >= base) { resultNumber[i-1] += resultNumber[i]/base; resultNumber[i] = resultNumber[i] % base; } } return trimNumber(resultNumber); } vector<int> calculateNewBase(int oldBase, int newBase, vector<int> oldNumber) { int newNumberLength = calculateNewBaseLength(oldBase, oldNumber.size(), newBase); vector<int> newNumber(newNumberLength, 0); vector<int> conversionFactor(1, 1); // a single digit of 1 for (int i = oldNumber.size()-1; i >= 0; i--) { vector<int> difference(conversionFactor); // size the vector for (unsigned int j = 0; j < difference.size(); j++) { difference[j] *= oldNumber[i]; } // add the vector for (unsigned int j = 0; j < difference.size(); j++) { int newNumberIndex = j + newNumberLength - difference.size(); newNumber[newNumberIndex] += difference[j]; } // increment the conversion factor by oldbase 10 conversionFactor = multiply(newBase, conversionFactor, tenInOldBase(oldBase,newBase)); } // Flatten number to base for (int i = newNumber.size()-1; i >=0; i--) { if (newNumber[i] >= newBase) { newNumber[i-1] += newNumber[i]/newBase; newNumber[i] = newNumber[i]%newBase; } } return trimNumber(newNumber); } ////////////////////////////////////////////////////////////////////////////// /////////////////////////////// READ SETTINGS //////////////////////////////// ////////////////////////////////////////////////////////////////////////////// struct settingWrapper { string domain; string allowedCharacters; uint maxCharacters; string regex; }; settingWrapper getSettings(string domain) { string hexCharacters = "0123456789abcdef"; settingWrapper settings; // open ~/.passcodes/config ifstream configFile; struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; string configPath = string(homedir) + "/.passcodes/"; string subscriptionPath = string(homedir) + "/.passcodes/subscriptions"; configFile.open(subscriptionPath.c_str()); if (!configFile.is_open()) { cout << "File does not exist" << endl; #if defined(_WIN32) _mkdir(strPath.c_str()); #else mkdir(configPath.c_str(), 0777); // notice that 777 is different than 0777 #endif ofstream testFile; testFile.open(subscriptionPath.c_str()); testFile << "http://passcod.es/global.chanel" << endl; testFile << "http://asherglick.github.io/Passcodes" << endl; testFile.close(); configFile.open(subscriptionPath.c_str()); } string subscription = ""; if (configFile.is_open()) { // For each subscription look up the while (getline(configFile, subscription)) { // Get a hash of the subscription path, hashses are used to insure // the folder the cashe exists in is a valid folder name unsigned char hash[20]; SHA1((unsigned char*)subscription.c_str(), subscription.size(), hash); string cashedSubscriptionName = ""; for (int i = 0; i < 4; i++) { cashedSubscriptionName += hexCharacters[hash[i]&0x0F]; cashedSubscriptionName += hexCharacters[(hash[i]>>4)&0x0F]; } // Open the domain in the current subscription folder ifstream cashedSubscritption; string subscriptionPath = configPath + "cashe/" + cashedSubscriptionName + "/" + domain; cashedSubscritption.open(subscriptionPath); if (cashedSubscritption.is_open()) { string maxLength = ""; getline(cashedSubscritption, maxLength); if (maxLength != "") settings.maxCharacters = stoi(maxLength); string regex = ""; getline(cashedSubscritption, regex); if (regex != "") settings.regex = regex; string allowedCharacters = ""; getline(cashedSubscritption, allowedCharacters); if (allowedCharacters != "") settings.allowedCharacters = allowedCharacters; string parent = ""; getline(cashedSubscritption, parent); if (parent != "") settings.domain = parent; } else { //cout << "No cashed version of " << domain << " exists from the subscrition " << subscription << endl; //cout << "Run \"passcodes --update\" to update the cashe from all your subscriptions" << endl; } //cout << subscriptionPath << endl; } } // look for 'subscriptions' section // open each file in the subscriptions list in order // ~/.passcodes/<subscription>/<domain> // add any non-blank entry to the settings, latter entries overriding former return settings; } ////////////////////////////////////////////////////////////////////////////// //////////////////////// GENERATE PASSWORD FUNCTIONS ///////////////////////// ////////////////////////////////////////////////////////////////////////////// #define ITERATIONCOUNT 100000 /****************************** GENERATE PASSWORD *****************************\ | The generate password function takes in the domain and the master password | | then returns the 16 character long base64 password based off of the sha256 | | hash o | \******************************************************************************/ string generatePassword(string domain, string masterpass ) { settingWrapper settings = getSettings(domain); // cout << "MAX LENGTH: " << settings.maxCharacters << endl; // cout << "ALLOWED CHARACTERS: " << settings.allowedCharacters << endl; // cout << "DOMAIN: " << settings.domain << endl; // cout << "REGEX MATHC: " << settings.regex << endl; string prehash = settings.domain+masterpass; unsigned char hash[HASHSIZE]; string output = ""; for (int i = 0; i < ITERATIONCOUNT; i++) { SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash); prehash = ""; for (int j = 0; j < HASHSIZE; j++) { prehash += hash[j]; } } vector<int> hashedValues(32); for (int j = 0; j < HASHSIZE; j++) { hashedValues[j] = static_cast<int>(hash[j]); } int newbase = settings.allowedCharacters.length(); cout << "NEWBASE: " << newbase << endl; vector<int> newValues = calculateNewBase(256, newbase, hashedValues); for (unsigned int i = 0; i < 16 && i < settings.maxCharacters; i++) { cout << settings.allowedCharacters[newValues[i]]; } return "Failed"; } /************************************ HELP ************************************\ | The help fucntion displays the help text to the user, it is called if the | | help flag is present or if the user has used the program incorrectly | \******************************************************************************/ void help() { cout << "Welcome to the command line application for passcod.es\n" "written by Asher Glick (aglick@aglick.com)\n" "\n" "Usage\n" " passcodes [-s] [-h] [-d] <domain text> [-p] <password text>\n" "\n" "Commands\n" " -d Any text that comes after this flag is set as the domain\n" " If no domain is given it is prompted for\n" " -p Any text that comes after this flag is set as the password\n" " If this flag is set a warning will be displayed\n" " If this flag is not set the user is prompted for a password\n" " -h Display the help menu\n" " No other functions will be run if this flag is present\n" " -s Suppress warnings\n" " No warning messages will appear from using the -p flag\n" << endl; } /************************************ MAIN ************************************\ | The main function handles all of the arguments, parsing them into the | | correct locations. Then prompts the user to enter the domain and password | | if they have not been specified in the arguments. Finaly it outputs the | | generated password to the user | \******************************************************************************/ int main(int argc, char* argv[]) { bool silent = false; string domain = ""; string password = ""; string *pointer = NULL; // Parse the arguments for (int i = 1; i < argc; i++) { if (string(argv[i]) == "-p") { // password flag pointer = &password; } else if (string(argv[i]) == "-d") { // domain flag pointer = &domain; } else if (string(argv[i]) == "-s") { // silent flag silent = true; } else if (string(argv[i]) == "-h") { // help flag help(); return 0; } else { if (pointer == NULL) { help(); return 0; } else { *pointer += argv[i]; } } } // If there is no domain given, prompt the user for a domain if (domain == "") { cout << "Enter Domain: "; getline(cin, domain); } // If there is a password given and the silent flag is not present // give the user a warning telling them that the password flag is insecure if (password != "" && !silent) { cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl; } // If there is not a password given, prompt the user for a password securly else if (password == "") { password = string(getpass("Enter Password: ")); } // Output the generated Password to the user cout << generatePassword(domain, password) << endl; } <commit_msg>removed debug statements<commit_after>/********************************** SIGNATURE *********************************\ | ,, | | db `7MM | | ;MM: MM | | ,V^MM. ,pP"Ybd MMpMMMb. .gP"Ya `7Mb,od8 | | ,M `MM 8I `" MM MM ,M' Yb MM' "' | | AbmmmqMA `YMMMa. MM MM 8M"""""" MM | | A' VML L. I8 MM MM YM. , MM | | .AMA. .AMMA.M9mmmP'.JMML JMML.`Mbmmd'.JMML. | | | | | | ,, ,, | | .g8"""bgd `7MM db `7MM | | .dP' `M MM MM | | dM' ` MM `7MM ,p6"bo MM ,MP' | | MM MM MM 6M' OO MM ;Y | | MM. `7MMF' MM MM 8M MM;Mm | | `Mb. MM MM MM YM. , MM `Mb. | | `"bmmmdPY .JMML..JMML.YMbmd'.JMML. YA. | | | \******************************************************************************/ /*********************************** LICENSE **********************************\ | Copyright (c) 2013, Asher Glick | | 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. | \******************************************************************************/ #include <openssl/sha.h> #include <unistd.h> #include <math.h> #include <pwd.h> #include <stdio.h> #include <sys/stat.h> #include <fstream> #include <iostream> #include <iomanip> #include <string> #include <vector> using namespace std; #define HASHSIZE 32 ////////////////////////////////////////////////////////////////////////////// //////////////////////// BASE MODIFICATION FUNCTIONS ///////////////////////// ////////////////////////////////////////////////////////////////////////////// int calculateNewBaseLength(int oldBase, int oldBaseLength, int newBase) { double logOldBase = log(oldBase); double logNewBase = log(newBase); double newBaseLength = oldBaseLength * (logOldBase/logNewBase); int intNewBaseLength = newBaseLength; if (newBaseLength > intNewBaseLength) intNewBaseLength += 1; // round up return intNewBaseLength; } // Trims all of the preceding zeros off a function vector<int> trimNumber(vector<int> v) { vector<int>::iterator i = v.begin(); while (i != v.end()-1) { if (*i != 0) { break; } i++; } return vector<int>(i, v.end()); } // creats a new base number of the old base value of 10 vector<int> tenInOldBase(int oldBase, int newBase) { // int ten[] = {1,0}; int newBaseLength = calculateNewBaseLength(oldBase, 2, newBase); int maxLength = newBaseLength>2?newBaseLength:2; vector <int> newNumber(maxLength, 0); int currentNumber = oldBase; for (int i = maxLength-1; i >=0; i--) { newNumber[i] = currentNumber % newBase; currentNumber = currentNumber / newBase; } newNumber = trimNumber(newNumber); // return calculateNewBase(oldBase, 2, newBase, ten); return newNumber; } // Multiplies two base n numbers together vector <int> multiply(int base, vector<int> firstNumber, vector<int> secondNumber) { int resultLength = firstNumber.size() + secondNumber.size(); vector<int> resultNumber(resultLength, 0); for (int i = firstNumber.size() - 1 ; i >= 0; i--) { for (int j = secondNumber.size() - 1; j >= 0; j--) { resultNumber[i+j + 1] += firstNumber[i] * secondNumber[j]; } } for (int i = resultNumber.size() -1; i > 0; i--) { if (resultNumber[i] >= base) { resultNumber[i-1] += resultNumber[i]/base; resultNumber[i] = resultNumber[i] % base; } } return trimNumber(resultNumber); } vector<int> calculateNewBase(int oldBase, int newBase, vector<int> oldNumber) { int newNumberLength = calculateNewBaseLength(oldBase, oldNumber.size(), newBase); vector<int> newNumber(newNumberLength, 0); vector<int> conversionFactor(1, 1); // a single digit of 1 for (int i = oldNumber.size()-1; i >= 0; i--) { vector<int> difference(conversionFactor); // size the vector for (unsigned int j = 0; j < difference.size(); j++) { difference[j] *= oldNumber[i]; } // add the vector for (unsigned int j = 0; j < difference.size(); j++) { int newNumberIndex = j + newNumberLength - difference.size(); newNumber[newNumberIndex] += difference[j]; } // increment the conversion factor by oldbase 10 conversionFactor = multiply(newBase, conversionFactor, tenInOldBase(oldBase,newBase)); } // Flatten number to base for (int i = newNumber.size()-1; i >=0; i--) { if (newNumber[i] >= newBase) { newNumber[i-1] += newNumber[i]/newBase; newNumber[i] = newNumber[i]%newBase; } } return trimNumber(newNumber); } ////////////////////////////////////////////////////////////////////////////// /////////////////////////////// READ SETTINGS //////////////////////////////// ////////////////////////////////////////////////////////////////////////////// struct settingWrapper { string domain; string allowedCharacters; uint maxCharacters; string regex; }; settingWrapper getSettings(string domain) { string hexCharacters = "0123456789abcdef"; settingWrapper settings; // open ~/.passcodes/config ifstream configFile; struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; string configPath = string(homedir) + "/.passcodes/"; string subscriptionPath = string(homedir) + "/.passcodes/subscriptions"; configFile.open(subscriptionPath.c_str()); if (!configFile.is_open()) { cout << "File does not exist" << endl; #if defined(_WIN32) _mkdir(strPath.c_str()); #else mkdir(configPath.c_str(), 0777); // notice that 777 is different than 0777 #endif ofstream testFile; testFile.open(subscriptionPath.c_str()); testFile << "http://passcod.es/global.chanel" << endl; testFile << "http://asherglick.github.io/Passcodes" << endl; testFile.close(); configFile.open(subscriptionPath.c_str()); } string subscription = ""; if (configFile.is_open()) { // For each subscription look up the while (getline(configFile, subscription)) { // Get a hash of the subscription path, hashses are used to insure // the folder the cashe exists in is a valid folder name unsigned char hash[20]; SHA1((unsigned char*)subscription.c_str(), subscription.size(), hash); string cashedSubscriptionName = ""; for (int i = 0; i < 4; i++) { cashedSubscriptionName += hexCharacters[hash[i]&0x0F]; cashedSubscriptionName += hexCharacters[(hash[i]>>4)&0x0F]; } // Open the domain in the current subscription folder ifstream cashedSubscritption; string subscriptionPath = configPath + "cashe/" + cashedSubscriptionName + "/" + domain; cashedSubscritption.open(subscriptionPath); if (cashedSubscritption.is_open()) { string maxLength = ""; getline(cashedSubscritption, maxLength); if (maxLength != "") settings.maxCharacters = stoi(maxLength); string regex = ""; getline(cashedSubscritption, regex); if (regex != "") settings.regex = regex; string allowedCharacters = ""; getline(cashedSubscritption, allowedCharacters); if (allowedCharacters != "") settings.allowedCharacters = allowedCharacters; string parent = ""; getline(cashedSubscritption, parent); if (parent != "") settings.domain = parent; } else { //cout << "No cashed version of " << domain << " exists from the subscrition " << subscription << endl; //cout << "Run \"passcodes --update\" to update the cashe from all your subscriptions" << endl; } //cout << subscriptionPath << endl; } } // look for 'subscriptions' section // open each file in the subscriptions list in order // ~/.passcodes/<subscription>/<domain> // add any non-blank entry to the settings, latter entries overriding former return settings; } ////////////////////////////////////////////////////////////////////////////// //////////////////////// GENERATE PASSWORD FUNCTIONS ///////////////////////// ////////////////////////////////////////////////////////////////////////////// #define ITERATIONCOUNT 100000 /****************************** GENERATE PASSWORD *****************************\ | The generate password function takes in the domain and the master password | | then returns the 16 character long base64 password based off of the sha256 | | hash o | \******************************************************************************/ string generatePassword(string domain, string masterpass ) { settingWrapper settings = getSettings(domain); // cout << "MAX LENGTH: " << settings.maxCharacters << endl; // cout << "ALLOWED CHARACTERS: " << settings.allowedCharacters << endl; // cout << "DOMAIN: " << settings.domain << endl; // cout << "REGEX MATHC: " << settings.regex << endl; string prehash = settings.domain+masterpass; unsigned char hash[HASHSIZE]; string output = ""; for (int i = 0; i < ITERATIONCOUNT; i++) { SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash); prehash = ""; for (int j = 0; j < HASHSIZE; j++) { prehash += hash[j]; } } vector<int> hashedValues(32); for (int j = 0; j < HASHSIZE; j++) { hashedValues[j] = static_cast<int>(hash[j]); } int newbase = settings.allowedCharacters.length(); vector<int> newValues = calculateNewBase(256, newbase, hashedValues); string password = ""; for (unsigned int i = 0; i < 16 && i < settings.maxCharacters; i++) { password += settings.allowedCharacters[newValues[i]]; } return password; } /************************************ HELP ************************************\ | The help fucntion displays the help text to the user, it is called if the | | help flag is present or if the user has used the program incorrectly | \******************************************************************************/ void help() { cout << "Welcome to the command line application for passcod.es\n" "written by Asher Glick (aglick@aglick.com)\n" "\n" "Usage\n" " passcodes [-s] [-h] [-d] <domain text> [-p] <password text>\n" "\n" "Commands\n" " -d Any text that comes after this flag is set as the domain\n" " If no domain is given it is prompted for\n" " -p Any text that comes after this flag is set as the password\n" " If this flag is set a warning will be displayed\n" " If this flag is not set the user is prompted for a password\n" " -h Display the help menu\n" " No other functions will be run if this flag is present\n" " -s Suppress warnings\n" " No warning messages will appear from using the -p flag\n" << endl; } /************************************ MAIN ************************************\ | The main function handles all of the arguments, parsing them into the | | correct locations. Then prompts the user to enter the domain and password | | if they have not been specified in the arguments. Finaly it outputs the | | generated password to the user | \******************************************************************************/ int main(int argc, char* argv[]) { bool silent = false; string domain = ""; string password = ""; string *pointer = NULL; // Parse the arguments for (int i = 1; i < argc; i++) { if (string(argv[i]) == "-p") { // password flag pointer = &password; } else if (string(argv[i]) == "-d") { // domain flag pointer = &domain; } else if (string(argv[i]) == "-s") { // silent flag silent = true; } else if (string(argv[i]) == "-h") { // help flag help(); return 0; } else { if (pointer == NULL) { help(); return 0; } else { *pointer += argv[i]; } } } // If there is no domain given, prompt the user for a domain if (domain == "") { cout << "Enter Domain: "; getline(cin, domain); } // If there is a password given and the silent flag is not present // give the user a warning telling them that the password flag is insecure if (password != "" && !silent) { cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl; } // If there is not a password given, prompt the user for a password securly else if (password == "") { password = string(getpass("Enter Password: ")); } // Output the generated Password to the user cout << generatePassword(domain, password) << endl; } <|endoftext|>
<commit_before>/********************************** SIGNATURE *********************************\ | ,, | | db `7MM | | ;MM: MM | | ,V^MM. ,pP"Ybd MMpMMMb. .gP"Ya `7Mb,od8 | | ,M `MM 8I `" MM MM ,M' Yb MM' "' | | AbmmmqMA `YMMMa. MM MM 8M"""""" MM | | A' VML L. I8 MM MM YM. , MM | | .AMA. .AMMA.M9mmmP'.JMML JMML.`Mbmmd'.JMML. | | | | | | ,, ,, | | .g8"""bgd `7MM db `7MM | | .dP' `M MM MM | | dM' ` MM `7MM ,p6"bo MM ,MP' | | MM MM MM 6M' OO MM ;Y | | MM. `7MMF' MM MM 8M MM;Mm | | `Mb. MM MM MM YM. , MM `Mb. | | `"bmmmdPY .JMML..JMML.YMbmd'.JMML. YA. | | | \******************************************************************************/ /*********************************** LICENSE **********************************\ | Copyright (c) 2013, Asher Glick | | 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. | \******************************************************************************/ #include <openssl/sha.h> #include <unistd.h> #include <math.h> #include <pwd.h> #include <stdio.h> #include <sys/stat.h> #include <fstream> #include <iostream> #include <iomanip> #include <string> #include <vector> using namespace std; #define HASHSIZE 32 ////////////////////////////////////////////////////////////////////////////// //////////////////////// BASE MODIFICATION FUNCTIONS ///////////////////////// ////////////////////////////////////////////////////////////////////////////// int calculateNewBaseLength(int oldBase, int oldBaseLength, int newBase) { double logOldBase = log(oldBase); double logNewBase = log(newBase); double newBaseLength = oldBaseLength * (logOldBase/logNewBase); int intNewBaseLength = newBaseLength; if (newBaseLength > intNewBaseLength) intNewBaseLength += 1; // round up return intNewBaseLength; } // Trims all of the preceding zeros off a function vector<int> trimNumber(vector<int> v) { vector<int>::iterator i = v.begin(); while (i != v.end()-1) { if (*i != 0) { break; } i++; } return vector<int>(i, v.end()); } // creats a new base number of the old base value of 10 vector<int> tenInOldBase(int oldBase, int newBase) { // int ten[] = {1,0}; int newBaseLength = calculateNewBaseLength(oldBase, 2, newBase); int maxLength = newBaseLength>2?newBaseLength:2; vector <int> newNumber(maxLength, 0); int currentNumber = oldBase; for (int i = maxLength-1; i >=0; i--) { newNumber[i] = currentNumber % newBase; currentNumber = currentNumber / newBase; } newNumber = trimNumber(newNumber); // return calculateNewBase(oldBase, 2, newBase, ten); return newNumber; } // Multiplies two base n numbers together vector <int> multiply(int base, vector<int> firstNumber, vector<int> secondNumber) { int resultLength = firstNumber.size() + secondNumber.size(); vector<int> resultNumber(resultLength, 0); for (int i = firstNumber.size() - 1 ; i >= 0; i--) { for (int j = secondNumber.size() - 1; j >= 0; j--) { resultNumber[i+j + 1] += firstNumber[i] * secondNumber[j]; } } for (int i = resultNumber.size() -1; i > 0; i--) { if (resultNumber[i] >= base) { resultNumber[i-1] += resultNumber[i]/base; resultNumber[i] = resultNumber[i] % base; } } return trimNumber(resultNumber); } vector<int> calculateNewBase(int oldBase, int newBase, vector<int> oldNumber) { int newNumberLength = calculateNewBaseLength(oldBase, oldNumber.size(), newBase); vector<int> newNumber(newNumberLength, 0); vector<int> conversionFactor(1, 1); // a single digit of 1 for (int i = oldNumber.size()-1; i >= 0; i--) { vector<int> difference(conversionFactor); // size the vector for (unsigned int j = 0; j < difference.size(); j++) { difference[j] *= oldNumber[i]; } // add the vector for (unsigned int j = 0; j < difference.size(); j++) { int newNumberIndex = j + newNumberLength - difference.size(); newNumber[newNumberIndex] += difference[j]; } // increment the conversion factor by oldbase 10 conversionFactor = multiply(newBase, conversionFactor, tenInOldBase(oldBase,newBase)); } // Flatten number to base for (int i = newNumber.size()-1; i >=0; i--) { if (newNumber[i] >= newBase) { newNumber[i-1] += newNumber[i]/newBase; newNumber[i] = newNumber[i]%newBase; } } return trimNumber(newNumber); } ////////////////////////////////////////////////////////////////////////////// /////////////////////////////// READ SETTINGS //////////////////////////////// ////////////////////////////////////////////////////////////////////////////// struct settingWrapper { string domain; string allowedCharacters; uint maxCharacters; string regex; }; settingWrapper getSettings(string domain) { string hexCharacters = "0123456789abcdef"; settingWrapper settings; // open ~/.passcodes/config ifstream configFile; struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; string configPath = string(homedir) + "/.passcodes/"; string subscriptionPath = string(homedir) + "/.passcodes/subscriptions"; configFile.open(subscriptionPath.c_str()); if (!configFile.is_open()) { cout << "File does not exist" << endl; #if defined(_WIN32) _mkdir(strPath.c_str()); #else mkdir(configPath.c_str(), 0777); // notice that 777 is different than 0777 #endif ofstream testFile; testFile.open(subscriptionPath.c_str()); testFile << "http://passcod.es/global.chanel" << endl; testFile << "http://asherglick.github.io/Passcodes" << endl; testFile.close(); configFile.open(subscriptionPath.c_str()); } cout << "opening file" << endl; //configFile.open(subscriptionPath.c_str()); string subscription = ""; if (configFile.is_open()) { cout << "File is open" << endl; while (getline(configFile, subscription)) { unsigned char hash[20]; SHA1((unsigned char*)subscription.c_str(), subscription.size(), hash); string cashedSubscriptionName = ""; for (int i = 0; i < 4; i++) { cashedSubscriptionName += hexCharacters[hash[i]&0x0F]; cashedSubscriptionName += hexCharacters[(hash[i]>>4)&0x0F]; } ifstream subscription; string subscriptionPath = configPath + "cashe/" + cashedSubscriptionName + "/" + domain; subscription.open(subscriptionPath); string maxLength cout << subscriptionPath << endl; } } // look for 'subscriptions' section // open each file in the subscriptions list in order // ~/.passcodes/<subscription>/<domain> // add any non-blank entry to the settings, latter entries overriding former return settings; } ////////////////////////////////////////////////////////////////////////////// //////////////////////// GENERATE PASSWORD FUNCTIONS ///////////////////////// ////////////////////////////////////////////////////////////////////////////// #define ITERATIONCOUNT 100000 /****************************** GENERATE PASSWORD *****************************\ | The generate password function takes in the domain and the master password | | then returns the 16 character long base64 password based off of the sha256 | | hash | \******************************************************************************/ string generatePassword(string domain, string masterpass ) { settingWrapper settings = getSettings(domain); string prehash = domain+masterpass; unsigned char hash[HASHSIZE]; string output = ""; for (int i = 0; i < ITERATIONCOUNT; i++) { SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash); prehash = ""; for (int j = 0; j < HASHSIZE; j++) { prehash += hash[j]; } } vector<int> hashedValues(32); for (int j = 0; j < HASHSIZE; j++) { hashedValues[j] = static_cast<int>(hash[j]); } vector<int> newValues = calculateNewBase(256, 64, hashedValues); for (int val : newValues) { cout << val << ", "; } return "Failed"; } /************************************ HELP ************************************\ | The help fucntion displays the help text to the user, it is called if the | | help flag is present or if the user has used the program incorrectly | \******************************************************************************/ void help() { cout << "Welcome to the command line application for passcod.es\n" "written by Asher Glick (aglick@aglick.com)\n" "\n" "Usage\n" " passcodes [-s] [-h] [-d] <domain text> [-p] <password text>\n" "\n" "Commands\n" " -d Any text that comes after this flag is set as the domain\n" " If no domain is given it is prompted for\n" " -p Any text that comes after this flag is set as the password\n" " If this flag is set a warning will be displayed\n" " If this flag is not set the user is prompted for a password\n" " -h Display the help menu\n" " No other functions will be run if this flag is present\n" " -s Suppress warnings\n" " No warning messages will appear from using the -p flag\n" << endl; } /************************************ MAIN ************************************\ | The main function handles all of the arguments, parsing them into the | | correct locations. Then prompts the user to enter the domain and password | | if they have not been specified in the arguments. Finaly it outputs the | | generated password to the user | \******************************************************************************/ int main(int argc, char* argv[]) { bool silent = false; string domain = ""; string password = ""; string *pointer = NULL; // Parse the arguments for (int i = 1; i < argc; i++) { if (string(argv[i]) == "-p") { // password flag pointer = &password; } else if (string(argv[i]) == "-d") { // domain flag pointer = &domain; } else if (string(argv[i]) == "-s") { // silent flag silent = true; } else if (string(argv[i]) == "-h") { // help flag help(); return 0; } else { if (pointer == NULL) { help(); return 0; } else { *pointer += argv[i]; } } } // If there is no domain given, prompt the user for a domain if (domain == "") { cout << "Enter Domain: "; getline(cin, domain); } // If there is a password given and the silent flag is not present // give the user a warning telling them that the password flag is insecure if (password != "" && !silent) { cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl; } // If there is not a password given, prompt the user for a password securly else if (password == "") { password = string(getpass("Enter Password: ")); } // Output the generated Password to the user cout << generatePassword(domain, password) << endl; } <commit_msg>added a list of all typable characters to core<commit_after>/********************************** SIGNATURE *********************************\ | ,, | | db `7MM | | ;MM: MM | | ,V^MM. ,pP"Ybd MMpMMMb. .gP"Ya `7Mb,od8 | | ,M `MM 8I `" MM MM ,M' Yb MM' "' | | AbmmmqMA `YMMMa. MM MM 8M"""""" MM | | A' VML L. I8 MM MM YM. , MM | | .AMA. .AMMA.M9mmmP'.JMML JMML.`Mbmmd'.JMML. | | | | | | ,, ,, | | .g8"""bgd `7MM db `7MM | | .dP' `M MM MM | | dM' ` MM `7MM ,p6"bo MM ,MP' | | MM MM MM 6M' OO MM ;Y | | MM. `7MMF' MM MM 8M MM;Mm | | `Mb. MM MM MM YM. , MM `Mb. | | `"bmmmdPY .JMML..JMML.YMbmd'.JMML. YA. | | | \******************************************************************************/ /*********************************** LICENSE **********************************\ | Copyright (c) 2013, Asher Glick | | 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. | \******************************************************************************/ #include <openssl/sha.h> #include <unistd.h> #include <math.h> #include <pwd.h> #include <stdio.h> #include <sys/stat.h> #include <fstream> #include <iostream> #include <iomanip> #include <string> #include <vector> using namespace std; #define HASHSIZE 32 string allCharacters = " !\"#$%&'()*+,-./1234567890:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; ////////////////////////////////////////////////////////////////////////////// //////////////////////// BASE MODIFICATION FUNCTIONS ///////////////////////// ////////////////////////////////////////////////////////////////////////////// int calculateNewBaseLength(int oldBase, int oldBaseLength, int newBase) { double logOldBase = log(oldBase); double logNewBase = log(newBase); double newBaseLength = oldBaseLength * (logOldBase/logNewBase); int intNewBaseLength = newBaseLength; if (newBaseLength > intNewBaseLength) intNewBaseLength += 1; // round up return intNewBaseLength; } // Trims all of the preceding zeros off a function vector<int> trimNumber(vector<int> v) { vector<int>::iterator i = v.begin(); while (i != v.end()-1) { if (*i != 0) { break; } i++; } return vector<int>(i, v.end()); } // creats a new base number of the old base value of 10 vector<int> tenInOldBase(int oldBase, int newBase) { // int ten[] = {1,0}; int newBaseLength = calculateNewBaseLength(oldBase, 2, newBase); int maxLength = newBaseLength>2?newBaseLength:2; vector <int> newNumber(maxLength, 0); int currentNumber = oldBase; for (int i = maxLength-1; i >=0; i--) { newNumber[i] = currentNumber % newBase; currentNumber = currentNumber / newBase; } newNumber = trimNumber(newNumber); // return calculateNewBase(oldBase, 2, newBase, ten); return newNumber; } // Multiplies two base n numbers together vector <int> multiply(int base, vector<int> firstNumber, vector<int> secondNumber) { int resultLength = firstNumber.size() + secondNumber.size(); vector<int> resultNumber(resultLength, 0); for (int i = firstNumber.size() - 1 ; i >= 0; i--) { for (int j = secondNumber.size() - 1; j >= 0; j--) { resultNumber[i+j + 1] += firstNumber[i] * secondNumber[j]; } } for (int i = resultNumber.size() -1; i > 0; i--) { if (resultNumber[i] >= base) { resultNumber[i-1] += resultNumber[i]/base; resultNumber[i] = resultNumber[i] % base; } } return trimNumber(resultNumber); } vector<int> calculateNewBase(int oldBase, int newBase, vector<int> oldNumber) { int newNumberLength = calculateNewBaseLength(oldBase, oldNumber.size(), newBase); vector<int> newNumber(newNumberLength, 0); vector<int> conversionFactor(1, 1); // a single digit of 1 for (int i = oldNumber.size()-1; i >= 0; i--) { vector<int> difference(conversionFactor); // size the vector for (unsigned int j = 0; j < difference.size(); j++) { difference[j] *= oldNumber[i]; } // add the vector for (unsigned int j = 0; j < difference.size(); j++) { int newNumberIndex = j + newNumberLength - difference.size(); newNumber[newNumberIndex] += difference[j]; } // increment the conversion factor by oldbase 10 conversionFactor = multiply(newBase, conversionFactor, tenInOldBase(oldBase,newBase)); } // Flatten number to base for (int i = newNumber.size()-1; i >=0; i--) { if (newNumber[i] >= newBase) { newNumber[i-1] += newNumber[i]/newBase; newNumber[i] = newNumber[i]%newBase; } } return trimNumber(newNumber); } ////////////////////////////////////////////////////////////////////////////// /////////////////////////////// READ SETTINGS //////////////////////////////// ////////////////////////////////////////////////////////////////////////////// struct settingWrapper { string domain; string allowedCharacters; uint maxCharacters; string regex; }; settingWrapper getSettings(string domain) { string hexCharacters = "0123456789abcdef"; settingWrapper settings; // open ~/.passcodes/config ifstream configFile; struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; string configPath = string(homedir) + "/.passcodes/"; string subscriptionPath = string(homedir) + "/.passcodes/subscriptions"; configFile.open(subscriptionPath.c_str()); if (!configFile.is_open()) { cout << "File does not exist" << endl; #if defined(_WIN32) _mkdir(strPath.c_str()); #else mkdir(configPath.c_str(), 0777); // notice that 777 is different than 0777 #endif ofstream testFile; testFile.open(subscriptionPath.c_str()); testFile << "http://passcod.es/global.chanel" << endl; testFile << "http://asherglick.github.io/Passcodes" << endl; testFile.close(); configFile.open(subscriptionPath.c_str()); } cout << "opening file" << endl; //configFile.open(subscriptionPath.c_str()); string subscription = ""; if (configFile.is_open()) { cout << "File is open" << endl; while (getline(configFile, subscription)) { unsigned char hash[20]; SHA1((unsigned char*)subscription.c_str(), subscription.size(), hash); string cashedSubscriptionName = ""; for (int i = 0; i < 4; i++) { cashedSubscriptionName += hexCharacters[hash[i]&0x0F]; cashedSubscriptionName += hexCharacters[(hash[i]>>4)&0x0F]; } ifstream subscription; string subscriptionPath = configPath + "cashe/" + cashedSubscriptionName + "/" + domain; subscription.open(subscriptionPath); string maxLength cout << subscriptionPath << endl; } } // look for 'subscriptions' section // open each file in the subscriptions list in order // ~/.passcodes/<subscription>/<domain> // add any non-blank entry to the settings, latter entries overriding former return settings; } ////////////////////////////////////////////////////////////////////////////// //////////////////////// GENERATE PASSWORD FUNCTIONS ///////////////////////// ////////////////////////////////////////////////////////////////////////////// #define ITERATIONCOUNT 100000 /****************************** GENERATE PASSWORD *****************************\ | The generate password function takes in the domain and the master password | | then returns the 16 character long base64 password based off of the sha256 | | hash | \******************************************************************************/ string generatePassword(string domain, string masterpass ) { settingWrapper settings = getSettings(domain); string prehash = domain+masterpass; unsigned char hash[HASHSIZE]; string output = ""; for (int i = 0; i < ITERATIONCOUNT; i++) { SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash); prehash = ""; for (int j = 0; j < HASHSIZE; j++) { prehash += hash[j]; } } vector<int> hashedValues(32); for (int j = 0; j < HASHSIZE; j++) { hashedValues[j] = static_cast<int>(hash[j]); } vector<int> newValues = calculateNewBase(256, 64, hashedValues); for (int val : newValues) { cout << val << ", "; } return "Failed"; } /************************************ HELP ************************************\ | The help fucntion displays the help text to the user, it is called if the | | help flag is present or if the user has used the program incorrectly | \******************************************************************************/ void help() { cout << "Welcome to the command line application for passcod.es\n" "written by Asher Glick (aglick@aglick.com)\n" "\n" "Usage\n" " passcodes [-s] [-h] [-d] <domain text> [-p] <password text>\n" "\n" "Commands\n" " -d Any text that comes after this flag is set as the domain\n" " If no domain is given it is prompted for\n" " -p Any text that comes after this flag is set as the password\n" " If this flag is set a warning will be displayed\n" " If this flag is not set the user is prompted for a password\n" " -h Display the help menu\n" " No other functions will be run if this flag is present\n" " -s Suppress warnings\n" " No warning messages will appear from using the -p flag\n" << endl; } /************************************ MAIN ************************************\ | The main function handles all of the arguments, parsing them into the | | correct locations. Then prompts the user to enter the domain and password | | if they have not been specified in the arguments. Finaly it outputs the | | generated password to the user | \******************************************************************************/ int main(int argc, char* argv[]) { bool silent = false; string domain = ""; string password = ""; string *pointer = NULL; // Parse the arguments for (int i = 1; i < argc; i++) { if (string(argv[i]) == "-p") { // password flag pointer = &password; } else if (string(argv[i]) == "-d") { // domain flag pointer = &domain; } else if (string(argv[i]) == "-s") { // silent flag silent = true; } else if (string(argv[i]) == "-h") { // help flag help(); return 0; } else { if (pointer == NULL) { help(); return 0; } else { *pointer += argv[i]; } } } // If there is no domain given, prompt the user for a domain if (domain == "") { cout << "Enter Domain: "; getline(cin, domain); } // If there is a password given and the silent flag is not present // give the user a warning telling them that the password flag is insecure if (password != "" && !silent) { cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl; } // If there is not a password given, prompt the user for a password securly else if (password == "") { password = string(getpass("Enter Password: ")); } // Output the generated Password to the user cout << generatePassword(domain, password) << endl; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2017 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * ****************************************************************************/ #ifndef DTK_FINE_SEARCH_DEF_HPP #define DTK_FINE_SEARCH_DEF_HPP #include <DTK_DBC.hpp> #include <DTK_FineSearchFunctor.hpp> #include <Kokkos_Core.hpp> namespace DataTransferKit { template <typename DeviceType> void FineSearch<DeviceType>::search( Kokkos::View<Coordinate **, DeviceType> reference_points, Kokkos::View<bool *, DeviceType> point_in_cell, Kokkos::View<Coordinate **, DeviceType> physical_points, Kokkos::View<Coordinate ***, DeviceType> cells, Kokkos::View<unsigned int *, DeviceType> coarse_search_output_points, Kokkos::View<unsigned int *, DeviceType> coarse_search_output_cells, shards::CellTopology cell_topo ) { // Check the size of the Views DTK_REQUIRE( reference_points.extent( 0 ) == point_in_cell.extent( 0 ) ); DTK_REQUIRE( reference_points.extent( 1 ) == physical_points.extent( 1 ) ); DTK_REQUIRE( reference_points.extent( 1 ) == cells.extent( 2 ) ); DTK_REQUIRE( coarse_search_output_cells.extent( 0 ) == coarse_search_output_points.extent( 0 ) ); using ExecutionSpace = typename DeviceType::execution_space; int const n_ref_pts = reference_points.extent( 0 ); shards::Hexahedron<8> constexpr hex_8; shards::Hexahedron<27> constexpr hex_27; shards::Pyramid<5> constexpr pyr_5; shards::Quadrilateral<4> constexpr quad_4; shards::Quadrilateral<9> constexpr quad_9; shards::Tetrahedron<4> constexpr tet_4; shards::Tetrahedron<10> constexpr tet_10; shards::Triangle<3> constexpr tri_3; shards::Triangle<6> constexpr tri_6; shards::Wedge<6> constexpr wedge_6; shards::Wedge<18> constexpr wedge_18; // Perform the fine search. We hide the template parameters used by // Intrepid2, using the CellType template. switch ( cell_topo.getKey() ) { case hex_8.key: { Functor::FineSearch<CellType::Hexahedron_8, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_hex_8" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); break; } case hex_27.key: { Functor::FineSearch<CellType::Hexahedron_27, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_hex_27" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); break; } case pyr_5.key: { Functor::FineSearch<CellType::Pyramid_5, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_pyr_5" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); break; } case quad_4.key: { Functor::FineSearch<CellType::Quadrilateral_4, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_quad_4" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); break; } case quad_9.key: { Functor::FineSearch<CellType::Quadrilateral_9, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_quad_9" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); break; } case tet_4.key: { Functor::FineSearch<CellType::Tetrahedron_4, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tet_4" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); break; } case tet_10.key: { Functor::FineSearch<CellType::Tetrahedron_10, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tet_10" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); break; } case tri_3.key: { Functor::FineSearch<CellType::Triangle_3, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tri_3" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); break; } case tri_6.key: { Functor::FineSearch<CellType::Triangle_6, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tri_6" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); break; } case wedge_6.key: { Functor::FineSearch<CellType::Wedge_6, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_wedge_6" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); break; } case wedge_18.key: { Functor::FineSearch<CellType::Wedge_18, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_wedge_18" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); break; } default: { throw std::runtime_error( "Not implemented" ); } } Kokkos::fence(); // Get ride of bogus warning about variables not being used with gcc 7.1 std::ignore = hex_8; std::ignore = hex_27; std::ignore = pyr_5; std::ignore = quad_4; std::ignore = quad_9; std::ignore = tet_4; std::ignore = tet_10; std::ignore = tri_3; std::ignore = tri_6; std::ignore = wedge_6; std::ignore = wedge_18; } } // Explicit instantiation macro #define DTK_FINESEARCH_INSTANT( NODE ) \ template class FineSearch<typename NODE::device_type>; #endif <commit_msg>Replace switch with if else to make pgi happy.<commit_after>/**************************************************************************** * Copyright (c) 2012-2017 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * ****************************************************************************/ #ifndef DTK_FINE_SEARCH_DEF_HPP #define DTK_FINE_SEARCH_DEF_HPP #include <DTK_DBC.hpp> #include <DTK_FineSearchFunctor.hpp> #include <Kokkos_Core.hpp> namespace DataTransferKit { template <typename DeviceType> void FineSearch<DeviceType>::search( Kokkos::View<Coordinate **, DeviceType> reference_points, Kokkos::View<bool *, DeviceType> point_in_cell, Kokkos::View<Coordinate **, DeviceType> physical_points, Kokkos::View<Coordinate ***, DeviceType> cells, Kokkos::View<unsigned int *, DeviceType> coarse_search_output_points, Kokkos::View<unsigned int *, DeviceType> coarse_search_output_cells, shards::CellTopology cell_topo ) { // Check the size of the Views DTK_REQUIRE( reference_points.extent( 0 ) == point_in_cell.extent( 0 ) ); DTK_REQUIRE( reference_points.extent( 1 ) == physical_points.extent( 1 ) ); DTK_REQUIRE( reference_points.extent( 1 ) == cells.extent( 2 ) ); DTK_REQUIRE( coarse_search_output_cells.extent( 0 ) == coarse_search_output_points.extent( 0 ) ); using ExecutionSpace = typename DeviceType::execution_space; int const n_ref_pts = reference_points.extent( 0 ); // Perform the fine search. We hide the template parameters used by // Intrepid2, using the CellType template. unsigned int const cell_topo_key = cell_topo.getKey(); if ( cell_topo_key == shards::getCellTopologyData<shards::Hexahedron<8>>()->key ) { Functor::FineSearch<CellType::Hexahedron_8, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_hex_8" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Hexahedron<27>>()->key ) { Functor::FineSearch<CellType::Hexahedron_27, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_hex_27" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Pyramid<5>>()->key ) { Functor::FineSearch<CellType::Pyramid_5, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_pyr_5" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Quadrilateral<4>>()->key ) { Functor::FineSearch<CellType::Quadrilateral_4, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_quad_4" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Quadrilateral<8>>()->key ) { Functor::FineSearch<CellType::Quadrilateral_9, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_quad_9" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Tetrahedron<4>>()->key ) { Functor::FineSearch<CellType::Tetrahedron_4, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tet_4" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Tetrahedron<10>>()->key ) { Functor::FineSearch<CellType::Tetrahedron_10, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tet_10" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Triangle<3>>()->key ) { Functor::FineSearch<CellType::Triangle_3, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tri_3" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Triangle<6>>()->key ) { Functor::FineSearch<CellType::Triangle_6, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_tri_6" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Wedge<6>>()->key ) { Functor::FineSearch<CellType::Wedge_6, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_wedge_6" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else if ( cell_topo_key == shards::getCellTopologyData<shards::Wedge<18>>()->key ) { Functor::FineSearch<CellType::Wedge_18, DeviceType> search_functor( reference_points, point_in_cell, physical_points, cells, coarse_search_output_points, coarse_search_output_cells ); Kokkos::parallel_for( REGION_NAME( "compute_pos_in_ref_space_wedge_18" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_ref_pts ), search_functor ); } else { throw std::runtime_error( "Not implemented" ); } Kokkos::fence(); } } // Explicit instantiation macro #define DTK_FINESEARCH_INSTANT( NODE ) \ template class FineSearch<typename NODE::device_type>; #endif <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <string> #include <vector> #include <bitset> /* class Crypto { protected: int value; std::string ClearText; std::string CypherText; const std::string Pad = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const std::string HexPad = "0123456789ABCDEF"; std::vector<bool> Bin; std::string EncodedB64; std::bitset<6> b; public: Crypto() :value(0) {}; Crypto(const std::string s) :ClearText(s) {this -> Bin.resize(ClearText.length() * 8, 0);} ~Crypto(){}; // Print the clear text on screen void GetClearText() { std::cout << ClearText << std::endl; } // Returns an array with the indexes of the pad void Str2Bin() { unsigned int c = 0; unsigned int n; std::vector<bool>::reverse_iterator v = Bin.rbegin(); for (std::string::reverse_iterator it = ClearText.rbegin(); it < ClearText.rend(); ++it) { n = *it; while (n != 0) { *v++ = (n % 2 == 0 ? 0 : 1); n /= 2; c++; } v += 8 - c; c = 0; } for (bool i : Bin) std::cout << i; } // Convert from binary to base64 void Bin2Base64() { int c = 5; unsigned long int t; for (bool v : Bin) { while (c--) { b.set(c, v); if (c == 0){ t = b.to_ulong(); EncodedB64 += Pad[t]; c = 5; b.reset(); } } std::cout << EncodedB64 << std::endl; } } };*/ namespace Crypto{ // Declaration of the Base64 and alphabet const std::string B64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const std::string HexPad = "0123456789ABCDEF"; // Convert string into binary boolean vector std::vector<bool> Str2Bin(std::string s){ std::vector<bool> Bin (s.length() * 8, 0); std::vector<bool>::reverse_iterator v = Bin.rbegin(); unsigned int c = 0; unsigned int n; for (std::string::const_reverse_iterator it = s.crbegin(); it < s.crend(); ++it) { n = *it; while (n != 0) { *v++ = (n % 2 == 0 ? 0 : 1); n /= 2; c++; } v += 8 - c; c = 0; } return Bin; } // Hex representation of a string std::string Str2Hex(std::string s){ std::stringstream HexStream; for (std::string::const_iterator it = s.cbegin(); it < s.cend(); ++it){ HexStream << std::hex << (int)*it; } std::string Hex = HexStream.str(); return Hex; } // Base64 Encoding std::string Str2B64(std::string s){ std::string B64; std::vector<bool> Bin = Str2Bin(s); std::string padding(s.length() % 3, "="); } } int main() { std::string s = "CI"; std::vector<bool> Bin = Crypto::Str2Bin(s); for (bool i: Bin) std::cout << i; std::cout << std::endl; std::string Hex = Crypto::Str2Hex(s); std::cout << Hex; return 0; } <commit_msg>B64 Finalised<commit_after>#include <iostream> #include <iomanip> #include <string> #include <vector> #include <bitset> namespace Crypto{ // Declaration of the Base64 and alphabet const std::string B64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const std::string HexPad = "0123456789ABCDEF"; // Convert string into binary boolean vector std::vector<bool> Str2Bin(std::string s){ std::vector<bool> Bin (s.length() * 8, 0); std::vector<bool>::reverse_iterator v = Bin.rbegin(); unsigned int c = 0; unsigned int n; for (std::string::const_reverse_iterator it = s.crbegin(); it < s.crend(); ++it) { n = *it; while (n != 0) { *v++ = (n % 2 == 0 ? 0 : 1); n /= 2; c++; } v += 8 - c; c = 0; } return Bin; } // Hex representation of a string std::string Str2Hex(std::string s){ std::stringstream HexStream; for (std::string::const_iterator it = s.cbegin(); it < s.cend(); ++it){ HexStream << std::hex << (int)*it; } std::string Hex = HexStream.str(); return Hex; } // String to Base64 std::string Str2B64(std::string s){ std::string B64; std::bitset<6> b; std::vector<bool> Bin = Str2Bin(s); // Compose padding string and append 0 bits to the Bin vector unsigned short k = 3 - s.length() % 3; std::string padding (k, '='); for (int i = 0; i < 2 * k; i++) Bin.push_back(0); //read six bits at a time and encode them for (int j = 0; j < Bin.size() / 6; j++){ b.set(5, Bin[j * 6]); b.set(4, Bin[j * 6 + 1]); b.set(3, Bin[j * 6 + 2]); b.set(2, Bin[j * 6 + 3]); b.set(1, Bin[j * 6 + 4]); b.set(0, Bin[j * 6 + 5]); unsigned long l = b.to_ulong(); B64 += B64Alphabet[l]; } B64 += padding; return B64; } } int main() { std::string s; std::cout << "Provide a string:" << std::endl; std::cin >> s; /*std::vector<bool> Bin = Crypto::Str2Bin(s); for (bool i: Bin) std::cout << i; std::cout << std::endl; std::string Hex = Crypto::Str2Hex(s); std::cout << Hex << std::endl;*/ std::string B64 = Crypto::Str2B64(s); std::cout << B64 << std::endl; return 0; } <|endoftext|>
<commit_before>#ifndef AL_FREENECT_HPP #define AL_FREENECT_HPP /* Allocore -- Multimedia / virtual environment application class library Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB. Copyright (C) 2012. The Regents of the University of California. 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 University of California 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 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 description: Binding to freenect library. File author(s): Graham Wakefield, 2012, grrrwaaa@gmail.com */ #include "allocore/al_Allocore.hpp" #include "alloutil/al_FPS.hpp" #include "libfreenect.h" #include <map> namespace al { // run libfreenect on a backtround thread to reduce CPU load: class Freenect : public Thread, public ThreadFunction { public: static void depth_cb(freenect_device *dev, void *depth, uint32_t timestamp); static void video_cb(freenect_device *dev, void *video, uint32_t timestamp); static bool check(const char * what, int code); class Callback { public: Callback(int idx=0); virtual ~Callback(); // Warning: these will be called from a background thread: virtual void onVideo(Texture& raw, uint32_t timestamp) {} virtual void onDepth(Texture& raw, uint32_t timestamp) {} static Vec3f depthToEye(int x, int y, uint16_t d); static double rawDepthToMeters(uint16_t raw); void reconfigure(); bool startVideo(); bool stopVideo(); bool startDepth(); bool stopDepth(); // returns tilt in radians double tilt(); void tilt(double radians); Texture depth, video; protected: freenect_device * dev; }; // ThreadFunction: virtual void operator()(); static Freenect& get(); static void stop(); virtual ~Freenect(); private: Freenect(); Freenect * singleton; freenect_context * ctx; bool active; }; inline bool Freenect::check(const char * what, int code) { if (code < 0) { AL_WARN("Error (%s): %d", what, code); return false; } return true; } inline Freenect::Callback::Callback(int idx) { dev = 0; Freenect& self = get(); if (check("open", freenect_open_device(self.ctx, &dev, idx))) { freenect_set_user(dev, this); reconfigure(); } } inline Freenect::Callback::~Callback() { if (dev) freenect_set_user(dev, 0); } inline double Freenect::Callback::rawDepthToMeters(uint16_t raw) { static const double k1 = 1.1863; static const double k2 = 1./2842.5; static const double k3 = 0.1236; return k3 * tan(raw*k2 + k1); } // @see http://nicolas.burrus.name/index.php/Research/KinectCalibration inline Vec3f Freenect::Callback::depthToEye(int x, int y, uint16_t d) { // size of a pixel in meters, at zero/near plane: static const double metersPerPixelX = 1./594.21434211923247; static const double metersPerPixelY = 1./591.04053696870778; // location of X,Y corner at zero plane, in pixels: static const double edgeX = 339.30780975300314; // x edge pixel static const double edgeY = 242.73913761751615; // y edge pixel const double meters = rawDepthToMeters(d); const double disparityX = (x - edgeX); // in pixels const double disparityY = (y - edgeY); // in pixels return Vec3f(meters * disparityX * metersPerPixelX, meters * disparityY * metersPerPixelY, meters ); } inline void Freenect::Callback::reconfigure() { AlloArrayHeader header; const freenect_frame_mode dmode = freenect_get_current_depth_mode(dev); header.type = AlloUInt16Ty; header.components = 1; header.dimcount = 2; header.dim[0] = dmode.width; header.dim[1] = dmode.height; header.stride[0] = (dmode.data_bits_per_pixel+dmode.padding_bits_per_pixel)/8; header.stride[1] = header.stride[0] * dmode.width; depth.configure(header); depth.array().dataCalloc(); const freenect_frame_mode vmode = freenect_get_current_video_mode(dev); header.type = AlloUInt8Ty; header.components = 3; header.dimcount = 2; header.dim[0] = vmode.width; header.dim[1] = vmode.height; header.stride[0] = (vmode.data_bits_per_pixel+vmode.padding_bits_per_pixel)/8; header.stride[1] = header.stride[0] * vmode.width; video.configure(header); video.array().dataCalloc(); } inline bool Freenect::Callback::startVideo() { if (dev) { freenect_set_video_callback(dev, video_cb); return check("start_video", freenect_start_video(dev)); } return false; } inline bool Freenect::Callback::stopVideo() { if (dev) { return check("stop_video", freenect_stop_video(dev)); } return false; } inline bool Freenect::Callback::startDepth() { if (dev) { freenect_set_depth_callback(dev, depth_cb); return check("start_depth", freenect_start_depth(dev)); } return false; } inline bool Freenect::Callback::stopDepth() { if (dev) { return check("stop_depth", freenect_stop_depth(dev)); } return false; } // returns tilt in radians inline double Freenect::Callback::tilt() { double t = 0; if (dev) { freenect_update_tilt_state(dev); freenect_raw_tilt_state * state = freenect_get_tilt_state(dev); if (state) { t = freenect_get_tilt_degs(state); } else { AL_WARN("Error: no state"); } } return t * M_DEG2RAD; } inline void Freenect::Callback::tilt(double radians) { freenect_set_tilt_degs(dev, radians * M_RAD2DEG); } // ThreadFunction: inline void Freenect::operator()() { // listen for messages on main thread: while (active) { //printf("."); // blocking call: freenect_process_events(ctx); } } static Freenect& get(); inline void Freenect::stop() { Freenect& self = get(); self.active = 0; self.Thread::join(); } inline Freenect::~Freenect() { active = false; Thread::join(); freenect_shutdown(ctx); } inline Freenect::Freenect() : Thread() { // TODO: handle multiple contexts? freenect_usb_context * usb_ctx = NULL; int res = freenect_init(&ctx, usb_ctx); if (res < 0) { AL_WARN("Error: failed to initialize libfreenect"); exit(0); } int numdevs = freenect_num_devices(ctx); printf("%d devices\n", numdevs); active = true; Thread::start(*this); } } #endif <commit_msg>freenect include directive fixed<commit_after>#ifndef AL_FREENECT_HPP #define AL_FREENECT_HPP /* Allocore -- Multimedia / virtual environment application class library Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB. Copyright (C) 2012. The Regents of the University of California. 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 University of California 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 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 description: Binding to freenect library. File author(s): Graham Wakefield, 2012, grrrwaaa@gmail.com */ #include "allocore/al_Allocore.hpp" #include "alloutil/al_FPS.hpp" #include "libfreenect/libfreenect.h" #include <map> namespace al { // run libfreenect on a backtround thread to reduce CPU load: class Freenect : public Thread, public ThreadFunction { public: static void depth_cb(freenect_device *dev, void *depth, uint32_t timestamp); static void video_cb(freenect_device *dev, void *video, uint32_t timestamp); static bool check(const char * what, int code); class Callback { public: Callback(int idx=0); virtual ~Callback(); // Warning: these will be called from a background thread: virtual void onVideo(Texture& raw, uint32_t timestamp) {} virtual void onDepth(Texture& raw, uint32_t timestamp) {} static Vec3f depthToEye(int x, int y, uint16_t d); static double rawDepthToMeters(uint16_t raw); void reconfigure(); bool startVideo(); bool stopVideo(); bool startDepth(); bool stopDepth(); // returns tilt in radians double tilt(); void tilt(double radians); Texture depth, video; protected: freenect_device * dev; }; // ThreadFunction: virtual void operator()(); static Freenect& get(); static void stop(); virtual ~Freenect(); private: Freenect(); Freenect * singleton; freenect_context * ctx; bool active; }; inline bool Freenect::check(const char * what, int code) { if (code < 0) { AL_WARN("Error (%s): %d", what, code); return false; } return true; } inline Freenect::Callback::Callback(int idx) { dev = 0; Freenect& self = get(); if (check("open", freenect_open_device(self.ctx, &dev, idx))) { freenect_set_user(dev, this); reconfigure(); } } inline Freenect::Callback::~Callback() { if (dev) freenect_set_user(dev, 0); } inline double Freenect::Callback::rawDepthToMeters(uint16_t raw) { static const double k1 = 1.1863; static const double k2 = 1./2842.5; static const double k3 = 0.1236; return k3 * tan(raw*k2 + k1); } // @see http://nicolas.burrus.name/index.php/Research/KinectCalibration inline Vec3f Freenect::Callback::depthToEye(int x, int y, uint16_t d) { // size of a pixel in meters, at zero/near plane: static const double metersPerPixelX = 1./594.21434211923247; static const double metersPerPixelY = 1./591.04053696870778; // location of X,Y corner at zero plane, in pixels: static const double edgeX = 339.30780975300314; // x edge pixel static const double edgeY = 242.73913761751615; // y edge pixel const double meters = rawDepthToMeters(d); const double disparityX = (x - edgeX); // in pixels const double disparityY = (y - edgeY); // in pixels return Vec3f(meters * disparityX * metersPerPixelX, meters * disparityY * metersPerPixelY, meters ); } inline void Freenect::Callback::reconfigure() { AlloArrayHeader header; const freenect_frame_mode dmode = freenect_get_current_depth_mode(dev); header.type = AlloUInt16Ty; header.components = 1; header.dimcount = 2; header.dim[0] = dmode.width; header.dim[1] = dmode.height; header.stride[0] = (dmode.data_bits_per_pixel+dmode.padding_bits_per_pixel)/8; header.stride[1] = header.stride[0] * dmode.width; depth.configure(header); depth.array().dataCalloc(); const freenect_frame_mode vmode = freenect_get_current_video_mode(dev); header.type = AlloUInt8Ty; header.components = 3; header.dimcount = 2; header.dim[0] = vmode.width; header.dim[1] = vmode.height; header.stride[0] = (vmode.data_bits_per_pixel+vmode.padding_bits_per_pixel)/8; header.stride[1] = header.stride[0] * vmode.width; video.configure(header); video.array().dataCalloc(); } inline bool Freenect::Callback::startVideo() { if (dev) { freenect_set_video_callback(dev, video_cb); return check("start_video", freenect_start_video(dev)); } return false; } inline bool Freenect::Callback::stopVideo() { if (dev) { return check("stop_video", freenect_stop_video(dev)); } return false; } inline bool Freenect::Callback::startDepth() { if (dev) { freenect_set_depth_callback(dev, depth_cb); return check("start_depth", freenect_start_depth(dev)); } return false; } inline bool Freenect::Callback::stopDepth() { if (dev) { return check("stop_depth", freenect_stop_depth(dev)); } return false; } // returns tilt in radians inline double Freenect::Callback::tilt() { double t = 0; if (dev) { freenect_update_tilt_state(dev); freenect_raw_tilt_state * state = freenect_get_tilt_state(dev); if (state) { t = freenect_get_tilt_degs(state); } else { AL_WARN("Error: no state"); } } return t * M_DEG2RAD; } inline void Freenect::Callback::tilt(double radians) { freenect_set_tilt_degs(dev, radians * M_RAD2DEG); } // ThreadFunction: inline void Freenect::operator()() { // listen for messages on main thread: while (active) { //printf("."); // blocking call: freenect_process_events(ctx); } } static Freenect& get(); inline void Freenect::stop() { Freenect& self = get(); self.active = 0; self.Thread::join(); } inline Freenect::~Freenect() { active = false; Thread::join(); freenect_shutdown(ctx); } inline Freenect::Freenect() : Thread() { // TODO: handle multiple contexts? freenect_usb_context * usb_ctx = NULL; int res = freenect_init(&ctx, usb_ctx); if (res < 0) { AL_WARN("Error: failed to initialize libfreenect"); exit(0); } int numdevs = freenect_num_devices(ctx); printf("%d devices\n", numdevs); active = true; Thread::start(*this); } } #endif <|endoftext|>
<commit_before>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #define DUNE_STUFF_FUNCTIONS_DISABLE_CHECKS 1 #define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING 1 // This one has to come first (includes the config.h)! #include <dune/stuff/test/test_common.hh> #include <sstream> #if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H # define ENABLE_ALUGRID 1 # include <dune/grid/alugrid.hh> #else # error This test requires ALUGrid! #endif #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/print.hh> #include <dune/stuff/common/float_cmp.hh> #include <dune/hdd/playground/linearelliptic/testcases/OS2014.hh> #include "linearelliptic-swipdg.hh" #include "linearelliptic-block-swipdg.hh" // change this to toggle output std::ostream& test_out = std::cout; //std::ostream& test_out = DSC_LOG.devnull(); using namespace Dune; using namespace HDD; class OS2014_nonparametric_convergence_study : public ::testing::Test { static std::vector< double > truncate_vector_(const std::vector< double >& in, const size_t size) { assert(size <= in.size()); if (size == in.size()) return in; else { std::vector< double > ret(size); for (size_t ii = 0; ii < size; ++ii) ret[ii] = in[ii]; return ret; } } // ... truncate_vector(...) template< class StudyType > static bool check_for_success_(const StudyType& study, std::map< std::string, std::vector< double > >& errors) { size_t failures = 0; std::stringstream ss; ss << "\n"; for (const auto& norm : study.provided_norms()) if (!Dune::Stuff::Common::FloatCmp::lt(errors[norm], truncate_vector_(study.expected_results(norm), errors[norm].size()))) { ++failures; Dune::Stuff::Common::print(errors[norm], "errors (" + norm + ")", ss); Dune::Stuff::Common::print(study.expected_results(norm), "expected results (" + norm + ")", ss); } if (failures) DUNE_THROW(errors_are_not_as_expected, ss.str()); return true; } // ... check_for_success_(...) static const GDT::ChooseSpaceBackend space_backend = GDT::ChooseSpaceBackend::fem; static const Stuff::LA::ChooseBackend la_backend = Stuff::LA::ChooseBackend::eigen_sparse; typedef ALUGrid< 2, 2, simplex, conforming > GridType; typedef LinearElliptic::TestCases::OS2014< GridType > TestCaseType; // typedef LinearElliptic::TestCases::ESV2007Multiscale< GridType > BlockTestCaseType; typedef LinearElliptic::Tests::EocStudySWIPDG< TestCaseType, 1, space_backend, la_backend > EocStudyType; // typedef LinearElliptic::Tests::EocStudyBlockSWIPDG< BlockTestCaseType, 1, la_backend > BlockEocStudyType; protected: bool SWIPDG_fine_triangulation() const { const TestCaseType test_case; test_case.print_header(test_out); test_out << std::endl; EocStudyType eoc_study(test_case); auto errors = eoc_study.run(false, test_out); return check_for_success_(eoc_study, errors); } // ... SWIPDG_fine_triangulation(...) // bool BlockSWIPDG_coarse_triangulation(const std::string partitioning) const // { // const BlockTestCaseType test_case(partitioning); // BlockEocStudyType eoc_study(test_case); // auto errors = eoc_study.run(false, test_out); // return check_for_success_(eoc_study, errors); // } // ... BlockSWIPDG_coarse_triangulation(...) }; // class OS2014_nonparametric_convergence_study TEST_F(OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation) { EXPECT_TRUE(SWIPDG_fine_triangulation()); } #include <dune/stuff/test/test_main.cxx> <commit_msg>[test.OS2014] use gtests expectation macros<commit_after>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #define DUNE_STUFF_FUNCTIONS_DISABLE_CHECKS 1 #define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING 1 // This one has to come first (includes the config.h)! #include <dune/stuff/test/test_common.hh> #include <sstream> #if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H # define ENABLE_ALUGRID 1 # include <dune/grid/alugrid.hh> #else # error This test requires ALUGrid! #endif #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/print.hh> #include <dune/stuff/common/float_cmp.hh> #include <dune/hdd/playground/linearelliptic/testcases/OS2014.hh> #include "linearelliptic-swipdg.hh" #include "linearelliptic-block-swipdg.hh" // change this to toggle output std::ostream& test_out = std::cout; //std::ostream& test_out = DSC_LOG.devnull(); using namespace Dune; using namespace HDD; class OS2014_nonparametric_convergence_study : public ::testing::Test { template< class StudyType > static void check_for_success(const StudyType& study, std::map< std::string, std::vector< double > >& errors_map) { for (const auto& norm : study.provided_norms()) { const auto errors = errors_map[norm]; const auto expected_results = study.expected_results(norm); assert(expected_results.size() <= errors.size()); for (size_t ii = 0; ii < errors.size(); ++ii) EXPECT_LE(errors[ii], expected_results[ii]) << " 'norm' = " << norm << ", level = " << ii; } } // ... check_for_success(...) static const GDT::ChooseSpaceBackend space_backend = GDT::ChooseSpaceBackend::fem; static const Stuff::LA::ChooseBackend la_backend = Stuff::LA::ChooseBackend::eigen_sparse; typedef ALUGrid< 2, 2, simplex, conforming > GridType; typedef LinearElliptic::TestCases::OS2014< GridType > TestCaseType; // typedef LinearElliptic::TestCases::ESV2007Multiscale< GridType > BlockTestCaseType; typedef LinearElliptic::Tests::EocStudySWIPDG< TestCaseType, 1, space_backend, la_backend > EocStudyType; // typedef LinearElliptic::Tests::EocStudyBlockSWIPDG< BlockTestCaseType, 1, la_backend > BlockEocStudyType; protected: void SWIPDG_fine_triangulation() const { const TestCaseType test_case; test_case.print_header(test_out); test_out << std::endl; EocStudyType eoc_study(test_case); auto errors = eoc_study.run(false, test_out); check_for_success(eoc_study, errors); } // ... SWIPDG_fine_triangulation(...) // bool BlockSWIPDG_coarse_triangulation(const std::string partitioning) const // { // const BlockTestCaseType test_case(partitioning); // BlockEocStudyType eoc_study(test_case); // auto errors = eoc_study.run(false, test_out); // return check_for_success(eoc_study, errors); // } // ... BlockSWIPDG_coarse_triangulation(...) }; // class OS2014_nonparametric_convergence_study TEST_F(OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation) { SWIPDG_fine_triangulation(); } #include <dune/stuff/test/test_main.cxx> <|endoftext|>
<commit_before>// Copyright 2016 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "runtime/runtime-filter.h" #include <gutil/strings/substitute.h> #include "common/names.h" #include "runtime/client-cache.h" #include "runtime/exec-env.h" #include "service/impala-server.h" #include "util/bloom-filter.h" using namespace impala; using namespace boost; using namespace strings; // 20 is BloomFilter::MinLogSpace(1ull << 20, 0.1) DEFINE_int32(bloom_filter_size, 1024 * 1024, "(Advanced) Sets the size in bytes of Bloom " "Filters used for runtime filters in bytes. Actual size of filter will be " "rounded up to the nearest power of two, and may not exceed 16MB"); DEFINE_double(max_filter_error_rate, 0.75, "(Advanced) The maximum probability of false " "positives in a runtime filter before it is disabled."); const int RuntimeFilter::SLEEP_PERIOD_MS = 20; RuntimeFilterBank::RuntimeFilterBank(const TQueryCtx& query_ctx, RuntimeState* state) : query_ctx_(query_ctx), state_(state), closed_(false) { memory_allocated_ = ADD_COUNTER(state->runtime_profile(), "BloomFilterBytes", TUnit::BYTES); // Determine the right size - query opt takes precedence over flag. int32_t query_opt_size = query_ctx_.request.query_options.runtime_bloom_filter_size; static const int MAX_SIZE = 16 * 1024 * 1024; // 16MB static const int MIN_SIZE = 4 * 1024; // 4K uint64_t size = (query_opt_size >= MIN_SIZE && query_opt_size <= MAX_SIZE) ? query_opt_size : FLAGS_bloom_filter_size; log_filter_size_ = BitUtil::Log2(size); } RuntimeFilter* RuntimeFilterBank::RegisterFilter(const TRuntimeFilterDesc& filter_desc, bool is_producer) { RuntimeFilter* ret = obj_pool_.Add(new RuntimeFilter(filter_desc)); lock_guard<SpinLock> l(runtime_filter_lock_); if (is_producer) { DCHECK(produced_filters_.find(filter_desc.filter_id) == produced_filters_.end()); produced_filters_[filter_desc.filter_id] = ret; } else { DCHECK(consumed_filters_.find(filter_desc.filter_id) == consumed_filters_.end()); consumed_filters_[filter_desc.filter_id] = ret; } return ret; } namespace { /// Sends a filter to the coordinator. Executed asynchronously in the context of /// ExecEnv::rpc_pool(). void SendFilterToCoordinator(TNetworkAddress address, TUpdateFilterParams params, ImpalaInternalServiceClientCache* client_cache) { Status status; ImpalaInternalServiceConnection coord(client_cache, address, &status); if (!status.ok()) { // Failing to send a filter is not a query-wide error - the remote fragment will // continue regardless. // TODO: Retry. LOG(INFO) << "Couldn't send filter to coordinator: " << status.msg().msg(); return; } TUpdateFilterResult res; status = coord.DoRpc(&ImpalaInternalServiceClient::UpdateFilter, params, &res); } } void RuntimeFilterBank::UpdateFilterFromLocal(uint32_t filter_id, BloomFilter* bloom_filter) { DCHECK_NE(state_->query_options().runtime_filter_mode, TRuntimeFilterMode::OFF) << "Should not be calling UpdateFilterFromLocal() if filtering is disabled"; TUpdateFilterParams params; bool is_broadcast = false; { lock_guard<SpinLock> l(runtime_filter_lock_); RuntimeFilterMap::iterator it = produced_filters_.find(filter_id); DCHECK(it != produced_filters_.end()) << "Tried to update unregistered filter: " << filter_id; it->second->SetBloomFilter(bloom_filter); is_broadcast = it->second->filter_desc().is_broadcast_join; } if (state_->query_options().runtime_filter_mode == TRuntimeFilterMode::GLOBAL) { bloom_filter->ToThrift(&params.bloom_filter); params.filter_id = filter_id; params.query_id = query_ctx_.query_id; ExecEnv::GetInstance()->rpc_pool()->Offer(bind<void>( SendFilterToCoordinator, query_ctx_.coord_address, params, ExecEnv::GetInstance()->impalad_client_cache())); } if (is_broadcast) { // Do a short circuit publication by pushing the same BloomFilter to the consumer // side. RuntimeFilter* filter; { lock_guard<SpinLock> l(runtime_filter_lock_); RuntimeFilterMap::iterator it = consumed_filters_.find(filter_id); if (it == consumed_filters_.end()) return; filter = it->second; // Check if the filter already showed up. if (filter->GetBloomFilter() != NULL) return; } // TODO: Avoid need for this copy. BloomFilter* copy = AllocateScratchBloomFilter(); copy->Or(*bloom_filter); filter->SetBloomFilter(copy); } } void RuntimeFilterBank::PublishGlobalFilter(uint32_t filter_id, const TBloomFilter& thrift_filter) { lock_guard<SpinLock> l(runtime_filter_lock_); if (closed_) return; RuntimeFilterMap::iterator it = consumed_filters_.find(filter_id); DCHECK(it != consumed_filters_.end()) << "Tried to publish unregistered filter: " << filter_id; if (it->second->filter_desc().is_broadcast_join && it->second->GetBloomFilter() != NULL) { // Already showed up from local filter. return; } if (!state_->query_mem_tracker()->TryConsume( BloomFilter::GetExpectedHeapSpaceUsed(thrift_filter.log_heap_space))) { // Silently fail to publish the filter if there's not enough memory for it. return; } BloomFilter* bloom_filter = obj_pool_.Add(new BloomFilter(thrift_filter, NULL, NULL)); memory_allocated_->Add(bloom_filter->GetHeapSpaceUsed()); it->second->SetBloomFilter(bloom_filter); state_->runtime_profile()->AddInfoString(Substitute("Filter $0 arrival", filter_id), PrettyPrinter::Print(it->second->arrival_delay(), TUnit::TIME_MS)); } BloomFilter* RuntimeFilterBank::AllocateScratchBloomFilter() { lock_guard<SpinLock> l(runtime_filter_lock_); if (closed_) return NULL; // Track required space uint32_t required_space = BloomFilter::GetExpectedHeapSpaceUsed(log_filter_size_); if (!state_->query_mem_tracker()->TryConsume(required_space)) return NULL; BloomFilter* bloom_filter = obj_pool_.Add(new BloomFilter(log_filter_size_, NULL, NULL)); DCHECK_EQ(required_space, bloom_filter->GetHeapSpaceUsed()); memory_allocated_->Add(bloom_filter->GetHeapSpaceUsed()); return bloom_filter; } bool RuntimeFilterBank::ShouldDisableFilter(uint64_t max_ndv) { double fpp = BloomFilter::FalsePositiveProb(max_ndv, log_filter_size_); return fpp > FLAGS_max_filter_error_rate; } void RuntimeFilterBank::Close() { lock_guard<SpinLock> l(runtime_filter_lock_); closed_ = true; BOOST_FOREACH(RuntimeFilterMap::value_type v, produced_filters_) { const BloomFilter* bloom_filter = v.second->GetBloomFilter(); if (bloom_filter != NULL) { state_->query_mem_tracker()->Release(bloom_filter->GetHeapSpaceUsed()); } } BOOST_FOREACH(RuntimeFilterMap::value_type v, consumed_filters_) { const BloomFilter* bloom_filter = v.second->GetBloomFilter(); if (bloom_filter != NULL) { state_->query_mem_tracker()->Release(bloom_filter->GetHeapSpaceUsed()); } } obj_pool_.Clear(); } bool RuntimeFilter::WaitForArrival(int32_t timeout_ms) const { if (GetBloomFilter() != NULL) return true; while ((MonotonicMillis() - registration_time_) < timeout_ms) { SleepForMs(SLEEP_PERIOD_MS); if (GetBloomFilter() != NULL) return true; } return false; } <commit_msg>IMPALA-3023: Check return from AllocateScratchBloomFilter()<commit_after>// Copyright 2016 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "runtime/runtime-filter.h" #include <gutil/strings/substitute.h> #include "common/names.h" #include "runtime/client-cache.h" #include "runtime/exec-env.h" #include "service/impala-server.h" #include "util/bloom-filter.h" using namespace impala; using namespace boost; using namespace strings; // 20 is BloomFilter::MinLogSpace(1ull << 20, 0.1) DEFINE_int32(bloom_filter_size, 1024 * 1024, "(Advanced) Sets the size in bytes of Bloom " "Filters used for runtime filters in bytes. Actual size of filter will be " "rounded up to the nearest power of two, and may not exceed 16MB"); DEFINE_double(max_filter_error_rate, 0.75, "(Advanced) The maximum probability of false " "positives in a runtime filter before it is disabled."); const int RuntimeFilter::SLEEP_PERIOD_MS = 20; RuntimeFilterBank::RuntimeFilterBank(const TQueryCtx& query_ctx, RuntimeState* state) : query_ctx_(query_ctx), state_(state), closed_(false) { memory_allocated_ = ADD_COUNTER(state->runtime_profile(), "BloomFilterBytes", TUnit::BYTES); // Determine the right size - query opt takes precedence over flag. int32_t query_opt_size = query_ctx_.request.query_options.runtime_bloom_filter_size; static const int MAX_SIZE = 16 * 1024 * 1024; // 16MB static const int MIN_SIZE = 4 * 1024; // 4K uint64_t size = (query_opt_size >= MIN_SIZE && query_opt_size <= MAX_SIZE) ? query_opt_size : FLAGS_bloom_filter_size; log_filter_size_ = BitUtil::Log2(size); } RuntimeFilter* RuntimeFilterBank::RegisterFilter(const TRuntimeFilterDesc& filter_desc, bool is_producer) { RuntimeFilter* ret = obj_pool_.Add(new RuntimeFilter(filter_desc)); lock_guard<SpinLock> l(runtime_filter_lock_); if (is_producer) { DCHECK(produced_filters_.find(filter_desc.filter_id) == produced_filters_.end()); produced_filters_[filter_desc.filter_id] = ret; } else { DCHECK(consumed_filters_.find(filter_desc.filter_id) == consumed_filters_.end()); consumed_filters_[filter_desc.filter_id] = ret; } return ret; } namespace { /// Sends a filter to the coordinator. Executed asynchronously in the context of /// ExecEnv::rpc_pool(). void SendFilterToCoordinator(TNetworkAddress address, TUpdateFilterParams params, ImpalaInternalServiceClientCache* client_cache) { Status status; ImpalaInternalServiceConnection coord(client_cache, address, &status); if (!status.ok()) { // Failing to send a filter is not a query-wide error - the remote fragment will // continue regardless. // TODO: Retry. LOG(INFO) << "Couldn't send filter to coordinator: " << status.msg().msg(); return; } TUpdateFilterResult res; status = coord.DoRpc(&ImpalaInternalServiceClient::UpdateFilter, params, &res); } } void RuntimeFilterBank::UpdateFilterFromLocal(uint32_t filter_id, BloomFilter* bloom_filter) { DCHECK_NE(state_->query_options().runtime_filter_mode, TRuntimeFilterMode::OFF) << "Should not be calling UpdateFilterFromLocal() if filtering is disabled"; TUpdateFilterParams params; bool is_broadcast = false; { lock_guard<SpinLock> l(runtime_filter_lock_); RuntimeFilterMap::iterator it = produced_filters_.find(filter_id); DCHECK(it != produced_filters_.end()) << "Tried to update unregistered filter: " << filter_id; it->second->SetBloomFilter(bloom_filter); is_broadcast = it->second->filter_desc().is_broadcast_join; } if (state_->query_options().runtime_filter_mode == TRuntimeFilterMode::GLOBAL) { bloom_filter->ToThrift(&params.bloom_filter); params.filter_id = filter_id; params.query_id = query_ctx_.query_id; ExecEnv::GetInstance()->rpc_pool()->Offer(bind<void>( SendFilterToCoordinator, query_ctx_.coord_address, params, ExecEnv::GetInstance()->impalad_client_cache())); } if (is_broadcast) { // Do a short circuit publication by pushing the same BloomFilter to the consumer // side. RuntimeFilter* filter; { lock_guard<SpinLock> l(runtime_filter_lock_); RuntimeFilterMap::iterator it = consumed_filters_.find(filter_id); if (it == consumed_filters_.end()) return; filter = it->second; // Check if the filter already showed up. if (filter->GetBloomFilter() != NULL) return; } // TODO: Avoid need for this copy. BloomFilter* copy = AllocateScratchBloomFilter(); if (copy == NULL) return; copy->Or(*bloom_filter); { // Take lock only to ensure no race with PublishGlobalFilter() - there's no need for // coordination with readers of the filter. lock_guard<SpinLock> l(runtime_filter_lock_); if (filter->GetBloomFilter() == NULL) { filter->SetBloomFilter(copy); state_->runtime_profile()->AddInfoString( Substitute("Filter $0 arrival", filter_id), PrettyPrinter::Print(filter->arrival_delay(), TUnit::TIME_MS)); } } } } void RuntimeFilterBank::PublishGlobalFilter(uint32_t filter_id, const TBloomFilter& thrift_filter) { lock_guard<SpinLock> l(runtime_filter_lock_); if (closed_) return; RuntimeFilterMap::iterator it = consumed_filters_.find(filter_id); DCHECK(it != consumed_filters_.end()) << "Tried to publish unregistered filter: " << filter_id; if (it->second->filter_desc().is_broadcast_join && it->second->GetBloomFilter() != NULL) { // Already showed up from local filter. return; } if (!state_->query_mem_tracker()->TryConsume( BloomFilter::GetExpectedHeapSpaceUsed(thrift_filter.log_heap_space))) { // Silently fail to publish the filter if there's not enough memory for it. return; } BloomFilter* bloom_filter = obj_pool_.Add(new BloomFilter(thrift_filter, NULL, NULL)); memory_allocated_->Add(bloom_filter->GetHeapSpaceUsed()); it->second->SetBloomFilter(bloom_filter); state_->runtime_profile()->AddInfoString(Substitute("Filter $0 arrival", filter_id), PrettyPrinter::Print(it->second->arrival_delay(), TUnit::TIME_MS)); } BloomFilter* RuntimeFilterBank::AllocateScratchBloomFilter() { lock_guard<SpinLock> l(runtime_filter_lock_); if (closed_) return NULL; // Track required space uint32_t required_space = BloomFilter::GetExpectedHeapSpaceUsed(log_filter_size_); if (!state_->query_mem_tracker()->TryConsume(required_space)) return NULL; BloomFilter* bloom_filter = obj_pool_.Add(new BloomFilter(log_filter_size_, NULL, NULL)); DCHECK_EQ(required_space, bloom_filter->GetHeapSpaceUsed()); memory_allocated_->Add(bloom_filter->GetHeapSpaceUsed()); return bloom_filter; } bool RuntimeFilterBank::ShouldDisableFilter(uint64_t max_ndv) { double fpp = BloomFilter::FalsePositiveProb(max_ndv, log_filter_size_); return fpp > FLAGS_max_filter_error_rate; } void RuntimeFilterBank::Close() { lock_guard<SpinLock> l(runtime_filter_lock_); closed_ = true; BOOST_FOREACH(RuntimeFilterMap::value_type v, produced_filters_) { const BloomFilter* bloom_filter = v.second->GetBloomFilter(); if (bloom_filter != NULL) { state_->query_mem_tracker()->Release(bloom_filter->GetHeapSpaceUsed()); } } BOOST_FOREACH(RuntimeFilterMap::value_type v, consumed_filters_) { const BloomFilter* bloom_filter = v.second->GetBloomFilter(); if (bloom_filter != NULL) { state_->query_mem_tracker()->Release(bloom_filter->GetHeapSpaceUsed()); } } obj_pool_.Clear(); } bool RuntimeFilter::WaitForArrival(int32_t timeout_ms) const { if (GetBloomFilter() != NULL) return true; while ((MonotonicMillis() - registration_time_) < timeout_ms) { SleepForMs(SLEEP_PERIOD_MS); if (GetBloomFilter() != NULL) return true; } return false; } <|endoftext|>
<commit_before>#ifndef FIXED_VECTOR_HPP #define FIXED_VECTOR_HPP #include<algorithm> #include<type_traits> #include<utility> namespace nContainer { template<class T,auto N> class Fixed_vector { public: using value_type=T; using size_type=std::remove_cv_t<decltype(N)>; using pointer=T*; using const_pointer=const T*; using reference=T&; using const_reference=const T&; using iterator=T*; using const_iterator=const T*; private: value_type data_[N]; pointer end_; public: constexpr Fixed_vector() noexcept(std::is_nothrow_default_constructible_v<T>) :end_(data_){} template<class InIter> constexpr Fixed_vector(InIter begin,InIter end) { end_=std::copy(begin,end,data_); } Fixed_vector(const Fixed_vector &rhs)=delete; constexpr reference back() noexcept { return *(end_-1); } constexpr const_reference back() const noexcept { return *(end_-1); } constexpr iterator begin() noexcept { return data_; } constexpr const_iterator begin() const noexcept { return data_; } constexpr size_type capacity() const noexcept { return N; } constexpr void clear() noexcept { end_=data_; } constexpr iterator end() noexcept { return end_; } constexpr const_iterator end() const noexcept { return end_; } constexpr bool empty() const noexcept { return data_==end_; } constexpr pointer data() noexcept { return data_; } constexpr const_pointer data() const noexcept { return data_; } constexpr reference front() noexcept { return data_[0]; } constexpr const_reference front() const noexcept { return data_[0]; } constexpr void pop_back() noexcept { --end_; } constexpr void push_back(const value_type &val) noexcept(std::is_nothrow_copy_assignable_v<value_type>) { *(end_++)=val; } constexpr void push_back(value_type &&val) noexcept(std::is_nothrow_move_assignable_v<value_type>) { *(end_++)=std::move(val); } constexpr void resize(const size_type new_size) noexcept { end_=data_+new_size; } constexpr size_type size() const noexcept { return end_-data_; } constexpr reference operator[](const size_type pos) { return data_[pos]; } constexpr const_reference operator[](const size_type pos) const { return data_[pos]; } Fixed_vector& operator=(const Fixed_vector &rhs)=delete; }; } #endif<commit_msg>add erase<commit_after>#ifndef FIXED_VECTOR_HPP #define FIXED_VECTOR_HPP #include<algorithm> #include<type_traits> #include<utility> namespace nContainer { template<class T,auto N> class Fixed_vector { public: using value_type=T; using size_type=std::remove_cv_t<decltype(N)>; using pointer=T*; using const_pointer=const T*; using reference=T&; using const_reference=const T&; using iterator=T*; using const_iterator=const T*; private: value_type data_[N]; pointer end_; public: constexpr Fixed_vector() noexcept(std::is_nothrow_default_constructible_v<T>) :end_(data_){} template<class InIter> constexpr Fixed_vector(InIter begin,InIter end) { end_=std::copy(begin,end,data_); } Fixed_vector(const Fixed_vector &rhs)=delete; constexpr reference back() noexcept { return *(end_-1); } constexpr const_reference back() const noexcept { return *(end_-1); } constexpr iterator begin() noexcept { return data_; } constexpr const_iterator begin() const noexcept { return data_; } constexpr size_type capacity() const noexcept { return N; } constexpr void clear() noexcept { end_=data_; } constexpr iterator end() noexcept { return end_; } constexpr const_iterator end() const noexcept { return end_; } constexpr bool empty() const noexcept { return data_==end_; } void erase(const const_iterator pos) { std::move(pos+1,end_,pos); } constexpr pointer data() noexcept { return data_; } constexpr const_pointer data() const noexcept { return data_; } constexpr reference front() noexcept { return data_[0]; } constexpr const_reference front() const noexcept { return data_[0]; } constexpr void pop_back() noexcept { --end_; } constexpr void push_back(const value_type &val) noexcept(std::is_nothrow_copy_assignable_v<value_type>) { *(end_++)=val; } constexpr void push_back(value_type &&val) noexcept(std::is_nothrow_move_assignable_v<value_type>) { *(end_++)=std::move(val); } constexpr void resize(const size_type new_size) noexcept { end_=data_+new_size; } constexpr size_type size() const noexcept { return end_-data_; } constexpr reference operator[](const size_type pos) { return data_[pos]; } constexpr const_reference operator[](const size_type pos) const { return data_[pos]; } Fixed_vector& operator=(const Fixed_vector &rhs)=delete; }; } #endif<|endoftext|>
<commit_before>#ifndef FIXED_VECTOR_HPP #define FIXED_VECTOR_HPP #include<algorithm> #include<type_traits> #include<utility> namespace nContainer { template<class T,auto N> class Fixed_vector { public: using value_type=T; using size_type=std::remove_cv_t<decltype(N)>; using pointer=T*; using const_pointer=const T*; using reference=T&; using const_reference=const T&; using iterator=T*; using const_iterator=const T*; private: value_type data_[N]; pointer end_; public: constexpr Fixed_vector() noexcept(std::is_nothrow_default_constructible_v<T>) :end_(data_){} Fixed_vector(const Fixed_vector &rhs) :Fixed_vector(rhs.begin(),rhs.end()){} Fixed_vector(Fixed_vector &&rhs) { end_=std::move(rhs.begin(),rhs.end(),data_); } template<class InIter> constexpr Fixed_vector(InIter begin,InIter end) { end_=std::copy(begin,end,data_); } Fixed_vector(const Fixed_vector &rhs)=delete; constexpr reference back() noexcept { return *(end_-1); } constexpr const_reference back() const noexcept { return *(end_-1); } constexpr iterator begin() noexcept { return data_; } constexpr const_iterator begin() const noexcept { return data_; } constexpr size_type capacity() const noexcept { return N; } constexpr void clear() noexcept { end_=data_; } constexpr iterator end() noexcept { return end_; } constexpr const_iterator end() const noexcept { return end_; } constexpr bool empty() const noexcept { return data_==end_; } void erase(const const_iterator pos) { std::move(pos+1,end_,pos); } constexpr pointer data() noexcept { return data_; } constexpr const_pointer data() const noexcept { return data_; } constexpr reference front() noexcept { return data_[0]; } constexpr const_reference front() const noexcept { return data_[0]; } constexpr void pop_back() noexcept { --end_; } constexpr void push_back(const value_type &val) noexcept(std::is_nothrow_copy_assignable_v<value_type>) { *(end_++)=val; } constexpr void push_back(value_type &&val) noexcept(std::is_nothrow_move_assignable_v<value_type>) { *(end_++)=std::move(val); } constexpr void resize(const size_type new_size) noexcept { end_=data_+new_size; } constexpr size_type size() const noexcept { return end_-data_; } constexpr reference operator[](const size_type pos) { return data_[pos]; } constexpr const_reference operator[](const size_type pos) const { return data_[pos]; } Fixed_vector& operator=(const Fixed_vector &rhs) { if(this!=&rhs) end_=std::copy(rhs.begin(),rhs.end(),data_); return *this; } Fixed_vector& operator=(Fixed_vector &&rhs) { if(this!=&rhs) end_=std::move(rhs.begin(),rhs.end(),data_); return *this; } }; } #endif<commit_msg>add erase & insert<commit_after>#ifndef FIXED_VECTOR_HPP #define FIXED_VECTOR_HPP #include<algorithm> #include<type_traits> #include<utility> namespace nContainer { template<class T,auto N> class Fixed_vector { public: using value_type=T; using size_type=std::remove_cv_t<decltype(N)>; using pointer=T*; using const_pointer=const T*; using reference=T&; using const_reference=const T&; using iterator=T*; using const_iterator=const T*; private: value_type data_[N]; pointer end_; public: constexpr Fixed_vector() noexcept(std::is_nothrow_default_constructible_v<T>) :end_(data_){} Fixed_vector(const Fixed_vector &rhs) :Fixed_vector(rhs.begin(),rhs.end()){} Fixed_vector(Fixed_vector &&rhs) { end_=std::move(rhs.begin(),rhs.end(),data_); } template<class InIter> constexpr Fixed_vector(InIter begin,InIter end) { end_=std::copy(begin,end,data_); } Fixed_vector(const Fixed_vector &rhs)=delete; constexpr reference back() noexcept { return *(end_-1); } constexpr const_reference back() const noexcept { return *(end_-1); } constexpr iterator begin() noexcept { return data_; } constexpr const_iterator begin() const noexcept { return data_; } constexpr size_type capacity() const noexcept { return N; } constexpr void clear() noexcept { end_=data_; } constexpr iterator end() noexcept { return end_; } constexpr const_iterator end() const noexcept { return end_; } constexpr bool empty() const noexcept { return data_==end_; } void erase(const const_iterator pos) { std::move(pos+1,end_,pos); } void erase(const const_iterator first,const const_iterator last) { std::move(last,end_,first); } constexpr pointer data() noexcept { return data_; } constexpr const_pointer data() const noexcept { return data_; } constexpr reference front() noexcept { return data_[0]; } constexpr const_reference front() const noexcept { return data_[0]; } void insert(const iterator pos,const_reference val) { std::move_backward(pos,end_,end_); *pos=val; } constexpr void pop_back() noexcept { --end_; } constexpr void push_back(const value_type &val) noexcept(std::is_nothrow_copy_assignable_v<value_type>) { *(end_++)=val; } constexpr void push_back(value_type &&val) noexcept(std::is_nothrow_move_assignable_v<value_type>) { *(end_++)=std::move(val); } constexpr void resize(const size_type new_size) noexcept { end_=data_+new_size; } constexpr size_type size() const noexcept { return end_-data_; } constexpr reference operator[](const size_type pos) { return data_[pos]; } constexpr const_reference operator[](const size_type pos) const { return data_[pos]; } Fixed_vector& operator=(const Fixed_vector &rhs) { if(this!=&rhs) end_=std::copy(rhs.begin(),rhs.end(),data_); return *this; } Fixed_vector& operator=(Fixed_vector &&rhs) { if(this!=&rhs) end_=std::move(rhs.begin(),rhs.end(),data_); return *this; } }; } #endif<|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "IFile.h" #include "IMediaLibrary.h" #include "IShow.h" #include "IShowEpisode.h" class Shows : public testing::Test { public: static IMediaLibrary* ml; protected: virtual void SetUp() { ml = MediaLibraryFactory::create(); bool res = ml->initialize( "test.db" ); ASSERT_TRUE( res ); } virtual void TearDown() { delete ml; ml = nullptr; unlink("test.db"); } }; IMediaLibrary* Shows::ml; TEST_F( Shows, Create ) { auto s = ml->createShow( "show" ); ASSERT_NE( s, nullptr ); auto s2 = ml->show( "show" ); ASSERT_EQ( s, s2 ); } TEST_F( Shows, Fetch ) { auto s = ml->createShow( "show" ); // Clear the cache delete ml; SetUp(); auto s2 = ml->show( "show" ); // The shared pointers are expected to point to different instances ASSERT_NE( s, s2 ); ASSERT_EQ( s->id(), s2->id() ); } TEST_F( Shows, SetReleaseDate ) { auto s = ml->createShow( "show" ); s->setReleaseDate( 1234 ); ASSERT_EQ( s->releaseDate(), 1234 ); delete ml; SetUp(); auto s2 = ml->show( "show" ); ASSERT_EQ( s->releaseDate(), s2->releaseDate() ); } TEST_F( Shows, SetShortSummary ) { auto s = ml->createShow( "show" ); s->setShortSummary( "summary" ); ASSERT_EQ( s->shortSummary(), "summary" ); delete ml; SetUp(); auto s2 = ml->show( "show" ); ASSERT_EQ( s->shortSummary(), s2->shortSummary() ); } TEST_F( Shows, SetArtworkUrl ) { auto s = ml->createShow( "show" ); s->setArtworkUrl( "artwork" ); ASSERT_EQ( s->artworkUrl(), "artwork" ); delete ml; SetUp(); auto s2 = ml->show( "show" ); ASSERT_EQ( s->artworkUrl(), s2->artworkUrl() ); } TEST_F( Shows, SetTvdbId ) { auto s = ml->createShow( "show" ); s->setTvdbId( "TVDBID" ); ASSERT_EQ( s->tvdbId(), "TVDBID" ); delete ml; SetUp(); auto s2 = ml->show( "show" ); ASSERT_EQ( s->tvdbId(), s2->tvdbId() ); } //////////////////////////////////////////////////// // Episodes: //////////////////////////////////////////////////// TEST_F( Shows, AddEpisode ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); ASSERT_NE( e, nullptr ); ASSERT_EQ( e->episodeNumber(), 1u ); ASSERT_EQ( e->show(), show ); ASSERT_EQ( e->name(), "episode 1" ); std::vector<ShowEpisodePtr> episodes; bool res = show->episodes( episodes ); ASSERT_TRUE( res ); ASSERT_EQ( episodes.size(), 1u ); ASSERT_EQ( episodes[0], e ); } TEST_F( Shows, SetEpisodeArtwork ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); bool res = e->setArtworkUrl( "path-to-snapshot" ); ASSERT_TRUE( res ); ASSERT_EQ( e->artworkUrl(), "path-to-snapshot" ); delete ml; SetUp(); show = ml->show( "show" ); std::vector<ShowEpisodePtr> episodes; show->episodes( episodes ); ASSERT_EQ( episodes[0]->artworkUrl(), e->artworkUrl() ); } TEST_F( Shows, SetEpisodeSeasonNumber ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); bool res = e->setSeasonNumber( 42 ); ASSERT_TRUE( res ); ASSERT_EQ( e->seasonNumber(), 42 ); delete ml; SetUp(); show = ml->show( "show" ); std::vector<ShowEpisodePtr> episodes; show->episodes( episodes ); ASSERT_EQ( episodes[0]->seasonNumber(), e->seasonNumber() ); } TEST_F( Shows, SetEpisodeSummary ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); bool res = e->setShortSummary( "Insert spoilers here" ); ASSERT_TRUE( res ); ASSERT_EQ( e->shortSummary(), "Insert spoilers here" ); delete ml; SetUp(); show = ml->show( "show" ); std::vector<ShowEpisodePtr> episodes; show->episodes( episodes ); ASSERT_EQ( episodes[0]->shortSummary(), e->shortSummary() ); } TEST_F( Shows, SetEpisodeTvdbId ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); bool res = e->setTvdbId( "TVDBID" ); ASSERT_TRUE( res ); ASSERT_EQ( e->tvdbId(), "TVDBID" ); delete ml; SetUp(); show = ml->show( "show" ); std::vector<ShowEpisodePtr> episodes; show->episodes( episodes ); ASSERT_EQ( episodes[0]->tvdbId(), e->tvdbId() ); } //////////////////////////////////////////////////// // Files links: //////////////////////////////////////////////////// TEST_F( Shows, FileSetShowEpisode ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); auto f = ml->addFile( "file" ); ASSERT_EQ( f->showEpisode(), nullptr ); f->setShowEpisode( e ); ASSERT_EQ( f->showEpisode(), e ); delete ml; SetUp(); f = ml->file( "file" ); e = f->showEpisode(); ASSERT_NE( e, nullptr ); ASSERT_EQ( e->name(), "episode 1" ); } TEST_F( Shows, DeleteShowEpisode ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); auto f = ml->addFile( "file" ); f->setShowEpisode( e ); e->destroy(); f = ml->file( "file" ); ASSERT_EQ( f, nullptr ); delete ml; SetUp(); f = ml->file( "file" ); ASSERT_EQ( f, nullptr ); } <commit_msg>Tests: Fix warning<commit_after>#include "gtest/gtest.h" #include "IFile.h" #include "IMediaLibrary.h" #include "IShow.h" #include "IShowEpisode.h" class Shows : public testing::Test { public: static IMediaLibrary* ml; protected: virtual void SetUp() { ml = MediaLibraryFactory::create(); bool res = ml->initialize( "test.db" ); ASSERT_TRUE( res ); } virtual void TearDown() { delete ml; ml = nullptr; unlink("test.db"); } }; IMediaLibrary* Shows::ml; TEST_F( Shows, Create ) { auto s = ml->createShow( "show" ); ASSERT_NE( s, nullptr ); auto s2 = ml->show( "show" ); ASSERT_EQ( s, s2 ); } TEST_F( Shows, Fetch ) { auto s = ml->createShow( "show" ); // Clear the cache delete ml; SetUp(); auto s2 = ml->show( "show" ); // The shared pointers are expected to point to different instances ASSERT_NE( s, s2 ); ASSERT_EQ( s->id(), s2->id() ); } TEST_F( Shows, SetReleaseDate ) { auto s = ml->createShow( "show" ); s->setReleaseDate( 1234 ); ASSERT_EQ( s->releaseDate(), 1234 ); delete ml; SetUp(); auto s2 = ml->show( "show" ); ASSERT_EQ( s->releaseDate(), s2->releaseDate() ); } TEST_F( Shows, SetShortSummary ) { auto s = ml->createShow( "show" ); s->setShortSummary( "summary" ); ASSERT_EQ( s->shortSummary(), "summary" ); delete ml; SetUp(); auto s2 = ml->show( "show" ); ASSERT_EQ( s->shortSummary(), s2->shortSummary() ); } TEST_F( Shows, SetArtworkUrl ) { auto s = ml->createShow( "show" ); s->setArtworkUrl( "artwork" ); ASSERT_EQ( s->artworkUrl(), "artwork" ); delete ml; SetUp(); auto s2 = ml->show( "show" ); ASSERT_EQ( s->artworkUrl(), s2->artworkUrl() ); } TEST_F( Shows, SetTvdbId ) { auto s = ml->createShow( "show" ); s->setTvdbId( "TVDBID" ); ASSERT_EQ( s->tvdbId(), "TVDBID" ); delete ml; SetUp(); auto s2 = ml->show( "show" ); ASSERT_EQ( s->tvdbId(), s2->tvdbId() ); } //////////////////////////////////////////////////// // Episodes: //////////////////////////////////////////////////// TEST_F( Shows, AddEpisode ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); ASSERT_NE( e, nullptr ); ASSERT_EQ( e->episodeNumber(), 1u ); ASSERT_EQ( e->show(), show ); ASSERT_EQ( e->name(), "episode 1" ); std::vector<ShowEpisodePtr> episodes; bool res = show->episodes( episodes ); ASSERT_TRUE( res ); ASSERT_EQ( episodes.size(), 1u ); ASSERT_EQ( episodes[0], e ); } TEST_F( Shows, SetEpisodeArtwork ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); bool res = e->setArtworkUrl( "path-to-snapshot" ); ASSERT_TRUE( res ); ASSERT_EQ( e->artworkUrl(), "path-to-snapshot" ); delete ml; SetUp(); show = ml->show( "show" ); std::vector<ShowEpisodePtr> episodes; show->episodes( episodes ); ASSERT_EQ( episodes[0]->artworkUrl(), e->artworkUrl() ); } TEST_F( Shows, SetEpisodeSeasonNumber ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); bool res = e->setSeasonNumber( 42 ); ASSERT_TRUE( res ); ASSERT_EQ( e->seasonNumber(), 42u ); delete ml; SetUp(); show = ml->show( "show" ); std::vector<ShowEpisodePtr> episodes; show->episodes( episodes ); ASSERT_EQ( episodes[0]->seasonNumber(), e->seasonNumber() ); } TEST_F( Shows, SetEpisodeSummary ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); bool res = e->setShortSummary( "Insert spoilers here" ); ASSERT_TRUE( res ); ASSERT_EQ( e->shortSummary(), "Insert spoilers here" ); delete ml; SetUp(); show = ml->show( "show" ); std::vector<ShowEpisodePtr> episodes; show->episodes( episodes ); ASSERT_EQ( episodes[0]->shortSummary(), e->shortSummary() ); } TEST_F( Shows, SetEpisodeTvdbId ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); bool res = e->setTvdbId( "TVDBID" ); ASSERT_TRUE( res ); ASSERT_EQ( e->tvdbId(), "TVDBID" ); delete ml; SetUp(); show = ml->show( "show" ); std::vector<ShowEpisodePtr> episodes; show->episodes( episodes ); ASSERT_EQ( episodes[0]->tvdbId(), e->tvdbId() ); } //////////////////////////////////////////////////// // Files links: //////////////////////////////////////////////////// TEST_F( Shows, FileSetShowEpisode ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); auto f = ml->addFile( "file" ); ASSERT_EQ( f->showEpisode(), nullptr ); f->setShowEpisode( e ); ASSERT_EQ( f->showEpisode(), e ); delete ml; SetUp(); f = ml->file( "file" ); e = f->showEpisode(); ASSERT_NE( e, nullptr ); ASSERT_EQ( e->name(), "episode 1" ); } TEST_F( Shows, DeleteShowEpisode ) { auto show = ml->createShow( "show" ); auto e = show->addEpisode( "episode 1", 1 ); auto f = ml->addFile( "file" ); f->setShowEpisode( e ); e->destroy(); f = ml->file( "file" ); ASSERT_EQ( f, nullptr ); delete ml; SetUp(); f = ml->file( "file" ); ASSERT_EQ( f, nullptr ); } <|endoftext|>
<commit_before>#include <client/clone.hpp> #include <silicium/for_each.hpp> #include <silicium/coroutine.hpp> #include <silicium/ready_future.hpp> #include <boost/test/unit_test.hpp> #include <boost/unordered_map.hpp> namespace Si { template <class T> struct is_optional : std::false_type { }; template <class T> struct is_optional<boost::optional<T>> : std::true_type { }; template <class Optional, class Transformation, class = typename std::enable_if<is_optional<typename std::decay<Optional>::type>::value, void>::type> auto map(Optional &&value, Transformation &&transform) -> boost::optional<decltype(std::forward<Transformation>(transform)(*std::forward<Optional>(value)))> { if (value) { return std::forward<Transformation>(transform)(*std::forward<Optional>(value)); } return boost::none; } } namespace { template <class To, class From> To sign_cast(From from) { BOOST_STATIC_ASSERT(std::is_integral<To>::value); BOOST_STATIC_ASSERT(std::is_integral<From>::value); BOOST_STATIC_ASSERT(sizeof(To) == sizeof(From)); return static_cast<To>(from); } struct writeable_file : fileserver::writeable_file { virtual boost::system::error_code seek(fileserver::file_offset destination) SILICIUM_OVERRIDE { BOOST_FAIL("unexpected seek"); return boost::system::error_code(); } virtual boost::system::error_code write(boost::iterator_range<char const *> const &written) SILICIUM_OVERRIDE { return boost::system::error_code(); } }; struct readonly_directory_manipulator : fileserver::directory_manipulator { explicit readonly_directory_manipulator(boost::filesystem::path location) : location(std::move(location)) { } virtual boost::system::error_code require_exists() SILICIUM_OVERRIDE { return {}; } virtual std::unique_ptr<fileserver::directory_manipulator> edit_subdirectory(std::string const &name) SILICIUM_OVERRIDE { return Si::make_unique<readonly_directory_manipulator>(location / name); } virtual Si::error_or<std::unique_ptr<fileserver::writeable_file>> create_regular_file(std::string const &name) SILICIUM_OVERRIDE { return boost::system::error_code(EPERM, boost::system::system_category()); } virtual Si::error_or<fileserver::read_write_file> read_write_regular_file(std::string const &name) SILICIUM_OVERRIDE { return boost::system::error_code(EPERM, boost::system::system_category()); } private: boost::filesystem::path location; }; struct file_service : fileserver::file_service { boost::unordered_map<fileserver::unknown_digest, std::shared_ptr<std::vector<char> const>> files; virtual Si::unique_observable<Si::error_or<fileserver::linear_file>> open(fileserver::unknown_digest const &name) SILICIUM_OVERRIDE { auto it = files.find(name); if (it == files.end()) { return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::linear_file>(boost::system::error_code(fileserver::service_error::file_not_found)))); } auto file = it->second; return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::linear_file>( fileserver::linear_file{ sign_cast<fileserver::file_offset>(file->size()), Si::erase_unique(Si::make_coroutine<Si::error_or<Si::incoming_bytes>>([file](Si::push_context<Si::error_or<Si::incoming_bytes>> push) { push(Si::incoming_bytes(file->data(), file->data() + file->size())); })) } ))); } virtual Si::unique_observable<Si::error_or<fileserver::file_offset>> size(fileserver::unknown_digest const &name) SILICIUM_OVERRIDE { auto it = files.find(name); if (it == files.end()) { return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::file_offset>(boost::system::error_code(fileserver::service_error::file_not_found)))); } return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::file_offset>(it->second->size()))); } }; } BOOST_AUTO_TEST_CASE(client_clone_empty) { fileserver::unknown_digest const root; readonly_directory_manipulator dir("."); boost::asio::io_service io; file_service service; service.files.insert(std::make_pair(root, Si::to_shared(std::vector<char>{'{', '}'}))); bool has_finished = false; auto all = Si::for_each(fileserver::clone_directory(root, dir, service, io), [&has_finished](boost::system::error_code ec) { has_finished = true; BOOST_CHECK_EQUAL(boost::system::error_code(), ec); }); all.start(); io.run(); BOOST_CHECK(has_finished); } <commit_msg>return a more suitable error code<commit_after>#include <client/clone.hpp> #include <silicium/for_each.hpp> #include <silicium/coroutine.hpp> #include <silicium/ready_future.hpp> #include <boost/test/unit_test.hpp> #include <boost/unordered_map.hpp> namespace Si { template <class T> struct is_optional : std::false_type { }; template <class T> struct is_optional<boost::optional<T>> : std::true_type { }; template <class Optional, class Transformation, class = typename std::enable_if<is_optional<typename std::decay<Optional>::type>::value, void>::type> auto map(Optional &&value, Transformation &&transform) -> boost::optional<decltype(std::forward<Transformation>(transform)(*std::forward<Optional>(value)))> { if (value) { return std::forward<Transformation>(transform)(*std::forward<Optional>(value)); } return boost::none; } } namespace { template <class To, class From> To sign_cast(From from) { BOOST_STATIC_ASSERT(std::is_integral<To>::value); BOOST_STATIC_ASSERT(std::is_integral<From>::value); BOOST_STATIC_ASSERT(sizeof(To) == sizeof(From)); return static_cast<To>(from); } struct writeable_file : fileserver::writeable_file { virtual boost::system::error_code seek(fileserver::file_offset destination) SILICIUM_OVERRIDE { BOOST_FAIL("unexpected seek"); return boost::system::error_code(); } virtual boost::system::error_code write(boost::iterator_range<char const *> const &written) SILICIUM_OVERRIDE { return boost::system::error_code(); } }; struct readonly_directory_manipulator : fileserver::directory_manipulator { explicit readonly_directory_manipulator(boost::filesystem::path location) : location(std::move(location)) { } virtual boost::system::error_code require_exists() SILICIUM_OVERRIDE { return {}; } virtual std::unique_ptr<fileserver::directory_manipulator> edit_subdirectory(std::string const &name) SILICIUM_OVERRIDE { return Si::make_unique<readonly_directory_manipulator>(location / name); } virtual Si::error_or<std::unique_ptr<fileserver::writeable_file>> create_regular_file(std::string const &name) SILICIUM_OVERRIDE { return boost::system::error_code(EACCES, boost::system::system_category()); } virtual Si::error_or<fileserver::read_write_file> read_write_regular_file(std::string const &name) SILICIUM_OVERRIDE { return boost::system::error_code(EACCES, boost::system::system_category()); } private: boost::filesystem::path location; }; struct file_service : fileserver::file_service { boost::unordered_map<fileserver::unknown_digest, std::shared_ptr<std::vector<char> const>> files; virtual Si::unique_observable<Si::error_or<fileserver::linear_file>> open(fileserver::unknown_digest const &name) SILICIUM_OVERRIDE { auto it = files.find(name); if (it == files.end()) { return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::linear_file>(boost::system::error_code(fileserver::service_error::file_not_found)))); } auto file = it->second; return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::linear_file>( fileserver::linear_file{ sign_cast<fileserver::file_offset>(file->size()), Si::erase_unique(Si::make_coroutine<Si::error_or<Si::incoming_bytes>>([file](Si::push_context<Si::error_or<Si::incoming_bytes>> push) { push(Si::incoming_bytes(file->data(), file->data() + file->size())); })) } ))); } virtual Si::unique_observable<Si::error_or<fileserver::file_offset>> size(fileserver::unknown_digest const &name) SILICIUM_OVERRIDE { auto it = files.find(name); if (it == files.end()) { return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::file_offset>(boost::system::error_code(fileserver::service_error::file_not_found)))); } return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::file_offset>(it->second->size()))); } }; } BOOST_AUTO_TEST_CASE(client_clone_empty) { fileserver::unknown_digest const root; readonly_directory_manipulator dir("."); boost::asio::io_service io; file_service service; service.files.insert(std::make_pair(root, Si::to_shared(std::vector<char>{'{', '}'}))); bool has_finished = false; auto all = Si::for_each(fileserver::clone_directory(root, dir, service, io), [&has_finished](boost::system::error_code ec) { has_finished = true; BOOST_CHECK_EQUAL(boost::system::error_code(), ec); }); all.start(); io.run(); BOOST_CHECK(has_finished); } <|endoftext|>
<commit_before>#include <ctime> #include <iostream> #include <cstdlib> #include <iterator> #include <timedb.h> #include <ctime> #include <limits> #include <cmath> int main(int argc, char *argv[]) { auto test_buffer_size=1024*1024*100; uint8_t *buffer=new uint8_t[test_buffer_size]; //delta compression std::fill(buffer,buffer+test_buffer_size,0); { timedb::compression::BinaryBuffer bw(buffer,buffer+test_buffer_size); timedb::compression::DeltaCompressor dc(bw); std::vector<timedb::Time> deltas{50,255,1024,2050}; timedb::Time t=0; auto start=clock(); for(size_t i=0;i<1000000;i++){ dc.append(t); t+=deltas[i%deltas.size()]; if (t > std::numeric_limits<timedb::Time>::max()){ t=0; } } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"delta copmressor : "<<elapsed<<std::endl; } { timedb::compression::BinaryBuffer bw(buffer,buffer+test_buffer_size); timedb::compression::DeltaDeCompressor dc(bw,0); auto start=clock(); for(size_t i=1;i<1000000;i++){ dc.read(); } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"delta decopmressor : "<<elapsed<<std::endl; } //xor compression std::fill(buffer,buffer+test_buffer_size,0); { timedb::compression::BinaryBuffer bw(buffer,buffer+test_buffer_size); timedb::compression::XorCompressor dc(bw); timedb::Value t=1; auto start=clock(); for(size_t i=0;i<1000000;i++){ dc.append(t); t*=2; } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"xor copmressor : "<<elapsed<<std::endl; } { timedb::compression::BinaryBuffer bw(buffer,buffer+test_buffer_size); timedb::compression::XorDeCompressor dc(bw,0); auto start=clock(); for(size_t i=1;i<1000000;i++){ dc.read(); } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"xor decopmressor : "<<elapsed<<std::endl; } { uint8_t* time_begin=new uint8_t[test_buffer_size]; auto time_end = time_begin + test_buffer_size; uint8_t* value_begin = new uint8_t[test_buffer_size]; auto value_end = value_begin + test_buffer_size; uint8_t* flag_begin = new uint8_t[test_buffer_size]; auto flag_end = flag_begin + test_buffer_size; std::fill(time_begin, time_end, 0); std::fill(flag_begin, flag_end, 0); std::fill(value_begin, value_end, 0); timedb::compression::CopmressedWriter cwr(timedb::compression::BinaryBuffer(time_begin, time_end), timedb::compression::BinaryBuffer(value_begin, value_end), timedb::compression::BinaryBuffer(flag_begin, flag_end)); auto start = clock(); for (int i = 0; i < 1000000; i++) { auto m = timedb::Meas::empty(); m.time = i; m.flag = i; m.value = i; cwr.append(m); } auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "compress writer : " << elapsed << std::endl; auto m = timedb::Meas::empty(); timedb::compression::CopmressedReader crr(timedb::compression::BinaryBuffer(time_begin, time_end), timedb::compression::BinaryBuffer(value_begin, value_end), timedb::compression::BinaryBuffer(flag_begin, flag_end),m); start = clock(); for (int i = 1; i < 1000000; i++) { crr.read(); } elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "compress reader : " << elapsed << std::endl; delete[] time_begin; delete[] value_begin; delete[] flag_begin; } delete[]buffer; } <commit_msg>copmressor => compressor<commit_after>#include <ctime> #include <iostream> #include <cstdlib> #include <iterator> #include <timedb.h> #include <ctime> #include <limits> #include <cmath> int main(int argc, char *argv[]) { auto test_buffer_size=1024*1024*100; uint8_t *buffer=new uint8_t[test_buffer_size]; //delta compression std::fill(buffer,buffer+test_buffer_size,0); { timedb::compression::BinaryBuffer bw(buffer,buffer+test_buffer_size); timedb::compression::DeltaCompressor dc(bw); std::vector<timedb::Time> deltas{50,255,1024,2050}; timedb::Time t=0; auto start=clock(); for(size_t i=0;i<1000000;i++){ dc.append(t); t+=deltas[i%deltas.size()]; if (t > std::numeric_limits<timedb::Time>::max()){ t=0; } } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"delta compressor : "<<elapsed<<std::endl; } { timedb::compression::BinaryBuffer bw(buffer,buffer+test_buffer_size); timedb::compression::DeltaDeCompressor dc(bw,0); auto start=clock(); for(size_t i=1;i<1000000;i++){ dc.read(); } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"delta decompressor : "<<elapsed<<std::endl; } //xor compression std::fill(buffer,buffer+test_buffer_size,0); { timedb::compression::BinaryBuffer bw(buffer,buffer+test_buffer_size); timedb::compression::XorCompressor dc(bw); timedb::Value t=1; auto start=clock(); for(size_t i=0;i<1000000;i++){ dc.append(t); t*=2; } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"xor compressor : "<<elapsed<<std::endl; } { timedb::compression::BinaryBuffer bw(buffer,buffer+test_buffer_size); timedb::compression::XorDeCompressor dc(bw,0); auto start=clock(); for(size_t i=1;i<1000000;i++){ dc.read(); } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"xor decompressor : "<<elapsed<<std::endl; } { uint8_t* time_begin=new uint8_t[test_buffer_size]; auto time_end = time_begin + test_buffer_size; uint8_t* value_begin = new uint8_t[test_buffer_size]; auto value_end = value_begin + test_buffer_size; uint8_t* flag_begin = new uint8_t[test_buffer_size]; auto flag_end = flag_begin + test_buffer_size; std::fill(time_begin, time_end, 0); std::fill(flag_begin, flag_end, 0); std::fill(value_begin, value_end, 0); timedb::compression::CopmressedWriter cwr(timedb::compression::BinaryBuffer(time_begin, time_end), timedb::compression::BinaryBuffer(value_begin, value_end), timedb::compression::BinaryBuffer(flag_begin, flag_end)); auto start = clock(); for (int i = 0; i < 1000000; i++) { auto m = timedb::Meas::empty(); m.time = i; m.flag = i; m.value = i; cwr.append(m); } auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "compress writer : " << elapsed << std::endl; auto m = timedb::Meas::empty(); timedb::compression::CopmressedReader crr(timedb::compression::BinaryBuffer(time_begin, time_end), timedb::compression::BinaryBuffer(value_begin, value_end), timedb::compression::BinaryBuffer(flag_begin, flag_end),m); start = clock(); for (int i = 1; i < 1000000; i++) { crr.read(); } elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "compress reader : " << elapsed << std::endl; delete[] time_begin; delete[] value_begin; delete[] flag_begin; } delete[]buffer; } <|endoftext|>
<commit_before>/* * Copyright 2017 deepstreamHub GmbH * * 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. */ #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <algorithm> #include <buffer.hpp> #include <event.hpp> #include <message.hpp> #include <scope_guard.hpp> namespace deepstream { BOOST_AUTO_TEST_CASE(simple) { int state = -1; const Event::Name name("name"); const std::string pattern("pattern"); auto send = [&state, name, pattern] (const Message& message) { if( state == -1 ) BOOST_FAIL( "Internal state is faulty" ); DEEPSTREAM_ON_EXIT( [&state] () { state = -1; } ); BOOST_CHECK_EQUAL( message.topic(), Topic::EVENT ); if( state == 0 ) { BOOST_CHECK_EQUAL( message.action(), Action::SUBSCRIBE ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( name.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), name.cbegin()) ); return true; } if( state == 1 ) { BOOST_CHECK_EQUAL( message.action(), Action::LISTEN ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( pattern.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), pattern.cbegin()) ); return true; } if( state == 2 ) { BOOST_CHECK_EQUAL( message.action(), Action::UNSUBSCRIBE ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( name.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), name.cbegin()) ); return true; } if( state == 3 ) { BOOST_CHECK_EQUAL( message.action(), Action::UNLISTEN ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( pattern.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), pattern.cbegin()) ); return true; } assert(0); return false; }; Event event(send); Event::SubscribeFn f = [] (const Buffer&) {}; Event::SubscribeFnPtr p1( new Event::SubscribeFn(f) ); Event::SubscribeFnPtr p2( new Event::SubscribeFn(f) ); state = 0; event.subscribe(name, p1); { BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); auto it = event.subscriber_map_.find(name); BOOST_REQUIRE( it != event.subscriber_map_.end() ); BOOST_CHECK_EQUAL( it->second.size(), 1 ); BOOST_CHECK_EQUAL( it->second.front(), p1 ); } event.subscribe(name, p2); { BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); auto it = event.subscriber_map_.find(name); BOOST_REQUIRE( it != event.subscriber_map_.end() ); BOOST_CHECK_EQUAL( it->second.size(), 2 ); } event.unsubscribe(name, p1); { BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); auto it = event.subscriber_map_.find(name); BOOST_REQUIRE( it != event.subscriber_map_.end() ); BOOST_CHECK_EQUAL( it->second.size(), 1 ); } BOOST_CHECK( event.listener_map_.empty() ); Event::ListenFn g = [] (const Event::Name&, const Buffer&) {}; Event::ListenFnPtr q1( new Event::ListenFn(g) ); Event::ListenFnPtr q2( new Event::ListenFn(g) ); state = 1; event.listen(pattern, q1); { BOOST_CHECK_EQUAL( event.listener_map_.size(), 1 ); auto it = event.listener_map_.find(pattern); BOOST_REQUIRE( it != event.listener_map_.end() ); BOOST_REQUIRE_EQUAL( it->first, pattern ); BOOST_REQUIRE_EQUAL( it->second, q1 ); } event.listen(pattern, q2); { BOOST_CHECK_EQUAL( event.listener_map_.size(), 1 ); auto it = event.listener_map_.find(pattern); BOOST_REQUIRE( it != event.listener_map_.end() ); BOOST_REQUIRE_EQUAL( it->first, pattern ); BOOST_REQUIRE_EQUAL( it->second, q1 ); } BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); event.unsubscribe(name, p1); // we removed p1 above already BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); state = 2; event.unsubscribe(name, p2); BOOST_CHECK( event.subscriber_map_.empty() ); BOOST_CHECK_EQUAL( event.listener_map_.size(), 1 ); state = 3; event.unlisten(pattern); BOOST_CHECK( event.subscriber_map_.empty() ); BOOST_CHECK( event.listener_map_.empty() ); } } <commit_msg>Test: add event notification test<commit_after>/* * Copyright 2017 deepstreamHub GmbH * * 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. */ #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <algorithm> #include <buffer.hpp> #include <event.hpp> #include <message.hpp> #include <message_builder.hpp> #include <scope_guard.hpp> namespace deepstream { BOOST_AUTO_TEST_CASE(simple) { int state = -1; const Event::Name name("name"); const std::string pattern("pattern"); auto send = [&state, name, pattern] (const Message& message) { if( state == -1 ) BOOST_FAIL( "Internal state is faulty" ); DEEPSTREAM_ON_EXIT( [&state] () { state = -1; } ); BOOST_CHECK_EQUAL( message.topic(), Topic::EVENT ); if( state == 0 ) { BOOST_CHECK_EQUAL( message.action(), Action::SUBSCRIBE ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( name.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), name.cbegin()) ); return true; } if( state == 1 ) { BOOST_CHECK_EQUAL( message.action(), Action::LISTEN ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( pattern.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), pattern.cbegin()) ); return true; } if( state == 2 ) { BOOST_CHECK_EQUAL( message.action(), Action::UNSUBSCRIBE ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( name.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), name.cbegin()) ); return true; } if( state == 3 ) { BOOST_CHECK_EQUAL( message.action(), Action::UNLISTEN ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( pattern.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), pattern.cbegin()) ); return true; } assert(0); return false; }; Event event(send); Event::SubscribeFn f = [] (const Buffer&) {}; Event::SubscribeFnPtr p1( new Event::SubscribeFn(f) ); Event::SubscribeFnPtr p2( new Event::SubscribeFn(f) ); state = 0; event.subscribe(name, p1); { BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); auto it = event.subscriber_map_.find(name); BOOST_REQUIRE( it != event.subscriber_map_.end() ); BOOST_CHECK_EQUAL( it->second.size(), 1 ); BOOST_CHECK_EQUAL( it->second.front(), p1 ); } event.subscribe(name, p2); { BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); auto it = event.subscriber_map_.find(name); BOOST_REQUIRE( it != event.subscriber_map_.end() ); BOOST_CHECK_EQUAL( it->second.size(), 2 ); } event.unsubscribe(name, p1); { BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); auto it = event.subscriber_map_.find(name); BOOST_REQUIRE( it != event.subscriber_map_.end() ); BOOST_CHECK_EQUAL( it->second.size(), 1 ); } BOOST_CHECK( event.listener_map_.empty() ); Event::ListenFn g = [] (const Event::Name&, const Buffer&) {}; Event::ListenFnPtr q1( new Event::ListenFn(g) ); Event::ListenFnPtr q2( new Event::ListenFn(g) ); state = 1; event.listen(pattern, q1); { BOOST_CHECK_EQUAL( event.listener_map_.size(), 1 ); auto it = event.listener_map_.find(pattern); BOOST_REQUIRE( it != event.listener_map_.end() ); BOOST_REQUIRE_EQUAL( it->first, pattern ); BOOST_REQUIRE_EQUAL( it->second, q1 ); } event.listen(pattern, q2); { BOOST_CHECK_EQUAL( event.listener_map_.size(), 1 ); auto it = event.listener_map_.find(pattern); BOOST_REQUIRE( it != event.listener_map_.end() ); BOOST_REQUIRE_EQUAL( it->first, pattern ); BOOST_REQUIRE_EQUAL( it->second, q1 ); } BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); event.unsubscribe(name, p1); // we removed p1 above already BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); state = 2; event.unsubscribe(name, p2); BOOST_CHECK( event.subscriber_map_.empty() ); BOOST_CHECK_EQUAL( event.listener_map_.size(), 1 ); state = 3; event.unlisten(pattern); BOOST_CHECK( event.subscriber_map_.empty() ); BOOST_CHECK( event.listener_map_.empty() ); } BOOST_AUTO_TEST_CASE(subscriber_notification) { const Event::Name name("name"); const Buffer data("data"); bool is_subscribed = false; auto send = [name, &is_subscribed] (const Message& message) -> bool { BOOST_CHECK_EQUAL( message.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( message.action(), Action::SUBSCRIBE ); BOOST_CHECK( std::equal(name.cbegin(), name.cend(), message[0].cbegin()) ); is_subscribed = true; return true; }; Event event(send); unsigned num_calls = 0; Event::SubscribeFn f = [data, &num_calls] (const Buffer& my_data) { BOOST_CHECK( std::equal(data.cbegin(), data.cend(), my_data.cbegin()) ); ++num_calls; }; Event::SubscribeFnPtr p_f = event.subscribe(name, f); BOOST_CHECK( p_f ); BOOST_CHECK( is_subscribed ); BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); MessageBuilder message(Topic::EVENT, Action::EVENT); message.add_argument(name); message.add_argument(data); event.notify_(message); BOOST_CHECK_EQUAL( num_calls, 1 ); event.notify_(message); BOOST_CHECK_EQUAL( num_calls, 2 ); } } <|endoftext|>
<commit_before>// Copyright (C) 2012 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include <QtCore/QString> #include "CQTabWidget.h" #include "CQMessageBox.h" #include "qtUtilities.h" #include "CQNotes.h" #include "MIRIAMUI/CQMiriamWidget.h" #include "MIRIAMUI/CQRDFTreeView.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include "function/CFunction.h" #include "UI/CQCompartment.h" #include "UI/CQSpeciesDetail.h" #include "UI/ReactionsWidget1.h" #include "UI/CQUnitDetail.h" #include <QUndoStack> #include <copasi/undoFramework/EntityRenameCommand.h> #include <copasi/UI/copasiui3window.h> #ifdef COPASI_Provenance #include "CEntityProvenanceDialog.h" #include "versioning/CModelVersion.h" #endif CQTabWidget::CQTabWidget(const ListViews::ObjectType & objectType, CopasiWidget * pCopasiWidget, QWidget * parent, Qt::WindowFlags f) : CopasiWidget(parent, NULL, f), mPages(), mObjectType(objectType), mIgnoreLeave(false) { setupUi(this); mpLblName->setText("<h3>" + FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) + "</h3>"); mpTabWidget->addTab(pCopasiWidget, "Details"); mPages.push_back(pCopasiWidget); switch (mObjectType) { case ListViews::MODEL: mpBtnNew->hide(); mpBtnCopy->hide(); mpBtnDelete->hide(); break; case ListViews::MODELPARAMETERSET: mpBtnNew->setText("Apply"); mpBtnNew->setToolTip("Apply the current parameters to the model."); // The break statement is intentionally missing default: CQNotes* pNotes = new CQNotes(mpTabWidget); mPages.push_back(pNotes); mpTabWidget->addTab(pNotes, "Notes"); connect(this, SIGNAL(newClicked()), pCopasiWidget, SLOT(slotBtnNew())); connect(this, SIGNAL(copyClicked()), pCopasiWidget, SLOT(slotBtnCopy())); connect(this, SIGNAL(deleteClicked()), pCopasiWidget, SLOT(slotBtnDelete())); connect(this, SIGNAL(copyClicked()), pNotes, SLOT(slotBtnCopy())); break; } CQMiriamWidget* pMIRIAMWidget = new CQMiriamWidget(mpTabWidget); mPages.push_back(pMIRIAMWidget); mpTabWidget->addTab(pMIRIAMWidget, "Annotation"); connect(this, SIGNAL(copyClicked()), pMIRIAMWidget, SLOT(slotBtnCopy())); CQRDFTreeView* pRDFTreeView = new CQRDFTreeView(mpTabWidget); mPages.push_back(pRDFTreeView); mpTabWidget->addTab(pRDFTreeView, "RDF Browser"); CopasiUI3Window * pWindow = dynamic_cast<CopasiUI3Window * >(parent->parent()); setUndoStack(pWindow->getUndoStack()); #ifdef COPASI_Provenance if ((FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Species") || (FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Compartment") || (FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Reaction") || (FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Event") || (FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Global Quantity")) { CEntityProvenanceDialog* pEntityProvenanceDialog = new CEntityProvenanceDialog(mpTabWidget, mpUndoStack, "New Compartment2", pWindow->getVersionHierarchy()->getPathFile(), pWindow->getVersionHierarchy()->getVersionsPathToCurrentModel(), pWindow->getProvenanceParentOfCurrentVersion(), pWindow->getVersionHierarchy()->getParentOfCurrentModel()); mPages.push_back(pEntityProvenanceDialog); mpTabWidget->addTab(pEntityProvenanceDialog, "Provenance"); //connect(this, SIGNAL(),EntityProvenanceDialog ,SLOT(EntityProvenanceDialog->exec())); } #endif } CQTabWidget::~CQTabWidget() { // TODO Auto-generated destructor stub } bool CQTabWidget::leave() { if (mIgnoreLeave) return true; bool success = save(); std::vector< CopasiWidget * >::iterator it = mPages.begin(); std::vector< CopasiWidget * >::iterator end = mPages.end(); for (; it != end; ++it) success &= (*it)->leave(); return true; } bool CQTabWidget::enterProtected() { load(); std::vector< CopasiWidget * >::iterator it = mPages.begin(); std::vector< CopasiWidget * >::iterator end = mPages.end(); for (; it != end; ++it) (*it)->enter(mKey); return true; } bool CQTabWidget::update(ListViews::ObjectType objectType, ListViews::Action action, const std::string & key) { if (mIgnoreUpdates) return true; if (objectType == mObjectType && key == mKey) { switch (action) { case ListViews::RENAME: load(); break; case ListViews::DELETE: mpObject = NULL; break; default: break; } } // We do not need to update the child pages as they are directly called from listviews. return true; } void CQTabWidget::selectTab(int index) const { mpTabWidget->setCurrentIndex(index); } void CQTabWidget::load() { // mpObject can not be trusted mpObject = CCopasiRootContainer::getKeyFactory()->get(mKey); if (mpObject != NULL) { mpEditName->setText(FROM_UTF8(mpObject->getObjectName())); if (mObjectType == ListViews::FUNCTION) { bool readOnly = static_cast< const CFunction * >(mpObject)->isReadOnly(); mpEditName->setReadOnly(readOnly); mpBtnCommit->setEnabled(!readOnly); mpBtnRevert->setEnabled(!readOnly); mpBtnDelete->setEnabled(!readOnly); } else if (mObjectType == ListViews::UNIT) { bool readOnly = static_cast< const CUnitDefinition * >(mpObject)->isReadOnly(); mpEditName->setReadOnly(readOnly); mpBtnCommit->setEnabled(!readOnly); mpBtnRevert->setEnabled(!readOnly); mpBtnDelete->setEnabled(!readOnly); } } else { mpEditName->setText(""); } } bool CQTabWidget::save() { // mpObject can not be trusted mpObject = CCopasiRootContainer::getKeyFactory()->get(mKey); if (mpObject == NULL) return false; // We need to tell the sub-widgets to ignore all notifications std::vector< CopasiWidget * >::iterator it = mPages.begin(); std::vector< CopasiWidget * >::iterator end = mPages.end(); for (; it != end; ++it) (*it)->setIgnoreUpdates(true); if (mpObject->getObjectName() != TO_UTF8(mpEditName->text())) { mpUndoStack->push(new EntityRenameCommand(mpObject, mpObject->getObjectName(), TO_UTF8(mpEditName->text()), this)); } // We need to tell the sub-widgets to accept notifications again it = mPages.begin(); end = mPages.end(); for (; it != end; ++it) (*it)->setIgnoreUpdates(false); return true; } void CQTabWidget::slotBtnCommit() { mpBtnCommit->setFocus(); leave(); enterProtected(); } void CQTabWidget::slotBtnRevert() { enterProtected(); } void CQTabWidget::slotBtnDelete() { mIgnoreLeave = true; emit deleteClicked(); mIgnoreLeave = false; } void CQTabWidget::slotBtnNew() { mpBtnNew->setFocus(); leave(); mIgnoreLeave = true; emit newClicked(); mIgnoreLeave = false; } void CQTabWidget::slotBtnCopy() { mpBtnCopy->setFocus(); leave(); mIgnoreLeave = true; // CQCompartments and CQSpecies have copy options, use CModelExpansion, and do their own switching. if (QString(mPages[0]->metaObject()->className()) == "CQCompartment") { CQCompartment * pQCompartment = dynamic_cast< CQCompartment * >(mPages[0]); pQCompartment->copy(); } else if (QString(mPages[0]->metaObject()->className()) == "CQSpeciesDetail") { CQSpeciesDetail * pQSpeciesDetail = dynamic_cast< CQSpeciesDetail * >(mPages[0]); pQSpeciesDetail->copy(); } else if (QString(mPages[0]->metaObject()->className()) == "ReactionsWidget1") { ReactionsWidget1 * pReactionsWidget1 = dynamic_cast< ReactionsWidget1 * >(mPages[0]); pReactionsWidget1->copy(); } else if (QString(mPages[0]->metaObject()->className()) == "CQUnitDetail") { emit copyClicked(); } else { emit copyClicked(); emit newClicked(); } mIgnoreLeave = false; } bool CQTabWidget::renameEntity(const std::string& key, const std::string& newName) { mKey = key; load(); mpListView->switchToOtherWidget(C_INVALID_INDEX, mKey); qApp->processEvents(); if (!mpObject->setObjectName(newName)) { QString msg; msg = "Unable to rename " + FROM_UTF8(ListViews::ObjectTypeName[mObjectType]).toLower() + " '" + FROM_UTF8(mpObject->getObjectName()) + "'\n" + "to '" + FROM_UTF8(newName) + "' since a " + FROM_UTF8(ListViews::ObjectTypeName[mObjectType]).toLower() + " with that name already exists.\n"; CQMessageBox::information(this, "Unable to rename " + FROM_UTF8(ListViews::ObjectTypeName[mObjectType]), msg, QMessageBox::Ok, QMessageBox::Ok); mpEditName->setText(FROM_UTF8(mpObject->getObjectName())); return false; } mpEditName->setText(FROM_UTF8(newName)); protectedNotify(mObjectType, ListViews::RENAME, mKey); if (mpDataModel != NULL) { mpDataModel->changed(); } return true; } <commit_msg>copasi/UI/CQTabWidget.cpp<commit_after>// Copyright (C) 2012 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include <QtCore/QString> #include "CQTabWidget.h" #include "CQMessageBox.h" #include "qtUtilities.h" #include "CQNotes.h" #include "MIRIAMUI/CQMiriamWidget.h" #include "MIRIAMUI/CQRDFTreeView.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include "function/CFunction.h" #include "UI/CQCompartment.h" #include "UI/CQSpeciesDetail.h" #include "UI/ReactionsWidget1.h" #include "UI/CQUnitDetail.h" #include <QUndoStack> #include <copasi/undoFramework/EntityRenameCommand.h> #include <copasi/UI/copasiui3window.h> #ifdef COPASI_Provenance #include "CEntityProvenanceDialog.h" #include "versioning/CModelVersion.h" #include "commandline/CConfigurationFile.h" #endif CQTabWidget::CQTabWidget(const ListViews::ObjectType & objectType, CopasiWidget * pCopasiWidget, QWidget * parent, Qt::WindowFlags f) : CopasiWidget(parent, NULL, f), mPages(), mObjectType(objectType), mIgnoreLeave(false) { setupUi(this); mpLblName->setText("<h3>" + FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) + "</h3>"); mpTabWidget->addTab(pCopasiWidget, "Details"); mPages.push_back(pCopasiWidget); switch (mObjectType) { case ListViews::MODEL: mpBtnNew->hide(); mpBtnCopy->hide(); mpBtnDelete->hide(); break; case ListViews::MODELPARAMETERSET: mpBtnNew->setText("Apply"); mpBtnNew->setToolTip("Apply the current parameters to the model."); // The break statement is intentionally missing default: CQNotes* pNotes = new CQNotes(mpTabWidget); mPages.push_back(pNotes); mpTabWidget->addTab(pNotes, "Notes"); connect(this, SIGNAL(newClicked()), pCopasiWidget, SLOT(slotBtnNew())); connect(this, SIGNAL(copyClicked()), pCopasiWidget, SLOT(slotBtnCopy())); connect(this, SIGNAL(deleteClicked()), pCopasiWidget, SLOT(slotBtnDelete())); connect(this, SIGNAL(copyClicked()), pNotes, SLOT(slotBtnCopy())); break; } CQMiriamWidget* pMIRIAMWidget = new CQMiriamWidget(mpTabWidget); mPages.push_back(pMIRIAMWidget); mpTabWidget->addTab(pMIRIAMWidget, "Annotation"); connect(this, SIGNAL(copyClicked()), pMIRIAMWidget, SLOT(slotBtnCopy())); CQRDFTreeView* pRDFTreeView = new CQRDFTreeView(mpTabWidget); mPages.push_back(pRDFTreeView); mpTabWidget->addTab(pRDFTreeView, "RDF Browser"); CopasiUI3Window * pWindow = dynamic_cast<CopasiUI3Window * >(parent->parent()); setUndoStack(pWindow->getUndoStack()); #ifdef COPASI_Provenance if ((FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Species") || (FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Compartment") || (FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Reaction") || (FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Event") || (FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Global Quantity")) { //FROM_UTF8(mpObject->getObjectName()) //mpEntityProvenanceDialog = new CEntityProvenanceDialog(mpTabWidget, mpUndoStack, metaObject()->, pWindow->getVersionHierarchy()->getPathFile(), pWindow->getVersionHierarchy()->getVersionsPathToCurrentModel(), pWindow->getProvenanceParentOfCurrentVersion(), pWindow->getVersionHierarchy()->getParentOfCurrentModel()); mpEntityProvenanceDialog = new CEntityProvenanceDialog(mpTabWidget); mPathFile = pWindow->getVersionHierarchy()->getPathFile(); mVersionPathToCurrentModel = pWindow->getVersionHierarchy()->getVersionsPathToCurrentModel(); mPages.push_back(mpEntityProvenanceDialog); mpTabWidget->addTab(mpEntityProvenanceDialog, "Provenance"); //connect(this, SIGNAL(activated()), this, SLOT(mpEntityProvenanceDialog->exec())); //connect(this, SIGNAL(),EntityProvenanceDialog ,SLOT(EntityProvenanceDialog->exec())); } #endif } CQTabWidget::~CQTabWidget() { // TODO Auto-generated destructor stub } bool CQTabWidget::leave() { if (mIgnoreLeave) return true; bool success = save(); std::vector< CopasiWidget * >::iterator it = mPages.begin(); std::vector< CopasiWidget * >::iterator end = mPages.end(); for (; it != end; ++it) success &= (*it)->leave(); return true; } bool CQTabWidget::enterProtected() { load(); std::vector< CopasiWidget * >::iterator it = mPages.begin(); std::vector< CopasiWidget * >::iterator end = mPages.end(); for (; it != end; ++it) (*it)->enter(mKey); return true; } bool CQTabWidget::update(ListViews::ObjectType objectType, ListViews::Action action, const std::string & key) { if (mIgnoreUpdates) return true; if (objectType == mObjectType && key == mKey) { switch (action) { case ListViews::RENAME: load(); break; case ListViews::DELETE: mpObject = NULL; break; default: break; } } // We do not need to update the child pages as they are directly called from listviews. return true; } void CQTabWidget::selectTab(int index) const { mpTabWidget->setCurrentIndex(index); } void CQTabWidget::load() { // mpObject can not be trusted mpObject = CCopasiRootContainer::getKeyFactory()->get(mKey); if (mpObject != NULL) { mpEditName->setText(FROM_UTF8(mpObject->getObjectName())); if (mObjectType == ListViews::FUNCTION) { bool readOnly = static_cast< const CFunction * >(mpObject)->isReadOnly(); mpEditName->setReadOnly(readOnly); mpBtnCommit->setEnabled(!readOnly); mpBtnRevert->setEnabled(!readOnly); mpBtnDelete->setEnabled(!readOnly); } else if (mObjectType == ListViews::UNIT) { bool readOnly = static_cast< const CUnitDefinition * >(mpObject)->isReadOnly(); mpEditName->setReadOnly(readOnly); mpBtnCommit->setEnabled(!readOnly); mpBtnRevert->setEnabled(!readOnly); mpBtnDelete->setEnabled(!readOnly); } } else { mpEditName->setText(""); } #ifdef COPASI_Provenance if ((FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Species") || (FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Compartment") || (FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Reaction") || (FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Event") || (FROM_UTF8(ListViews::ObjectTypeName[mObjectType]) == "Global Quantity")) { mpEntityProvenanceDialog->load(mpUndoStack, FROM_UTF8(mpObject->getObjectName()), FROM_UTF8(CCopasiRootContainer::getConfiguration()->getWorkingDirectory()), mVersionPathToCurrentModel); } #endif } bool CQTabWidget::save() { // mpObject can not be trusted mpObject = CCopasiRootContainer::getKeyFactory()->get(mKey); if (mpObject == NULL) return false; // We need to tell the sub-widgets to ignore all notifications std::vector< CopasiWidget * >::iterator it = mPages.begin(); std::vector< CopasiWidget * >::iterator end = mPages.end(); for (; it != end; ++it) (*it)->setIgnoreUpdates(true); if (mpObject->getObjectName() != TO_UTF8(mpEditName->text())) { mpUndoStack->push(new EntityRenameCommand(mpObject, mpObject->getObjectName(), TO_UTF8(mpEditName->text()), this)); } // We need to tell the sub-widgets to accept notifications again it = mPages.begin(); end = mPages.end(); for (; it != end; ++it) (*it)->setIgnoreUpdates(false); return true; } void CQTabWidget::slotBtnCommit() { mpBtnCommit->setFocus(); leave(); enterProtected(); } void CQTabWidget::slotBtnRevert() { enterProtected(); } void CQTabWidget::slotBtnDelete() { mIgnoreLeave = true; emit deleteClicked(); mIgnoreLeave = false; } void CQTabWidget::slotBtnNew() { mpBtnNew->setFocus(); leave(); mIgnoreLeave = true; emit newClicked(); mIgnoreLeave = false; } void CQTabWidget::slotBtnCopy() { mpBtnCopy->setFocus(); leave(); mIgnoreLeave = true; // CQCompartments and CQSpecies have copy options, use CModelExpansion, and do their own switching. if (QString(mPages[0]->metaObject()->className()) == "CQCompartment") { CQCompartment * pQCompartment = dynamic_cast< CQCompartment * >(mPages[0]); pQCompartment->copy(); } else if (QString(mPages[0]->metaObject()->className()) == "CQSpeciesDetail") { CQSpeciesDetail * pQSpeciesDetail = dynamic_cast< CQSpeciesDetail * >(mPages[0]); pQSpeciesDetail->copy(); } else if (QString(mPages[0]->metaObject()->className()) == "ReactionsWidget1") { ReactionsWidget1 * pReactionsWidget1 = dynamic_cast< ReactionsWidget1 * >(mPages[0]); pReactionsWidget1->copy(); } else if (QString(mPages[0]->metaObject()->className()) == "CQUnitDetail") { emit copyClicked(); } else { emit copyClicked(); emit newClicked(); } mIgnoreLeave = false; } bool CQTabWidget::renameEntity(const std::string& key, const std::string& newName) { mKey = key; load(); mpListView->switchToOtherWidget(C_INVALID_INDEX, mKey); qApp->processEvents(); if (!mpObject->setObjectName(newName)) { QString msg; msg = "Unable to rename " + FROM_UTF8(ListViews::ObjectTypeName[mObjectType]).toLower() + " '" + FROM_UTF8(mpObject->getObjectName()) + "'\n" + "to '" + FROM_UTF8(newName) + "' since a " + FROM_UTF8(ListViews::ObjectTypeName[mObjectType]).toLower() + " with that name already exists.\n"; CQMessageBox::information(this, "Unable to rename " + FROM_UTF8(ListViews::ObjectTypeName[mObjectType]), msg, QMessageBox::Ok, QMessageBox::Ok); mpEditName->setText(FROM_UTF8(mpObject->getObjectName())); return false; } mpEditName->setText(FROM_UTF8(newName)); protectedNotify(mObjectType, ListViews::RENAME, mKey); if (mpDataModel != NULL) { mpDataModel->changed(); } return true; } <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/scan/CScanTask.cpp,v $ // $Revision: 1.76 $ // $Name: $ // $Author: shoops $ // $Date: 2009/02/23 16:20:18 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CScanTask class. * * This class implements a scan task which is comprised of a * of a problem and a method. * */ #include "copasi.h" #include "CScanTask.h" #include "CScanProblem.h" #include "CScanMethod.h" #include "utilities/CReadConfig.h" #include "report/CKeyFactory.h" #include "report/CReport.h" #include "model/CModel.h" #include "model/CState.h" #include "trajectory/CTrajectoryTask.h" #include "trajectory/CTrajectoryProblem.h" #include "steadystate/CSteadyStateTask.h" #include "steadystate/CSteadyStateProblem.h" #include "utilities/COutputHandler.h" #include "utilities/CProcessReport.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" CScanTask::CScanTask(const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::scan, pParent) { mpProblem = new CScanProblem(this); mpMethod = CScanMethod::createMethod(); this->add(mpMethod, true); ((CScanMethod *) mpMethod)->setProblem((CScanProblem *) mpProblem); } CScanTask::CScanTask(const CScanTask & src, const CCopasiContainer * pParent): CCopasiTask(src, pParent) { mpProblem = new CScanProblem(* (CScanProblem *) src.mpProblem, this); mpMethod = CScanMethod::createMethod(); this->add(mpMethod, true); ((CScanMethod *) mpMethod)->setProblem((CScanProblem *) mpProblem); } CScanTask::~CScanTask() {cleanup();} void CScanTask::cleanup() {} bool CScanTask::initialize(const OutputFlag & of, COutputHandler * pOutputHandler, std::ostream * pOstream) { assert(mpProblem && mpMethod); mpMethod->isValidProblem(mpProblem); bool success = true; initSubtask(pOutputHandler); CCopasiMessage::clearDeque(); if (!CCopasiTask::initialize(of, pOutputHandler, pOstream)) success = false; return success; } void CScanTask::load(CReadConfig & C_UNUSED(configBuffer)) {} bool CScanTask::process(const bool & useInitialValues) { if (!mpProblem) fatalError(); if (!mpMethod) fatalError(); //mpMethod->isValidProblem(mpProblem); CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem); if (!pProblem) fatalError(); CScanMethod * pMethod = dynamic_cast<CScanMethod *>(mpMethod); if (!pMethod) fatalError(); bool success = true; //initSubtask(); if (useInitialValues) { mpProblem->getModel()->applyInitialValues(); } //TODO: reports //initialize the method (parsing the ScanItems) pMethod->setProblem(pProblem); if (!pMethod->init()) return false; //init progress bar mProgress = 0; if (mpCallBack) { mpCallBack->setName("performing parameter scan..."); unsigned C_INT32 totalSteps = pMethod->getTotalNumberOfSteps(); mpCallBack->addItem("Number of Steps", CCopasiParameter::UINT, &mProgress, &totalSteps); if (mpSubtask) mpSubtask->setCallBack(mpCallBack); } //init output handler (plotting) output(COutputInterface::BEFORE); //calling the scanner, output is done in the callback if (!pMethod->scan()) success = false; //finishing progress bar and output //if (mpCallBack) mpCallBack->finish(); //if (mpOutputHandler) mpOutputHandler->finish(); output(COutputInterface::AFTER); if (mpSubtask) mpSubtask->setCallBack(NULL); return success; } bool CScanTask::processCallback() { bool success = mpSubtask->process(!mAdjustInitialConditions); //do output if (success && !mOutputInSubtask) output(COutputInterface::DURING); //do progress bar ++mProgress; if (mpCallBack) return mpCallBack->progress(); return true; } bool CScanTask::outputSeparatorCallback(bool isLast) { if ((!isLast) || mOutputInSubtask) separate(COutputInterface::DURING); return true; } bool CScanTask::initSubtask(COutputHandler * pOutputHandler) { if (!mpProblem) fatalError(); CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem); if (!pProblem) fatalError(); //get the parameters from the problem CCopasiTask::Type type = *(CCopasiTask::Type*) pProblem->getValue("Subtask").pUINT; CCopasiDataModel* pDataModel = getObjectDataModel(); assert(pDataModel != NULL); switch (type) { case CCopasiTask::steadyState: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Steady-State"]); break; case CCopasiTask::timeCourse: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Time-Course"]); break; case CCopasiTask::mca: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Metabolic Control Analysis"]); break; case CCopasiTask::lyap: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Lyapunov Exponents"]); break; case CCopasiTask::optimization: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Optimization"]); break; case CCopasiTask::parameterFitting: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Parameter Estimation"]); break; case CCopasiTask::sens: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Sensitivities"]); break; default: mpSubtask = NULL; } mOutputInSubtask = * pProblem->getValue("Output in subtask").pBOOL; //if (type != CCopasiTask::timeCourse) // mOutputInSubtask = false; mAdjustInitialConditions = * pProblem->getValue("Adjust initial conditions").pBOOL; if (!mpSubtask) return false; mpSubtask->getProblem()->setModel(pDataModel->getModel()); //TODO mpSubtask->setCallBack(NULL); if (mOutputInSubtask) mpSubtask->initialize(OUTPUT, pOutputHandler, NULL); else mpSubtask->initialize(NO_OUTPUT, pOutputHandler, NULL); return true; } <commit_msg>Fixed Bug 1287: The return value when initializing the subtasks was not handled at all. Additionally, the messages created during subtask initializing were not displayed.<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/scan/CScanTask.cpp,v $ // $Revision: 1.77 $ // $Name: $ // $Author: shoops $ // $Date: 2009/08/03 19:55:01 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CScanTask class. * * This class implements a scan task which is comprised of a * of a problem and a method. * */ #include "copasi.h" #include "CScanTask.h" #include "CScanProblem.h" #include "CScanMethod.h" #include "utilities/CReadConfig.h" #include "report/CKeyFactory.h" #include "report/CReport.h" #include "model/CModel.h" #include "model/CState.h" #include "trajectory/CTrajectoryTask.h" #include "trajectory/CTrajectoryProblem.h" #include "steadystate/CSteadyStateTask.h" #include "steadystate/CSteadyStateProblem.h" #include "utilities/COutputHandler.h" #include "utilities/CProcessReport.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" CScanTask::CScanTask(const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::scan, pParent) { mpProblem = new CScanProblem(this); mpMethod = CScanMethod::createMethod(); this->add(mpMethod, true); ((CScanMethod *) mpMethod)->setProblem((CScanProblem *) mpProblem); } CScanTask::CScanTask(const CScanTask & src, const CCopasiContainer * pParent): CCopasiTask(src, pParent) { mpProblem = new CScanProblem(*(CScanProblem *) src.mpProblem, this); mpMethod = CScanMethod::createMethod(); this->add(mpMethod, true); ((CScanMethod *) mpMethod)->setProblem((CScanProblem *) mpProblem); } CScanTask::~CScanTask() {cleanup();} void CScanTask::cleanup() {} bool CScanTask::initialize(const OutputFlag & of, COutputHandler * pOutputHandler, std::ostream * pOstream) { assert(mpProblem && mpMethod); mpMethod->isValidProblem(mpProblem); bool success = true; CCopasiMessage::clearDeque(); success &= initSubtask(pOutputHandler); success &= CCopasiTask::initialize(of, pOutputHandler, pOstream); return success; } void CScanTask::load(CReadConfig & C_UNUSED(configBuffer)) {} bool CScanTask::process(const bool & useInitialValues) { if (!mpProblem) fatalError(); if (!mpMethod) fatalError(); //mpMethod->isValidProblem(mpProblem); CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem); if (!pProblem) fatalError(); CScanMethod * pMethod = dynamic_cast<CScanMethod *>(mpMethod); if (!pMethod) fatalError(); bool success = true; //initSubtask(); if (useInitialValues) { mpProblem->getModel()->applyInitialValues(); } //TODO: reports //initialize the method (parsing the ScanItems) pMethod->setProblem(pProblem); if (!pMethod->init()) return false; //init progress bar mProgress = 0; if (mpCallBack) { mpCallBack->setName("performing parameter scan..."); unsigned C_INT32 totalSteps = pMethod->getTotalNumberOfSteps(); mpCallBack->addItem("Number of Steps", CCopasiParameter::UINT, &mProgress, &totalSteps); if (mpSubtask) mpSubtask->setCallBack(mpCallBack); } //init output handler (plotting) output(COutputInterface::BEFORE); //calling the scanner, output is done in the callback if (!pMethod->scan()) success = false; //finishing progress bar and output //if (mpCallBack) mpCallBack->finish(); //if (mpOutputHandler) mpOutputHandler->finish(); output(COutputInterface::AFTER); if (mpSubtask) mpSubtask->setCallBack(NULL); return success; } bool CScanTask::processCallback() { bool success = mpSubtask->process(!mAdjustInitialConditions); //do output if (success && !mOutputInSubtask) output(COutputInterface::DURING); //do progress bar ++mProgress; if (mpCallBack) return mpCallBack->progress(); return true; } bool CScanTask::outputSeparatorCallback(bool isLast) { if ((!isLast) || mOutputInSubtask) separate(COutputInterface::DURING); return true; } bool CScanTask::initSubtask(COutputHandler * pOutputHandler) { if (!mpProblem) fatalError(); CScanProblem * pProblem = dynamic_cast<CScanProblem *>(mpProblem); if (!pProblem) fatalError(); //get the parameters from the problem CCopasiTask::Type type = *(CCopasiTask::Type*) pProblem->getValue("Subtask").pUINT; CCopasiDataModel* pDataModel = getObjectDataModel(); assert(pDataModel != NULL); switch (type) { case CCopasiTask::steadyState: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Steady-State"]); break; case CCopasiTask::timeCourse: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Time-Course"]); break; case CCopasiTask::mca: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Metabolic Control Analysis"]); break; case CCopasiTask::lyap: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Lyapunov Exponents"]); break; case CCopasiTask::optimization: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Optimization"]); break; case CCopasiTask::parameterFitting: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Parameter Estimation"]); break; case CCopasiTask::sens: mpSubtask = dynamic_cast<CCopasiTask*> ((*pDataModel->getTaskList())["Sensitivities"]); break; default: mpSubtask = NULL; } mOutputInSubtask = * pProblem->getValue("Output in subtask").pBOOL; //if (type != CCopasiTask::timeCourse) // mOutputInSubtask = false; mAdjustInitialConditions = * pProblem->getValue("Adjust initial conditions").pBOOL; if (!mpSubtask) return false; mpSubtask->getProblem()->setModel(pDataModel->getModel()); //TODO mpSubtask->setCallBack(NULL); if (mOutputInSubtask) return mpSubtask->initialize(OUTPUT, pOutputHandler, NULL); else return mpSubtask->initialize(NO_OUTPUT, pOutputHandler, NULL); return true; } <|endoftext|>
<commit_before>/* * Author: Henry Bruce <henry.bruce@intel.com> * Copyright (c) 2015 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <unistd.h> #include <iostream> #include "t6713.h" #define EDISON_I2C_BUS 1 #define FT4222_I2C_BUS 0 //! [Interesting] // Simple example of using ICO2Sensor to determine // which sensor is present and return its name. // ICO2Sensor is then used to get readings from sensor upm::ICO2Sensor* getCO2Sensor() { upm::ICO2Sensor* cO2Sensor = NULL; try { cO2Sensor = new upm::T6713(mraa_get_sub_platform_id(FT4222_I2C_BUS)); return cO2Sensor; } catch (std::exception& e) { std::cerr << "T6713: " << e.what() << std::endl; } return cO2Sensor; } int main () { upm::ICO2Sensor* cO2Sensor = getCO2Sensor(); if (cO2Sensor == NULL) { std::cout << "CO2 sensor not detected" << std::endl; return 1; } std::cout << "CO2 sensor " << cO2Sensor->getModuleName() << " detected" << std::endl; while (true) { try { uint16_t value = cO2Sensor->getPpm(); std::cout << "CO2 level = " << value << " lux" << std::endl; } catch (std::exception& e) { std::cerr << e.what() << std::endl; } sleep(1); } delete cO2Sensor; return 0; } //! [Interesting] <commit_msg>cO2-sensor: changed lux to ppm<commit_after>/* * Author: Henry Bruce <henry.bruce@intel.com> * Copyright (c) 2015 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <unistd.h> #include <iostream> #include "t6713.h" #define EDISON_I2C_BUS 1 #define FT4222_I2C_BUS 0 //! [Interesting] // Simple example of using ICO2Sensor to determine // which sensor is present and return its name. // ICO2Sensor is then used to get readings from sensor upm::ICO2Sensor* getCO2Sensor() { upm::ICO2Sensor* cO2Sensor = NULL; try { cO2Sensor = new upm::T6713(mraa_get_sub_platform_id(FT4222_I2C_BUS)); return cO2Sensor; } catch (std::exception& e) { std::cerr << "T6713: " << e.what() << std::endl; } return cO2Sensor; } int main () { upm::ICO2Sensor* cO2Sensor = getCO2Sensor(); if (cO2Sensor == NULL) { std::cout << "CO2 sensor not detected" << std::endl; return 1; } std::cout << "CO2 sensor " << cO2Sensor->getModuleName() << " detected" << std::endl; while (true) { try { uint16_t value = cO2Sensor->getPpm(); std::cout << "CO2 level = " << value << " ppm" << std::endl; } catch (std::exception& e) { std::cerr << e.what() << std::endl; } sleep(1); } delete cO2Sensor; return 0; } //! [Interesting] <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/waitable_event_watcher.h" #include "base/condition_variable.h" #include "base/lock.h" #include "base/message_loop.h" #include "base/waitable_event.h" namespace base { // ----------------------------------------------------------------------------- // WaitableEventWatcher (async waits). // // The basic design is that we add an AsyncWaiter to the wait-list of the event. // That AsyncWaiter has a pointer to MessageLoop, and a Task to be posted to it. // The MessageLoop ends up running the task, which calls the delegate. // // Since the wait can be canceled, we have a thread-safe Flag object which is // set when the wait has been canceled. At each stage in the above, we check the // flag before going onto the next stage. Since the wait may only be canceled in // the MessageLoop which runs the Task, we are assured that the delegate cannot // be called after canceling... // ----------------------------------------------------------------------------- // A thread-safe, reference-counted, write-once flag. // ----------------------------------------------------------------------------- class Flag : public RefCountedThreadSafe<Flag> { public: Flag() { flag_ = false; } void Set() { AutoLock locked(lock_); flag_ = true; } bool value() const { AutoLock locked(lock_); return flag_; } private: mutable Lock lock_; bool flag_; }; // ----------------------------------------------------------------------------- // This is an asynchronous waiter which posts a task to a MessageLoop when // fired. An AsyncWaiter may only be in a single wait-list. // ----------------------------------------------------------------------------- class AsyncWaiter : public WaitableEvent::Waiter { public: AsyncWaiter(MessageLoop* message_loop, Task* task, Flag* flag) : message_loop_(message_loop), cb_task_(task), flag_(flag) { } bool Fire(WaitableEvent* event) { if (flag_->value()) { // If the callback has been canceled, we don't enqueue the task, we just // delete it instead. delete cb_task_; } else { message_loop_->PostTask(FROM_HERE, cb_task_); } // We are removed from the wait-list by the WaitableEvent itself. It only // remains to delete ourselves. delete this; // We can always return true because an AsyncWaiter is never in two // different wait-lists at the same time. return true; } // See StopWatching for discussion bool Compare(void* tag) { return tag == flag_.get(); } private: MessageLoop *const message_loop_; Task *const cb_task_; scoped_refptr<Flag> flag_; }; // ----------------------------------------------------------------------------- // For async waits we need to make a callback in a MessageLoop thread. We do // this by posting this task, which calls the delegate and keeps track of when // the event is canceled. // ----------------------------------------------------------------------------- class AsyncCallbackTask : public Task { public: AsyncCallbackTask(Flag* flag, WaitableEventWatcher::Delegate* delegate, WaitableEvent* event) : flag_(flag), delegate_(delegate), event_(event) { } void Run() { // Runs in MessageLoop thread. if (!flag_->value()) { // This is to let the WaitableEventWatcher know that the event has occured // because it needs to be able to return NULL from GetWatchedObject flag_->Set(); delegate_->OnWaitableEventSignaled(event_); } // We are deleted by the MessageLoop } private: scoped_refptr<Flag> flag_; WaitableEventWatcher::Delegate *const delegate_; WaitableEvent *const event_; }; WaitableEventWatcher::WaitableEventWatcher() : event_(NULL), message_loop_(NULL), cancel_flag_(NULL), callback_task_(NULL), delegate_(NULL) { } WaitableEventWatcher::~WaitableEventWatcher() { StopWatching(); } // ----------------------------------------------------------------------------- // The Handle is how the user cancels a wait. After deleting the Handle we // insure that the delegate cannot be called. // ----------------------------------------------------------------------------- bool WaitableEventWatcher::StartWatching (WaitableEvent* event, WaitableEventWatcher::Delegate* delegate) { MessageLoop *const current_ml = MessageLoop::current(); DCHECK(current_ml) << "Cannot create WaitableEventWatcher without a " "current MessageLoop"; // A user may call StartWatching from within the callback function. In this // case, we won't know that we have finished watching, expect that the Flag // will have been set in AsyncCallbackTask::Run() if (cancel_flag_.get() && cancel_flag_->value()) { if (message_loop_) { message_loop_->RemoveDestructionObserver(this); message_loop_ = NULL; } cancel_flag_ = NULL; } DCHECK(!cancel_flag_.get()) << "StartWatching called while still watching"; cancel_flag_ = new Flag; callback_task_ = new AsyncCallbackTask(cancel_flag_, delegate, event); WaitableEvent::WaitableEventKernel* kernel = event->kernel_.get(); AutoLock locked(kernel->lock_); delegate_ = delegate; event_ = event; if (kernel->signaled_) { if (!kernel->manual_reset_) kernel->signaled_ = false; // No hairpinning - we can't call the delegate directly here. We have to // enqueue a task on the MessageLoop as normal. current_ml->PostTask(FROM_HERE, callback_task_); return true; } message_loop_ = current_ml; current_ml->AddDestructionObserver(this); kernel_ = kernel; waiter_ = new AsyncWaiter(current_ml, callback_task_, cancel_flag_); event->Enqueue(waiter_); return true; } void WaitableEventWatcher::StopWatching() { delegate_ = NULL; if (message_loop_) { message_loop_->RemoveDestructionObserver(this); message_loop_ = NULL; } if (!cancel_flag_.get()) // if not currently watching... return; if (cancel_flag_->value()) { // In this case, the event has fired, but we haven't figured that out yet. // The WaitableEvent may have been deleted too. cancel_flag_ = NULL; return; } if (!kernel_.get()) { // We have no kernel. This means that we never enqueued a Waiter on an // event because the event was already signaled when StartWatching was // called. // // In this case, a task was enqueued on the MessageLoop and will run. // We set the flag in case the task hasn't yet run. The flag will stop the // delegate getting called. If the task has run then we have the last // reference to the flag and it will be deleted immedately after. cancel_flag_->Set(); cancel_flag_ = NULL; return; } AutoLock locked(kernel_->lock_); // We have a lock on the kernel. No one else can signal the event while we // have it. // We have a possible ABA issue here. If Dequeue was to compare only the // pointer values then it's possible that the AsyncWaiter could have been // fired, freed and the memory reused for a different Waiter which was // enqueued in the same wait-list. We would think that that waiter was our // AsyncWaiter and remove it. // // To stop this, Dequeue also takes a tag argument which is passed to the // virtual Compare function before the two are considered a match. So we need // a tag which is good for the lifetime of this handle: the Flag. Since we // have a reference to the Flag, its memory cannot be reused while this object // still exists. So if we find a waiter with the correct pointer value, and // which shares a Flag pointer, we have a real match. if (kernel_->Dequeue(waiter_, cancel_flag_.get())) { // Case 2: the waiter hasn't been signaled yet; it was still on the wait // list. We've removed it, thus we can delete it and the task (which cannot // have been enqueued with the MessageLoop because the waiter was never // signaled) delete waiter_; delete callback_task_; cancel_flag_ = NULL; return; } // Case 3: the waiter isn't on the wait-list, thus it was signaled. It may // not have run yet, so we set the flag to tell it not to bother enqueuing the // task on the MessageLoop, but to delete it instead. The Waiter deletes // itself once run. cancel_flag_->Set(); cancel_flag_ = NULL; // If the waiter has already run then the task has been enqueued. If the Task // hasn't yet run, the flag will stop the delegate from getting called. (This // is thread safe because one may only delete a Handle from the MessageLoop // thread.) // // If the delegate has already been called then we have nothing to do. The // task has been deleted by the MessageLoop. } WaitableEvent* WaitableEventWatcher::GetWatchedEvent() { if (!cancel_flag_.get()) return NULL; if (cancel_flag_->value()) return NULL; return event_; } // ----------------------------------------------------------------------------- // This is called when the MessageLoop which the callback will be run it is // deleted. We need to cancel the callback as if we had been deleted, but we // will still be deleted at some point in the future. // ----------------------------------------------------------------------------- void WaitableEventWatcher::WillDestroyCurrentMessageLoop() { StopWatching(); } } // namespace base <commit_msg>Coverity: uninitialized member in posix WaitableEventWatcher constructor.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/waitable_event_watcher.h" #include "base/condition_variable.h" #include "base/lock.h" #include "base/message_loop.h" #include "base/waitable_event.h" namespace base { // ----------------------------------------------------------------------------- // WaitableEventWatcher (async waits). // // The basic design is that we add an AsyncWaiter to the wait-list of the event. // That AsyncWaiter has a pointer to MessageLoop, and a Task to be posted to it. // The MessageLoop ends up running the task, which calls the delegate. // // Since the wait can be canceled, we have a thread-safe Flag object which is // set when the wait has been canceled. At each stage in the above, we check the // flag before going onto the next stage. Since the wait may only be canceled in // the MessageLoop which runs the Task, we are assured that the delegate cannot // be called after canceling... // ----------------------------------------------------------------------------- // A thread-safe, reference-counted, write-once flag. // ----------------------------------------------------------------------------- class Flag : public RefCountedThreadSafe<Flag> { public: Flag() { flag_ = false; } void Set() { AutoLock locked(lock_); flag_ = true; } bool value() const { AutoLock locked(lock_); return flag_; } private: mutable Lock lock_; bool flag_; }; // ----------------------------------------------------------------------------- // This is an asynchronous waiter which posts a task to a MessageLoop when // fired. An AsyncWaiter may only be in a single wait-list. // ----------------------------------------------------------------------------- class AsyncWaiter : public WaitableEvent::Waiter { public: AsyncWaiter(MessageLoop* message_loop, Task* task, Flag* flag) : message_loop_(message_loop), cb_task_(task), flag_(flag) { } bool Fire(WaitableEvent* event) { if (flag_->value()) { // If the callback has been canceled, we don't enqueue the task, we just // delete it instead. delete cb_task_; } else { message_loop_->PostTask(FROM_HERE, cb_task_); } // We are removed from the wait-list by the WaitableEvent itself. It only // remains to delete ourselves. delete this; // We can always return true because an AsyncWaiter is never in two // different wait-lists at the same time. return true; } // See StopWatching for discussion bool Compare(void* tag) { return tag == flag_.get(); } private: MessageLoop *const message_loop_; Task *const cb_task_; scoped_refptr<Flag> flag_; }; // ----------------------------------------------------------------------------- // For async waits we need to make a callback in a MessageLoop thread. We do // this by posting this task, which calls the delegate and keeps track of when // the event is canceled. // ----------------------------------------------------------------------------- class AsyncCallbackTask : public Task { public: AsyncCallbackTask(Flag* flag, WaitableEventWatcher::Delegate* delegate, WaitableEvent* event) : flag_(flag), delegate_(delegate), event_(event) { } void Run() { // Runs in MessageLoop thread. if (!flag_->value()) { // This is to let the WaitableEventWatcher know that the event has occured // because it needs to be able to return NULL from GetWatchedObject flag_->Set(); delegate_->OnWaitableEventSignaled(event_); } // We are deleted by the MessageLoop } private: scoped_refptr<Flag> flag_; WaitableEventWatcher::Delegate *const delegate_; WaitableEvent *const event_; }; WaitableEventWatcher::WaitableEventWatcher() : event_(NULL), message_loop_(NULL), cancel_flag_(NULL), waiter_(NULL), callback_task_(NULL), delegate_(NULL) { } WaitableEventWatcher::~WaitableEventWatcher() { StopWatching(); } // ----------------------------------------------------------------------------- // The Handle is how the user cancels a wait. After deleting the Handle we // insure that the delegate cannot be called. // ----------------------------------------------------------------------------- bool WaitableEventWatcher::StartWatching (WaitableEvent* event, WaitableEventWatcher::Delegate* delegate) { MessageLoop *const current_ml = MessageLoop::current(); DCHECK(current_ml) << "Cannot create WaitableEventWatcher without a " "current MessageLoop"; // A user may call StartWatching from within the callback function. In this // case, we won't know that we have finished watching, expect that the Flag // will have been set in AsyncCallbackTask::Run() if (cancel_flag_.get() && cancel_flag_->value()) { if (message_loop_) { message_loop_->RemoveDestructionObserver(this); message_loop_ = NULL; } cancel_flag_ = NULL; } DCHECK(!cancel_flag_.get()) << "StartWatching called while still watching"; cancel_flag_ = new Flag; callback_task_ = new AsyncCallbackTask(cancel_flag_, delegate, event); WaitableEvent::WaitableEventKernel* kernel = event->kernel_.get(); AutoLock locked(kernel->lock_); delegate_ = delegate; event_ = event; if (kernel->signaled_) { if (!kernel->manual_reset_) kernel->signaled_ = false; // No hairpinning - we can't call the delegate directly here. We have to // enqueue a task on the MessageLoop as normal. current_ml->PostTask(FROM_HERE, callback_task_); return true; } message_loop_ = current_ml; current_ml->AddDestructionObserver(this); kernel_ = kernel; waiter_ = new AsyncWaiter(current_ml, callback_task_, cancel_flag_); event->Enqueue(waiter_); return true; } void WaitableEventWatcher::StopWatching() { delegate_ = NULL; if (message_loop_) { message_loop_->RemoveDestructionObserver(this); message_loop_ = NULL; } if (!cancel_flag_.get()) // if not currently watching... return; if (cancel_flag_->value()) { // In this case, the event has fired, but we haven't figured that out yet. // The WaitableEvent may have been deleted too. cancel_flag_ = NULL; return; } if (!kernel_.get()) { // We have no kernel. This means that we never enqueued a Waiter on an // event because the event was already signaled when StartWatching was // called. // // In this case, a task was enqueued on the MessageLoop and will run. // We set the flag in case the task hasn't yet run. The flag will stop the // delegate getting called. If the task has run then we have the last // reference to the flag and it will be deleted immedately after. cancel_flag_->Set(); cancel_flag_ = NULL; return; } AutoLock locked(kernel_->lock_); // We have a lock on the kernel. No one else can signal the event while we // have it. // We have a possible ABA issue here. If Dequeue was to compare only the // pointer values then it's possible that the AsyncWaiter could have been // fired, freed and the memory reused for a different Waiter which was // enqueued in the same wait-list. We would think that that waiter was our // AsyncWaiter and remove it. // // To stop this, Dequeue also takes a tag argument which is passed to the // virtual Compare function before the two are considered a match. So we need // a tag which is good for the lifetime of this handle: the Flag. Since we // have a reference to the Flag, its memory cannot be reused while this object // still exists. So if we find a waiter with the correct pointer value, and // which shares a Flag pointer, we have a real match. if (kernel_->Dequeue(waiter_, cancel_flag_.get())) { // Case 2: the waiter hasn't been signaled yet; it was still on the wait // list. We've removed it, thus we can delete it and the task (which cannot // have been enqueued with the MessageLoop because the waiter was never // signaled) delete waiter_; delete callback_task_; cancel_flag_ = NULL; return; } // Case 3: the waiter isn't on the wait-list, thus it was signaled. It may // not have run yet, so we set the flag to tell it not to bother enqueuing the // task on the MessageLoop, but to delete it instead. The Waiter deletes // itself once run. cancel_flag_->Set(); cancel_flag_ = NULL; // If the waiter has already run then the task has been enqueued. If the Task // hasn't yet run, the flag will stop the delegate from getting called. (This // is thread safe because one may only delete a Handle from the MessageLoop // thread.) // // If the delegate has already been called then we have nothing to do. The // task has been deleted by the MessageLoop. } WaitableEvent* WaitableEventWatcher::GetWatchedEvent() { if (!cancel_flag_.get()) return NULL; if (cancel_flag_->value()) return NULL; return event_; } // ----------------------------------------------------------------------------- // This is called when the MessageLoop which the callback will be run it is // deleted. We need to cancel the callback as if we had been deleted, but we // will still be deleted at some point in the future. // ----------------------------------------------------------------------------- void WaitableEventWatcher::WillDestroyCurrentMessageLoop() { StopWatching(); } } // namespace base <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/voice_engine/test/auto_test/fixtures/after_streaming_fixture.h" namespace { void ExpectVolumeNear(int expected, int actual) { // The hardware volume may be more coarsely quantized than [0, 255], so // it is not always reasonable to expect to get exactly what we set. This // allows for some error. const int kMaxVolumeError = 10; EXPECT_NEAR(expected, actual, kMaxVolumeError); EXPECT_GE(actual, 0); EXPECT_LE(actual, 255); } } // namespace class VolumeTest : public AfterStreamingFixture { }; // TODO(phoglund): a number of tests are disabled here on Linux, all pending // investigation in // http://code.google.com/p/webrtc/issues/detail?id=367 TEST_F(VolumeTest, DefaultSpeakerVolumeIsAtMost255) { unsigned int volume = 1000; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); EXPECT_LE(volume, 255u); } TEST_F(VolumeTest, SetVolumeBeforePlayoutWorks) { // This is a rather specialized test, intended to exercise some PulseAudio // code. However, these conditions should be satisfied on any platform. unsigned int original_volume = 0; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume)); Sleep(1000); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(200)); unsigned int volume; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); ExpectVolumeNear(200u, volume); PausePlaying(); ResumePlaying(); EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); // Ensure the volume has not changed after resuming playout. ExpectVolumeNear(200u, volume); PausePlaying(); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100)); ResumePlaying(); // Ensure the volume set while paused is retained. EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); ExpectVolumeNear(100u, volume); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume)); } TEST_F(VolumeTest, ManualSetVolumeWorks) { unsigned int original_volume = 0; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume)); Sleep(1000); TEST_LOG("Setting speaker volume to 0 out of 255.\n"); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(0)); unsigned int volume; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); ExpectVolumeNear(0u, volume); Sleep(1000); TEST_LOG("Setting speaker volume to 100 out of 255.\n"); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100)); EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); ExpectVolumeNear(100u, volume); Sleep(1000); // Set the volume to 255 very briefly so we don't blast the poor user // listening to this. This is just to test the call succeeds. EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(255)); EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); ExpectVolumeNear(255u, volume); TEST_LOG("Setting speaker volume to the original %d out of 255.\n", original_volume); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume)); Sleep(1000); } TEST_F(VolumeTest, DISABLED_ON_LINUX(DefaultMicrophoneVolumeIsAtMost255)) { unsigned int volume = 1000; EXPECT_EQ(0, voe_volume_control_->GetMicVolume(volume)); EXPECT_LE(volume, 255u); } TEST_F(VolumeTest, DISABLED_ON_LINUX( ManualRequiresMicrophoneCanSetMicrophoneVolumeWithAcgOff)) { SwitchToManualMicrophone(); EXPECT_EQ(0, voe_apm_->SetAgcStatus(false)); unsigned int original_volume = 0; EXPECT_EQ(0, voe_volume_control_->GetMicVolume(original_volume)); TEST_LOG("Setting microphone volume to 0.\n"); EXPECT_EQ(0, voe_volume_control_->SetMicVolume(channel_)); Sleep(1000); TEST_LOG("Setting microphone volume to 255.\n"); EXPECT_EQ(0, voe_volume_control_->SetMicVolume(255)); Sleep(1000); TEST_LOG("Setting microphone volume back to saved value.\n"); EXPECT_EQ(0, voe_volume_control_->SetMicVolume(original_volume)); Sleep(1000); } TEST_F(VolumeTest, ChannelScalingIsOneByDefault) { float scaling = -1.0f; EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling( channel_, scaling)); EXPECT_FLOAT_EQ(1.0f, scaling); } TEST_F(VolumeTest, ManualCanSetChannelScaling) { EXPECT_EQ(0, voe_volume_control_->SetChannelOutputVolumeScaling( channel_, 0.1f)); float scaling = 1.0f; EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling( channel_, scaling)); EXPECT_FLOAT_EQ(0.1f, scaling); TEST_LOG("Channel scaling set to 0.1: audio should be barely audible.\n"); Sleep(2000); } TEST_F(VolumeTest, InputMutingIsNotEnabledByDefault) { bool is_muted = true; EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted)); EXPECT_FALSE(is_muted); } TEST_F(VolumeTest, DISABLED_ON_LINUX(ManualInputMutingMutesMicrophone)) { SwitchToManualMicrophone(); // Enable muting. EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, true)); bool is_muted = false; EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted)); EXPECT_TRUE(is_muted); TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n"); Sleep(2000); // Test that we can disable muting. EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, false)); EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted)); EXPECT_FALSE(is_muted); TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n"); Sleep(2000); } TEST_F(VolumeTest, DISABLED_ON_LINUX(SystemInputMutingIsNotEnabledByDefault)) { bool is_muted = true; EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted)); EXPECT_FALSE(is_muted); } TEST_F(VolumeTest, DISABLED_ON_LINUX(ManualSystemInputMutingMutesMicrophone)) { SwitchToManualMicrophone(); // Enable system input muting. EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(true)); bool is_muted = false; EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted)); EXPECT_TRUE(is_muted); TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n"); Sleep(2000); // Test that we can disable system input muting. EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(false)); EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted)); EXPECT_FALSE(is_muted); TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n"); Sleep(2000); } TEST_F(VolumeTest, DISABLED_ON_LINUX(SystemOutputMutingIsNotEnabledByDefault)) { bool is_muted = true; EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted)); EXPECT_FALSE(is_muted); } TEST_F(VolumeTest, ManualSystemOutputMutingMutesOutput) { // Enable muting. EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(true)); bool is_muted = false; EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted)); EXPECT_TRUE(is_muted); TEST_LOG("Muted: you should hear no audio.\n"); Sleep(2000); // Test that we can disable muting. EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(false)); EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted)); EXPECT_FALSE(is_muted); TEST_LOG("Unmuted: you should hear audio.\n"); Sleep(2000); } TEST_F(VolumeTest, ManualTestInputAndOutputLevels) { SwitchToManualMicrophone(); TEST_LOG("Speak and verify that the following levels look right:\n"); for (int i = 0; i < 5; i++) { Sleep(1000); unsigned int input_level = 0; unsigned int output_level = 0; unsigned int input_level_full_range = 0; unsigned int output_level_full_range = 0; EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevel( input_level)); EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevel( channel_, output_level)); EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevelFullRange( input_level_full_range)); EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevelFullRange( channel_, output_level_full_range)); TEST_LOG(" warped levels (0-9) : in=%5d, out=%5d\n", input_level, output_level); TEST_LOG(" linear levels (0-32768): in=%5d, out=%5d\n", input_level_full_range, output_level_full_range); } } TEST_F(VolumeTest, ChannelsAreNotPannedByDefault) { float left = -1.0; float right = -1.0; EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right)); EXPECT_FLOAT_EQ(1.0, left); EXPECT_FLOAT_EQ(1.0, right); } TEST_F(VolumeTest, ManualTestChannelPanning) { TEST_LOG("Panning left.\n"); EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.8f, 0.1f)); Sleep(1000); TEST_LOG("Back to center.\n"); EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 1.0f, 1.0f)); Sleep(1000); TEST_LOG("Panning right.\n"); EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.1f, 0.8f)); Sleep(1000); // To finish, verify that the getter works. float left = 0.0f; float right = 0.0f; EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right)); EXPECT_FLOAT_EQ(0.1f, left); EXPECT_FLOAT_EQ(0.8f, right); } <commit_msg>Enables VolumeTest.DefaultMicrophoneVolumeIsAtMost255<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/voice_engine/test/auto_test/fixtures/after_streaming_fixture.h" namespace { void ExpectVolumeNear(int expected, int actual) { // The hardware volume may be more coarsely quantized than [0, 255], so // it is not always reasonable to expect to get exactly what we set. This // allows for some error. const int kMaxVolumeError = 10; EXPECT_NEAR(expected, actual, kMaxVolumeError); EXPECT_GE(actual, 0); EXPECT_LE(actual, 255); } } // namespace class VolumeTest : public AfterStreamingFixture { }; // TODO(phoglund): a number of tests are disabled here on Linux, all pending // investigation in // http://code.google.com/p/webrtc/issues/detail?id=367 TEST_F(VolumeTest, DefaultSpeakerVolumeIsAtMost255) { unsigned int volume = 1000; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); EXPECT_LE(volume, 255u); } TEST_F(VolumeTest, SetVolumeBeforePlayoutWorks) { // This is a rather specialized test, intended to exercise some PulseAudio // code. However, these conditions should be satisfied on any platform. unsigned int original_volume = 0; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume)); Sleep(1000); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(200)); unsigned int volume; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); ExpectVolumeNear(200u, volume); PausePlaying(); ResumePlaying(); EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); // Ensure the volume has not changed after resuming playout. ExpectVolumeNear(200u, volume); PausePlaying(); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100)); ResumePlaying(); // Ensure the volume set while paused is retained. EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); ExpectVolumeNear(100u, volume); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume)); } TEST_F(VolumeTest, ManualSetVolumeWorks) { unsigned int original_volume = 0; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume)); Sleep(1000); TEST_LOG("Setting speaker volume to 0 out of 255.\n"); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(0)); unsigned int volume; EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); ExpectVolumeNear(0u, volume); Sleep(1000); TEST_LOG("Setting speaker volume to 100 out of 255.\n"); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100)); EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); ExpectVolumeNear(100u, volume); Sleep(1000); // Set the volume to 255 very briefly so we don't blast the poor user // listening to this. This is just to test the call succeeds. EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(255)); EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume)); ExpectVolumeNear(255u, volume); TEST_LOG("Setting speaker volume to the original %d out of 255.\n", original_volume); EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume)); Sleep(1000); } TEST_F(VolumeTest, DefaultMicrophoneVolumeIsAtMost255) { unsigned int volume = 1000; if (voe_volume_control_->GetMicVolume(volume) == 0) EXPECT_LE(volume, 255u); else EXPECT_EQ(1000u, volume); } TEST_F(VolumeTest, DISABLED_ON_LINUX( ManualRequiresMicrophoneCanSetMicrophoneVolumeWithAcgOff)) { SwitchToManualMicrophone(); EXPECT_EQ(0, voe_apm_->SetAgcStatus(false)); unsigned int original_volume = 0; EXPECT_EQ(0, voe_volume_control_->GetMicVolume(original_volume)); TEST_LOG("Setting microphone volume to 0.\n"); EXPECT_EQ(0, voe_volume_control_->SetMicVolume(channel_)); Sleep(1000); TEST_LOG("Setting microphone volume to 255.\n"); EXPECT_EQ(0, voe_volume_control_->SetMicVolume(255)); Sleep(1000); TEST_LOG("Setting microphone volume back to saved value.\n"); EXPECT_EQ(0, voe_volume_control_->SetMicVolume(original_volume)); Sleep(1000); } TEST_F(VolumeTest, ChannelScalingIsOneByDefault) { float scaling = -1.0f; EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling( channel_, scaling)); EXPECT_FLOAT_EQ(1.0f, scaling); } TEST_F(VolumeTest, ManualCanSetChannelScaling) { EXPECT_EQ(0, voe_volume_control_->SetChannelOutputVolumeScaling( channel_, 0.1f)); float scaling = 1.0f; EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling( channel_, scaling)); EXPECT_FLOAT_EQ(0.1f, scaling); TEST_LOG("Channel scaling set to 0.1: audio should be barely audible.\n"); Sleep(2000); } TEST_F(VolumeTest, InputMutingIsNotEnabledByDefault) { bool is_muted = true; EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted)); EXPECT_FALSE(is_muted); } TEST_F(VolumeTest, DISABLED_ON_LINUX(ManualInputMutingMutesMicrophone)) { SwitchToManualMicrophone(); // Enable muting. EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, true)); bool is_muted = false; EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted)); EXPECT_TRUE(is_muted); TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n"); Sleep(2000); // Test that we can disable muting. EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, false)); EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted)); EXPECT_FALSE(is_muted); TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n"); Sleep(2000); } TEST_F(VolumeTest, DISABLED_ON_LINUX(SystemInputMutingIsNotEnabledByDefault)) { bool is_muted = true; EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted)); EXPECT_FALSE(is_muted); } TEST_F(VolumeTest, DISABLED_ON_LINUX(ManualSystemInputMutingMutesMicrophone)) { SwitchToManualMicrophone(); // Enable system input muting. EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(true)); bool is_muted = false; EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted)); EXPECT_TRUE(is_muted); TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n"); Sleep(2000); // Test that we can disable system input muting. EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(false)); EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted)); EXPECT_FALSE(is_muted); TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n"); Sleep(2000); } TEST_F(VolumeTest, DISABLED_ON_LINUX(SystemOutputMutingIsNotEnabledByDefault)) { bool is_muted = true; EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted)); EXPECT_FALSE(is_muted); } TEST_F(VolumeTest, ManualSystemOutputMutingMutesOutput) { // Enable muting. EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(true)); bool is_muted = false; EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted)); EXPECT_TRUE(is_muted); TEST_LOG("Muted: you should hear no audio.\n"); Sleep(2000); // Test that we can disable muting. EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(false)); EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted)); EXPECT_FALSE(is_muted); TEST_LOG("Unmuted: you should hear audio.\n"); Sleep(2000); } TEST_F(VolumeTest, ManualTestInputAndOutputLevels) { SwitchToManualMicrophone(); TEST_LOG("Speak and verify that the following levels look right:\n"); for (int i = 0; i < 5; i++) { Sleep(1000); unsigned int input_level = 0; unsigned int output_level = 0; unsigned int input_level_full_range = 0; unsigned int output_level_full_range = 0; EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevel( input_level)); EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevel( channel_, output_level)); EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevelFullRange( input_level_full_range)); EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevelFullRange( channel_, output_level_full_range)); TEST_LOG(" warped levels (0-9) : in=%5d, out=%5d\n", input_level, output_level); TEST_LOG(" linear levels (0-32768): in=%5d, out=%5d\n", input_level_full_range, output_level_full_range); } } TEST_F(VolumeTest, ChannelsAreNotPannedByDefault) { float left = -1.0; float right = -1.0; EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right)); EXPECT_FLOAT_EQ(1.0, left); EXPECT_FLOAT_EQ(1.0, right); } TEST_F(VolumeTest, ManualTestChannelPanning) { TEST_LOG("Panning left.\n"); EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.8f, 0.1f)); Sleep(1000); TEST_LOG("Back to center.\n"); EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 1.0f, 1.0f)); Sleep(1000); TEST_LOG("Panning right.\n"); EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.1f, 0.8f)); Sleep(1000); // To finish, verify that the getter works. float left = 0.0f; float right = 0.0f; EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right)); EXPECT_FLOAT_EQ(0.1f, left); EXPECT_FLOAT_EQ(0.8f, right); } <|endoftext|>
<commit_before>#include "IO.hpp" #include <stdexcept> #include <fstream> #include <iostream> #include <boost/filesystem.hpp> #define TINYOBJLOADER_IMPLEMENTATION #include "tiny_obj_loader.h" namespace Slic3r { namespace IO { bool STL::read(std::string input_file, TriangleMesh* mesh) { // TODO: encode file name // TODO: check that file exists try { mesh->ReadSTLFile(input_file); mesh->check_topology(); } catch (...) { throw std::runtime_error("Error while reading STL file"); } return true; } bool STL::read(std::string input_file, Model* model) { TriangleMesh mesh; if (!STL::read(input_file, &mesh)) return false; if (mesh.facets_count() == 0) throw std::runtime_error("This STL file couldn't be read because it's empty."); ModelObject* object = model->add_object(); object->name = boost::filesystem::path(input_file).filename().string(); object->input_file = input_file; ModelVolume* volume = object->add_volume(mesh); volume->name = object->name; return true; } bool STL::write(Model& model, std::string output_file, bool binary) { TriangleMesh mesh = model.mesh(); return STL::write(mesh, output_file, binary); } bool STL::write(TriangleMesh& mesh, std::string output_file, bool binary) { if (binary) { mesh.write_binary(output_file); } else { mesh.write_ascii(output_file); } return true; } bool OBJ::read(std::string input_file, TriangleMesh* mesh) { Model model; OBJ::read(input_file, &model); *mesh = model.mesh(); return true; } bool OBJ::read(std::string input_file, Model* model) { // TODO: encode file name // TODO: check that file exists tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, input_file.c_str()); if (!err.empty()) { // `err` may contain warning message. std::cerr << err << std::endl; } if (!ret) throw std::runtime_error("Error while reading OBJ file"); ModelObject* object = model->add_object(); object->name = boost::filesystem::path(input_file).filename().string(); object->input_file = input_file; // Loop over shapes and add a volume for each one. for (std::vector<tinyobj::shape_t>::const_iterator shape = shapes.begin(); shape != shapes.end(); ++shape) { Pointf3s points; std::vector<Point3> facets; // Read vertices. assert((shape->mesh.vertices.size() % 3) == 0); for (size_t v = 0; v < attrib.vertices.size(); v += 3) { points.push_back(Pointf3( attrib.vertices[v], attrib.vertices[v+1], attrib.vertices[v+2] )); } // Loop over facets of the current shape. for (size_t f = 0; f < shape->mesh.num_face_vertices.size(); ++f) { // tiny_obj_loader should triangulate any facet with more than 3 vertices assert((shape->mesh.num_face_vertices[f] % 3) == 0); facets.push_back(Point3( shape->mesh.indices[f*3+0].vertex_index, shape->mesh.indices[f*3+1].vertex_index, shape->mesh.indices[f*3+2].vertex_index )); } TriangleMesh mesh(points, facets); mesh.check_topology(); ModelVolume* volume = object->add_volume(mesh); volume->name = object->name; } return true; } bool OBJ::write(Model& model, std::string output_file) { TriangleMesh mesh = model.mesh(); return OBJ::write(mesh, output_file); } bool OBJ::write(TriangleMesh& mesh, std::string output_file) { mesh.WriteOBJFile(output_file); return true; } bool POV::write(TriangleMesh& mesh, std::string output_file) { TriangleMesh mesh2 = mesh; mesh2.center_around_origin(); using namespace std; ofstream pov; pov.open(output_file.c_str(), ios::out | ios::trunc); for (int i = 0; i < mesh2.stl.stats.number_of_facets; ++i) { const stl_facet &f = mesh2.stl.facet_start[i]; pov << "triangle { "; pov << "<" << f.vertex[0].x << "," << f.vertex[0].y << "," << f.vertex[0].z << ">,"; pov << "<" << f.vertex[1].x << "," << f.vertex[1].y << "," << f.vertex[1].z << ">,"; pov << "<" << f.vertex[2].x << "," << f.vertex[2].y << "," << f.vertex[2].z << ">"; pov << " }" << endl; } pov.close(); return true; } } } <commit_msg>Fixed typo in assert<commit_after>#include "IO.hpp" #include <stdexcept> #include <fstream> #include <iostream> #include <boost/filesystem.hpp> #define TINYOBJLOADER_IMPLEMENTATION #include "tiny_obj_loader.h" namespace Slic3r { namespace IO { bool STL::read(std::string input_file, TriangleMesh* mesh) { // TODO: encode file name // TODO: check that file exists try { mesh->ReadSTLFile(input_file); mesh->check_topology(); } catch (...) { throw std::runtime_error("Error while reading STL file"); } return true; } bool STL::read(std::string input_file, Model* model) { TriangleMesh mesh; if (!STL::read(input_file, &mesh)) return false; if (mesh.facets_count() == 0) throw std::runtime_error("This STL file couldn't be read because it's empty."); ModelObject* object = model->add_object(); object->name = boost::filesystem::path(input_file).filename().string(); object->input_file = input_file; ModelVolume* volume = object->add_volume(mesh); volume->name = object->name; return true; } bool STL::write(Model& model, std::string output_file, bool binary) { TriangleMesh mesh = model.mesh(); return STL::write(mesh, output_file, binary); } bool STL::write(TriangleMesh& mesh, std::string output_file, bool binary) { if (binary) { mesh.write_binary(output_file); } else { mesh.write_ascii(output_file); } return true; } bool OBJ::read(std::string input_file, TriangleMesh* mesh) { Model model; OBJ::read(input_file, &model); *mesh = model.mesh(); return true; } bool OBJ::read(std::string input_file, Model* model) { // TODO: encode file name // TODO: check that file exists tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, input_file.c_str()); if (!err.empty()) { // `err` may contain warning message. std::cerr << err << std::endl; } if (!ret) throw std::runtime_error("Error while reading OBJ file"); ModelObject* object = model->add_object(); object->name = boost::filesystem::path(input_file).filename().string(); object->input_file = input_file; // Loop over shapes and add a volume for each one. for (std::vector<tinyobj::shape_t>::const_iterator shape = shapes.begin(); shape != shapes.end(); ++shape) { Pointf3s points; std::vector<Point3> facets; // Read vertices. assert((attrib.vertices.size() % 3) == 0); for (size_t v = 0; v < attrib.vertices.size(); v += 3) { points.push_back(Pointf3( attrib.vertices[v], attrib.vertices[v+1], attrib.vertices[v+2] )); } // Loop over facets of the current shape. for (size_t f = 0; f < shape->mesh.num_face_vertices.size(); ++f) { // tiny_obj_loader should triangulate any facet with more than 3 vertices assert((shape->mesh.num_face_vertices[f] % 3) == 0); facets.push_back(Point3( shape->mesh.indices[f*3+0].vertex_index, shape->mesh.indices[f*3+1].vertex_index, shape->mesh.indices[f*3+2].vertex_index )); } TriangleMesh mesh(points, facets); mesh.check_topology(); ModelVolume* volume = object->add_volume(mesh); volume->name = object->name; } return true; } bool OBJ::write(Model& model, std::string output_file) { TriangleMesh mesh = model.mesh(); return OBJ::write(mesh, output_file); } bool OBJ::write(TriangleMesh& mesh, std::string output_file) { mesh.WriteOBJFile(output_file); return true; } bool POV::write(TriangleMesh& mesh, std::string output_file) { TriangleMesh mesh2 = mesh; mesh2.center_around_origin(); using namespace std; ofstream pov; pov.open(output_file.c_str(), ios::out | ios::trunc); for (int i = 0; i < mesh2.stl.stats.number_of_facets; ++i) { const stl_facet &f = mesh2.stl.facet_start[i]; pov << "triangle { "; pov << "<" << f.vertex[0].x << "," << f.vertex[0].y << "," << f.vertex[0].z << ">,"; pov << "<" << f.vertex[1].x << "," << f.vertex[1].y << "," << f.vertex[1].z << ">,"; pov << "<" << f.vertex[2].x << "," << f.vertex[2].y << "," << f.vertex[2].z << ">"; pov << " }" << endl; } pov.close(); return true; } } } <|endoftext|>
<commit_before>// $Id$ /** \file csvtool.cc * File containing another example application: * A CSV Parser, Filter and Sorter using the Expression Parser * See the doxygen documentation for a short specification. */ // Enhanced CSV Parser and Filter using the Expression Parser #include "ExpressionParser.h" #include "strnatcmp.h" #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <boost/lexical_cast.hpp> // use this as the delimiter. this can be changed to ';' or ',' if needed const char delimiter = '\t'; // read one line from instream and split it into tab (or otherwise) delimited // columns. returns the number of columns read, 0 if eof. unsigned int read_csvline(std::istream &instream, std::vector<std::string> &columns) { columns.clear(); // read one line from the input stream std::string line; if (!std::getline(instream, line, '\n').good()) { return 0; } // parse line into tab separated columns, start with inital column columns.push_back(""); for (std::string::const_iterator si = line.begin(); si != line.end(); ++si) { if (*si == delimiter) columns.push_back(""); else // add non-delimiter to last column columns.back() += *si; } return columns.size(); } // subclass stx::BasicSymbolTable and return variable values from the current // csv row. the variable names are defined by the map containing the column // header. class CSVRowSymbolTable : public stx::BasicSymbolTable { public: // maps the column variable name to the vector index const std::map<std::string, unsigned int> &headersmap; // refernce to the reused data row vector. const std::vector<std::string> &datacolumns; CSVRowSymbolTable(const std::map<std::string, unsigned int> &_headersmap, const std::vector<std::string> &_datacolumns) : stx::BasicSymbolTable(), headersmap(_headersmap), datacolumns(_datacolumns) { } virtual stx::AnyScalar lookupVariable(const std::string &varname) const { // look if the variable name is defined by the CSV file std::map<std::string, unsigned int>::const_iterator varfind = headersmap.find(varname); if (varfind == headersmap.end()) { // if not, let BasicSymbolTable check if it knows it return stx::BasicSymbolTable::lookupVariable(varname); } // return the variable value from the current vector. it is // auto-converted into a stx::AnyScalar. if(varfind->second < datacolumns.size()) return datacolumns[ varfind->second ]; else return ""; // happens when a data row has too few delimited // fields. } }; // std::sort order relation functional object struct DataRecordSortRelation { // the column index to sort by unsigned int sortcol; // sort ascending or descending bool descending; inline DataRecordSortRelation(unsigned int _sortcol, bool _descending = 0) : sortcol(_sortcol), descending(_descending) { } // calls the strnatcasecmp on the given column's text or "" if the column // does not exist. sorts in "natural" sort order means numbers and text are // ordered correctly. inline bool operator()(const std::vector<std::string> &recordA, const std::vector<std::string> &recordB) const { if (!descending) { return strnatcasecmp(sortcol < recordA.size() ? recordA[sortcol].c_str() : "", sortcol < recordB.size() ? recordB[sortcol].c_str() : "") < 0; } else { return strnatcasecmp(sortcol < recordA.size() ? recordA[sortcol].c_str() : "", sortcol < recordB.size() ? recordB[sortcol].c_str() : "") > 0; } } }; // trim function from my weblog. static inline std::string string_trim(const std::string& str) { std::string::size_type pos1 = str.find_first_not_of(' '); if (pos1 == std::string::npos) return std::string(); std::string::size_type pos2 = str.find_last_not_of(' '); if (pos2 == std::string::npos) return std::string(); return str.substr(pos1 == std::string::npos ? 0 : pos1, pos2 == std::string::npos ? (str.length() - 1) : (pos2 - pos1 + 1)); } int main(int argc, char *argv[]) { // get progarm argment or reasonable defaults if (argc < 2) { std::cerr << "Usage: " << argv[0] << " <csv-filename> [filter expression] [sort-column] [offset] [limit]" << "\n"; return 0; } std::string csvfilename = argv[1]; std::string exprstring = (argc >= 3) ? string_trim(argv[2]) : ""; std::string sortcolumn = (argc >= 4) ? string_trim(argv[3]) : ""; std::string offsetstring = (argc >= 5) ? string_trim(argv[4]) : ""; std::string limitstring = (argc >= 6) ? string_trim(argv[5]) : ""; // parse expression into a parse tree stx::ParseTree pt; try { if (exprstring.size()) { pt = stx::parseExpression(exprstring); } } catch (stx::ExpressionParserException &e) { std::cerr << "ExpressionParserException: " << e.what() << "\n"; return 0; } // open the CSV file stream, either stdin or the given filename std::ifstream csvfilestream; if (csvfilename != "-") { csvfilestream.open(csvfilename.c_str()); if (!csvfilestream) { std::cerr << "Error opening CSV file " << csvfilename << "\n"; return 0; } } std::istream& csvfile = (csvfilename == "-") ? std::cin : csvfilestream; // read first line of CSV input as column headers std::vector<std::string> headers; if (read_csvline(csvfile, headers) == 0) { std::cerr << "Error read column headers: no input\n"; return 0; } // create a header column lookup map for CSVRowSymbolTable std::map<std::string, unsigned int> headersmap; for(unsigned int headnum = 0; headnum < headers.size(); ++headnum) { headersmap[ headers[headnum] ] = headnum; } // iterate over the data lines of the CSV input and save matching data rows // into "datarecords" unsigned int linesprocessed = 0; bool addedEvalResult = false; std::vector<std::string> datacolumns; // current row CSVRowSymbolTable csvsymboltable(headersmap, datacolumns); // huge table containing copied rows. std::vector< std::vector<std::string> > datarecords; while( read_csvline(csvfile, datacolumns) > 0 ) { // evaluate the expression for each row using the headers/datacolumns // as variables try { linesprocessed++; if (!pt.isEmpty()) { stx::AnyScalar val = pt.evaluate( csvsymboltable ); if (val.isBooleanType()) { if (!val.getBoolean()) continue; } else { // if calculation results in non-boolean value, then save // that value into a column "EvalResult" if (!addedEvalResult) { headers.push_back("EvalResult"); addedEvalResult = true; } while( datacolumns.size() + 1 < headers.size() ) datacolumns.push_back(""); datacolumns.push_back(val.getString()); } } } catch (stx::ExpressionParserException &e) { // save exception text into column "EvalResult" if (!addedEvalResult) { headers.push_back("EvalResult"); addedEvalResult = true; } // add calculation result as last column while( datacolumns.size() + 1 < headers.size() ) datacolumns.push_back(""); datacolumns.push_back(std::string("Exception: ") + e.what()); } datarecords.push_back( datacolumns ); } // add "EvalResult" to headers map to allow sorting by it. if (addedEvalResult) { headersmap[ headers[headers.size() - 1] ] = headers.size() - 1; } // sort the result table if required. if (sortcolumn.size()) { std::map<std::string, unsigned int>::const_iterator colfind = headersmap.find(sortcolumn); if (colfind != headersmap.end()) { // sort ascending std::sort(datarecords.begin(), datarecords.end(), DataRecordSortRelation(colfind->second)); } else { // the the sort column is !header it is sorted descending. if (sortcolumn[0] == '!') { sortcolumn.erase(0, 1); colfind = headersmap.find(sortcolumn); if (colfind != headersmap.end()) { std::sort(datarecords.begin(), datarecords.end(), DataRecordSortRelation(colfind->second, 1)); } else { std::cerr << "Bad sort column: " << sortcolumn << " could not be found.\n"; return 0; } } else { std::cerr << "Bad sort column: " << sortcolumn << " could not be found.\n"; return 0; } } } // determine offset and limit of the outputted data rows. unsigned int offset = 0; unsigned int limit = datarecords.size(); if (offsetstring.size()) { try { offset = boost::lexical_cast<unsigned int>(offsetstring); } catch (boost::bad_lexical_cast &e) { std::cerr << "Bad number in offset: not an integer.\n"; return 0; } } if (limitstring.size()) { try { limit = boost::lexical_cast<unsigned int>(limitstring); } catch (boost::bad_lexical_cast &e) { std::cerr << "Bad number in limit: not an integer.\n"; return 0; } } // write a processing summary to stderr std::cerr << "Processed " << linesprocessed << " lines, " << "copied " << datarecords.size() << " and " << "skipped " << (linesprocessed - datarecords.size()) << " lines" << "\n"; // write column headers to stdout for(std::vector<std::string>::const_iterator coliter = headers.begin(); coliter != headers.end(); ++coliter) { if (coliter != headers.begin()) std::cout << delimiter; std::cout << *coliter; } std::cout << "\n"; // output data rows from "offset" to "offset+limit" unsigned int current = 0; for(std::vector< std::vector<std::string> >::const_iterator recorditer = datarecords.begin(); recorditer != datarecords.end(); ++recorditer, ++current) { if (current < offset || current >= offset + limit) continue; // output this data row to std::cout for(std::vector<std::string>::const_iterator coliter = recorditer->begin(); coliter != recorditer->end(); ++coliter) { if (coliter != recorditer->begin()) std::cout << delimiter; std::cout << *coliter; } std::cout << "\n"; } } <commit_msg>Faster region output in csvtool<commit_after>// $Id$ /** \file csvtool.cc * File containing another example application: * A CSV Parser, Filter and Sorter using the Expression Parser * See the doxygen documentation for a short specification. */ // Enhanced CSV Parser and Filter using the Expression Parser #include "ExpressionParser.h" #include "strnatcmp.h" #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <boost/lexical_cast.hpp> // use this as the delimiter. this can be changed to ';' or ',' if needed const char delimiter = '\t'; // read one line from instream and split it into tab (or otherwise) delimited // columns. returns the number of columns read, 0 if eof. unsigned int read_csvline(std::istream &instream, std::vector<std::string> &columns) { columns.clear(); // read one line from the input stream std::string line; if (!std::getline(instream, line, '\n').good()) { return 0; } // parse line into tab separated columns, start with inital column columns.push_back(""); for (std::string::const_iterator si = line.begin(); si != line.end(); ++si) { if (*si == delimiter) columns.push_back(""); else // add non-delimiter to last column columns.back() += *si; } return columns.size(); } // subclass stx::BasicSymbolTable and return variable values from the current // csv row. the variable names are defined by the map containing the column // header. class CSVRowSymbolTable : public stx::BasicSymbolTable { public: // maps the column variable name to the vector index const std::map<std::string, unsigned int> &headersmap; // refernce to the reused data row vector. const std::vector<std::string> &datacolumns; CSVRowSymbolTable(const std::map<std::string, unsigned int> &_headersmap, const std::vector<std::string> &_datacolumns) : stx::BasicSymbolTable(), headersmap(_headersmap), datacolumns(_datacolumns) { } virtual stx::AnyScalar lookupVariable(const std::string &varname) const { // look if the variable name is defined by the CSV file std::map<std::string, unsigned int>::const_iterator varfind = headersmap.find(varname); if (varfind == headersmap.end()) { // if not, let BasicSymbolTable check if it knows it return stx::BasicSymbolTable::lookupVariable(varname); } // return the variable value from the current vector. it is // auto-converted into a stx::AnyScalar. if(varfind->second < datacolumns.size()) return datacolumns[ varfind->second ]; else return ""; // happens when a data row has too few delimited // fields. } }; // std::sort order relation functional object struct DataRecordSortRelation { // the column index to sort by unsigned int sortcol; // sort ascending or descending bool descending; inline DataRecordSortRelation(unsigned int _sortcol, bool _descending = 0) : sortcol(_sortcol), descending(_descending) { } // calls the strnatcasecmp on the given column's text or "" if the column // does not exist. sorts in "natural" sort order means numbers and text are // ordered correctly. inline bool operator()(const std::vector<std::string> &recordA, const std::vector<std::string> &recordB) const { if (!descending) { return strnatcasecmp(sortcol < recordA.size() ? recordA[sortcol].c_str() : "", sortcol < recordB.size() ? recordB[sortcol].c_str() : "") < 0; } else { return strnatcasecmp(sortcol < recordA.size() ? recordA[sortcol].c_str() : "", sortcol < recordB.size() ? recordB[sortcol].c_str() : "") > 0; } } }; // trim function from my weblog. static inline std::string string_trim(const std::string& str) { std::string::size_type pos1 = str.find_first_not_of(' '); if (pos1 == std::string::npos) return std::string(); std::string::size_type pos2 = str.find_last_not_of(' '); if (pos2 == std::string::npos) return std::string(); return str.substr(pos1 == std::string::npos ? 0 : pos1, pos2 == std::string::npos ? (str.length() - 1) : (pos2 - pos1 + 1)); } int main(int argc, char *argv[]) { // get progarm argment or reasonable defaults if (argc < 2) { std::cerr << "Usage: " << argv[0] << " <csv-filename> [filter expression] [sort-column] [offset] [limit]" << "\n"; return 0; } std::string csvfilename = argv[1]; std::string exprstring = (argc >= 3) ? string_trim(argv[2]) : ""; std::string sortcolumn = (argc >= 4) ? string_trim(argv[3]) : ""; std::string offsetstring = (argc >= 5) ? string_trim(argv[4]) : ""; std::string limitstring = (argc >= 6) ? string_trim(argv[5]) : ""; // parse expression into a parse tree stx::ParseTree pt; try { if (exprstring.size()) { pt = stx::parseExpression(exprstring); } } catch (stx::ExpressionParserException &e) { std::cerr << "ExpressionParserException: " << e.what() << "\n"; return 0; } // open the CSV file stream, either stdin or the given filename std::ifstream csvfilestream; if (csvfilename != "-") { csvfilestream.open(csvfilename.c_str()); if (!csvfilestream) { std::cerr << "Error opening CSV file " << csvfilename << "\n"; return 0; } } std::istream& csvfile = (csvfilename == "-") ? std::cin : csvfilestream; // read first line of CSV input as column headers std::vector<std::string> headers; if (read_csvline(csvfile, headers) == 0) { std::cerr << "Error read column headers: no input\n"; return 0; } // create a header column lookup map for CSVRowSymbolTable std::map<std::string, unsigned int> headersmap; for(unsigned int headnum = 0; headnum < headers.size(); ++headnum) { headersmap[ headers[headnum] ] = headnum; } // iterate over the data lines of the CSV input and save matching data rows // into "datarecords" unsigned int linesprocessed = 0; bool addedEvalResult = false; std::vector<std::string> datacolumns; // current row CSVRowSymbolTable csvsymboltable(headersmap, datacolumns); // huge table containing copied rows. std::vector< std::vector<std::string> > datarecords; while( read_csvline(csvfile, datacolumns) > 0 ) { // evaluate the expression for each row using the headers/datacolumns // as variables try { linesprocessed++; if (!pt.isEmpty()) { stx::AnyScalar val = pt.evaluate( csvsymboltable ); if (val.isBooleanType()) { if (!val.getBoolean()) continue; } else { // if calculation results in non-boolean value, then save // that value into a column "EvalResult" if (!addedEvalResult) { headers.push_back("EvalResult"); addedEvalResult = true; } while( datacolumns.size() + 1 < headers.size() ) datacolumns.push_back(""); datacolumns.push_back(val.getString()); } } } catch (stx::ExpressionParserException &e) { // save exception text into column "EvalResult" if (!addedEvalResult) { headers.push_back("EvalResult"); addedEvalResult = true; } // add calculation result as last column while( datacolumns.size() + 1 < headers.size() ) datacolumns.push_back(""); datacolumns.push_back(std::string("Exception: ") + e.what()); } datarecords.push_back( datacolumns ); } // add "EvalResult" to headers map to allow sorting by it. if (addedEvalResult) { headersmap[ headers[headers.size() - 1] ] = headers.size() - 1; } // sort the result table if required. if (sortcolumn.size()) { std::map<std::string, unsigned int>::const_iterator colfind = headersmap.find(sortcolumn); if (colfind != headersmap.end()) { // sort ascending std::sort(datarecords.begin(), datarecords.end(), DataRecordSortRelation(colfind->second)); } else { // the the sort column is !header it is sorted descending. if (sortcolumn[0] == '!') { sortcolumn.erase(0, 1); colfind = headersmap.find(sortcolumn); if (colfind != headersmap.end()) { std::sort(datarecords.begin(), datarecords.end(), DataRecordSortRelation(colfind->second, 1)); } else { std::cerr << "Bad sort column: " << sortcolumn << " could not be found.\n"; return 0; } } else { std::cerr << "Bad sort column: " << sortcolumn << " could not be found.\n"; return 0; } } } // determine offset and limit of the outputted data rows. unsigned int offset = 0; unsigned int limit = datarecords.size(); if (offsetstring.size()) { try { offset = boost::lexical_cast<unsigned int>(offsetstring); } catch (boost::bad_lexical_cast &e) { std::cerr << "Bad number in offset: not an integer.\n"; return 0; } } if (limitstring.size()) { try { limit = boost::lexical_cast<unsigned int>(limitstring); } catch (boost::bad_lexical_cast &e) { std::cerr << "Bad number in limit: not an integer.\n"; return 0; } } // write a processing summary to stderr std::cerr << "Processed " << linesprocessed << " lines, " << "copied " << datarecords.size() << " and " << "skipped " << (linesprocessed - datarecords.size()) << " lines" << "\n"; // write column headers to stdout for(std::vector<std::string>::const_iterator coliter = headers.begin(); coliter != headers.end(); ++coliter) { if (coliter != headers.begin()) std::cout << delimiter; std::cout << *coliter; } std::cout << "\n"; // output data rows from "offset" to "offset+limit" for(unsigned int current = offset; current < offset + limit && current < datarecords.size(); ++current) { std::vector<std::string> &currrecord = datarecords[current]; // output this data row to std::cout for(std::vector<std::string>::const_iterator coliter = currrecord.begin(); coliter != currrecord.end(); ++coliter) { if (coliter != currrecord.begin()) std::cout << delimiter; std::cout << *coliter; } std::cout << "\n"; } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/dom_ui/dom_ui_browsertest.h" #include "chrome/browser/dom_ui/options/core_options_handler.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" #include "googleurl/src/gurl.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::StrictMock; using ::testing::_; MATCHER_P(Eq_ListValue, inList, "") { return arg->Equals(inList); } class MockCoreOptionsHandler : public CoreOptionsHandler { public: MOCK_METHOD1(HandleInitialize, void(const ListValue* args)); MOCK_METHOD1(HandleFetchPrefs, void(const ListValue* args)); MOCK_METHOD1(HandleObservePrefs, void(const ListValue* args)); MOCK_METHOD1(HandleSetBooleanPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetIntegerPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetDoublePref, void(const ListValue* args)); MOCK_METHOD1(HandleSetStringPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetObjectPref, void(const ListValue* args)); MOCK_METHOD1(HandleClearPref, void(const ListValue* args)); MOCK_METHOD1(HandleUserMetricsAction, void(const ListValue* args)); virtual void RegisterMessages() { dom_ui_->RegisterMessageCallback("coreOptionsInitialize", NewCallback(this, &MockCoreOptionsHandler ::HandleInitialize)); dom_ui_->RegisterMessageCallback("fetchPrefs", NewCallback(this, &MockCoreOptionsHandler ::HandleFetchPrefs)); dom_ui_->RegisterMessageCallback("observePrefs", NewCallback(this, &MockCoreOptionsHandler ::HandleObservePrefs)); dom_ui_->RegisterMessageCallback("setBooleanPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetBooleanPref)); dom_ui_->RegisterMessageCallback("setIntegerPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetIntegerPref)); dom_ui_->RegisterMessageCallback("setDoublePref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetDoublePref)); dom_ui_->RegisterMessageCallback("setStringPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetStringPref)); dom_ui_->RegisterMessageCallback("setObjectPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetObjectPref)); dom_ui_->RegisterMessageCallback("clearPref", NewCallback(this, &MockCoreOptionsHandler ::HandleClearPref)); dom_ui_->RegisterMessageCallback("coreOptionsUserMetricsAction", NewCallback(this, &MockCoreOptionsHandler ::HandleUserMetricsAction)); } }; class SettingsDOMUITest : public DOMUITest { protected: virtual DOMMessageHandler* GetMockMessageHandler() { return &mock_core_options_handler_; } StrictMock<MockCoreOptionsHandler> mock_core_options_handler_; }; // Test the end to end js to DOMUI handler code path for // the message setBooleanPref. // TODO(dtseng): add more EXPECT_CALL's when updating js test. IN_PROC_BROWSER_TEST_F(SettingsDOMUITest, TestSetBooleanPrefTriggers) { // This serves as an example of a very constrained test. ListValue true_list_value; true_list_value.Append(Value::CreateStringValue("browser.show_home_button")); true_list_value.Append(Value::CreateStringValue("true")); true_list_value.Append( Value::CreateStringValue("Options_Homepage_HomeButton")); ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUISettingsURL)); EXPECT_CALL(mock_core_options_handler_, HandleSetBooleanPref(Eq_ListValue(&true_list_value))); ASSERT_TRUE(RunDOMUITest( FILE_PATH_LITERAL("settings_set_boolean_pref_triggers.js"))); }<commit_msg>Fix build error from r73532. Added new line. TBR=dtseng<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/dom_ui/dom_ui_browsertest.h" #include "chrome/browser/dom_ui/options/core_options_handler.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" #include "googleurl/src/gurl.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::StrictMock; using ::testing::_; MATCHER_P(Eq_ListValue, inList, "") { return arg->Equals(inList); } class MockCoreOptionsHandler : public CoreOptionsHandler { public: MOCK_METHOD1(HandleInitialize, void(const ListValue* args)); MOCK_METHOD1(HandleFetchPrefs, void(const ListValue* args)); MOCK_METHOD1(HandleObservePrefs, void(const ListValue* args)); MOCK_METHOD1(HandleSetBooleanPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetIntegerPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetDoublePref, void(const ListValue* args)); MOCK_METHOD1(HandleSetStringPref, void(const ListValue* args)); MOCK_METHOD1(HandleSetObjectPref, void(const ListValue* args)); MOCK_METHOD1(HandleClearPref, void(const ListValue* args)); MOCK_METHOD1(HandleUserMetricsAction, void(const ListValue* args)); virtual void RegisterMessages() { dom_ui_->RegisterMessageCallback("coreOptionsInitialize", NewCallback(this, &MockCoreOptionsHandler ::HandleInitialize)); dom_ui_->RegisterMessageCallback("fetchPrefs", NewCallback(this, &MockCoreOptionsHandler ::HandleFetchPrefs)); dom_ui_->RegisterMessageCallback("observePrefs", NewCallback(this, &MockCoreOptionsHandler ::HandleObservePrefs)); dom_ui_->RegisterMessageCallback("setBooleanPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetBooleanPref)); dom_ui_->RegisterMessageCallback("setIntegerPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetIntegerPref)); dom_ui_->RegisterMessageCallback("setDoublePref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetDoublePref)); dom_ui_->RegisterMessageCallback("setStringPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetStringPref)); dom_ui_->RegisterMessageCallback("setObjectPref", NewCallback(this, &MockCoreOptionsHandler ::HandleSetObjectPref)); dom_ui_->RegisterMessageCallback("clearPref", NewCallback(this, &MockCoreOptionsHandler ::HandleClearPref)); dom_ui_->RegisterMessageCallback("coreOptionsUserMetricsAction", NewCallback(this, &MockCoreOptionsHandler ::HandleUserMetricsAction)); } }; class SettingsDOMUITest : public DOMUITest { protected: virtual DOMMessageHandler* GetMockMessageHandler() { return &mock_core_options_handler_; } StrictMock<MockCoreOptionsHandler> mock_core_options_handler_; }; // Test the end to end js to DOMUI handler code path for // the message setBooleanPref. // TODO(dtseng): add more EXPECT_CALL's when updating js test. IN_PROC_BROWSER_TEST_F(SettingsDOMUITest, TestSetBooleanPrefTriggers) { // This serves as an example of a very constrained test. ListValue true_list_value; true_list_value.Append(Value::CreateStringValue("browser.show_home_button")); true_list_value.Append(Value::CreateStringValue("true")); true_list_value.Append( Value::CreateStringValue("Options_Homepage_HomeButton")); ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUISettingsURL)); EXPECT_CALL(mock_core_options_handler_, HandleSetBooleanPref(Eq_ListValue(&true_list_value))); ASSERT_TRUE(RunDOMUITest( FILE_PATH_LITERAL("settings_set_boolean_pref_triggers.js"))); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/google_apis/operations_base.h" #include "base/json/json_reader.h" #include "base/metrics/histogram.h" #include "base/string_number_conversions.h" #include "base/stringprintf.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/common/net/url_util.h" #include "content/public/browser/browser_thread.h" #include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/google_service_auth_error.h" #include "google_apis/gaia/oauth2_access_token_fetcher.h" #include "net/base/load_flags.h" #include "net/http/http_util.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_request_status.h" using content::BrowserThread; using net::URLFetcher; namespace { // Used for success ratio histograms. 0 for failure, 1 for success, // 2 for no connection (likely offline). const int kSuccessRatioHistogramFailure = 0; const int kSuccessRatioHistogramSuccess = 1; const int kSuccessRatioHistogramNoConnection = 2; const int kSuccessRatioHistogramMaxValue = 3; // The max value is exclusive. // Template for optional OAuth2 authorization HTTP header. const char kAuthorizationHeaderFormat[] = "Authorization: Bearer %s"; // Template for GData API version HTTP header. const char kGDataVersionHeader[] = "GData-Version: 3.0"; // Maximum number of attempts for re-authentication per operation. const int kMaxReAuthenticateAttemptsPerOperation = 1; // Parse JSON string to base::Value object. void ParseJsonOnBlockingPool(const std::string& data, scoped_ptr<base::Value>* value) { DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI)); int error_code = -1; std::string error_message; value->reset(base::JSONReader::ReadAndReturnError(data, base::JSON_PARSE_RFC, &error_code, &error_message)); if (!value->get()) { LOG(ERROR) << "Error while parsing entry response: " << error_message << ", code: " << error_code << ", data:\n" << data; } } } // namespace namespace gdata { //================================ AuthOperation =============================== AuthOperation::AuthOperation(OperationRegistry* registry, const AuthStatusCallback& callback, const std::vector<std::string>& scopes, const std::string& refresh_token) : OperationRegistry::Operation(registry), refresh_token_(refresh_token), callback_(callback), scopes_(scopes) { } AuthOperation::~AuthOperation() {} void AuthOperation::Start() { DCHECK(!refresh_token_.empty()); oauth2_access_token_fetcher_.reset(new OAuth2AccessTokenFetcher( this, g_browser_process->system_request_context())); NotifyStart(); oauth2_access_token_fetcher_->Start( GaiaUrls::GetInstance()->oauth2_chrome_client_id(), GaiaUrls::GetInstance()->oauth2_chrome_client_secret(), refresh_token_, scopes_); } void AuthOperation::DoCancel() { oauth2_access_token_fetcher_->CancelRequest(); if (!callback_.is_null()) callback_.Run(GDATA_CANCELLED, std::string()); } // Callback for OAuth2AccessTokenFetcher on success. |access_token| is the token // used to start fetching user data. void AuthOperation::OnGetTokenSuccess(const std::string& access_token, const base::Time& expiration_time) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); UMA_HISTOGRAM_ENUMERATION("GData.AuthSuccess", kSuccessRatioHistogramSuccess, kSuccessRatioHistogramMaxValue); callback_.Run(HTTP_SUCCESS, access_token); NotifyFinish(OPERATION_COMPLETED); } // Callback for OAuth2AccessTokenFetcher on failure. void AuthOperation::OnGetTokenFailure(const GoogleServiceAuthError& error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); LOG(WARNING) << "AuthOperation: token request using refresh token failed" << error.ToString(); // There are many ways to fail, but if the failure is due to connection, // it's likely that the device is off-line. We treat the error differently // so that the file manager works while off-line. if (error.state() == GoogleServiceAuthError::CONNECTION_FAILED) { UMA_HISTOGRAM_ENUMERATION("GData.AuthSuccess", kSuccessRatioHistogramNoConnection, kSuccessRatioHistogramMaxValue); callback_.Run(GDATA_NO_CONNECTION, std::string()); } else { UMA_HISTOGRAM_ENUMERATION("GData.AuthSuccess", kSuccessRatioHistogramFailure, kSuccessRatioHistogramMaxValue); callback_.Run(HTTP_UNAUTHORIZED, std::string()); } NotifyFinish(OPERATION_FAILED); } //============================ UrlFetchOperationBase =========================== UrlFetchOperationBase::UrlFetchOperationBase(OperationRegistry* registry) : OperationRegistry::Operation(registry), re_authenticate_count_(0), save_temp_file_(false), started_(false) { } UrlFetchOperationBase::UrlFetchOperationBase(OperationRegistry* registry, OperationType type, const FilePath& path) : OperationRegistry::Operation(registry, type, path), re_authenticate_count_(0), save_temp_file_(false) { } UrlFetchOperationBase::~UrlFetchOperationBase() {} void UrlFetchOperationBase::Start(const std::string& auth_token) { DCHECK(!auth_token.empty()); GURL url = GetURL(); DCHECK(!url.is_empty()); DVLOG(1) << "URL: " << url.spec(); url_fetcher_.reset( URLFetcher::Create(url, GetRequestType(), this)); url_fetcher_->SetRequestContext(g_browser_process->system_request_context()); // Always set flags to neither send nor save cookies. url_fetcher_->SetLoadFlags( net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DISABLE_CACHE); if (save_temp_file_) { url_fetcher_->SaveResponseToTemporaryFile( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)); } else if (!output_file_path_.empty()) { url_fetcher_->SaveResponseToFileAtPath(output_file_path_, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)); } // Add request headers. // Note that SetExtraRequestHeaders clears the current headers and sets it // to the passed-in headers, so calling it for each header will result in // only the last header being set in request headers. url_fetcher_->AddExtraRequestHeader(kGDataVersionHeader); url_fetcher_->AddExtraRequestHeader( base::StringPrintf(kAuthorizationHeaderFormat, auth_token.data())); std::vector<std::string> headers = GetExtraRequestHeaders(); for (size_t i = 0; i < headers.size(); ++i) { url_fetcher_->AddExtraRequestHeader(headers[i]); DVLOG(1) << "Extra header: " << headers[i]; } // Set upload data if available. std::string upload_content_type; std::string upload_content; if (GetContentData(&upload_content_type, &upload_content)) { url_fetcher_->SetUploadData(upload_content_type, upload_content); } // Register to operation registry. NotifyStartToOperationRegistry(); url_fetcher_->Start(); started_ = true; } void UrlFetchOperationBase::SetReAuthenticateCallback( const ReAuthenticateCallback& callback) { DCHECK(re_authenticate_callback_.is_null()); re_authenticate_callback_ = callback; } URLFetcher::RequestType UrlFetchOperationBase::GetRequestType() const { return URLFetcher::GET; } std::vector<std::string> UrlFetchOperationBase::GetExtraRequestHeaders() const { return std::vector<std::string>(); } bool UrlFetchOperationBase::GetContentData(std::string* upload_content_type, std::string* upload_content) { return false; } void UrlFetchOperationBase::DoCancel() { url_fetcher_.reset(NULL); RunCallbackOnPrematureFailure(GDATA_CANCELLED); } GDataErrorCode UrlFetchOperationBase::GetErrorCode( const URLFetcher* source) const { GDataErrorCode code = static_cast<GDataErrorCode>(source->GetResponseCode()); if (code == HTTP_SUCCESS && !source->GetStatus().is_success()) { // If the HTTP response code is SUCCESS yet the URL request failed, it is // likely that the failure is due to loss of connection. code = GDATA_NO_CONNECTION; } return code; } void UrlFetchOperationBase::OnProcessURLFetchResultsComplete(bool result) { if (result) NotifySuccessToOperationRegistry(); else NotifyFinish(OPERATION_FAILED); } void UrlFetchOperationBase::OnURLFetchComplete(const URLFetcher* source) { GDataErrorCode code = GetErrorCode(source); DVLOG(1) << "Response headers:\n" << GetResponseHeadersAsString(source); if (code == HTTP_UNAUTHORIZED) { if (!re_authenticate_callback_.is_null() && ++re_authenticate_count_ <= kMaxReAuthenticateAttemptsPerOperation) { re_authenticate_callback_.Run(this); return; } OnAuthFailed(code); return; } // Overridden by each specialization ProcessURLFetchResults(source); } void UrlFetchOperationBase::NotifySuccessToOperationRegistry() { NotifyFinish(OPERATION_COMPLETED); } void UrlFetchOperationBase::NotifyStartToOperationRegistry() { NotifyStart(); } void UrlFetchOperationBase::OnAuthFailed(GDataErrorCode code) { RunCallbackOnPrematureFailure(code); // Notify authentication failed. NotifyAuthFailed(); // Check if this failed before we even started fetching. If so, register // for start so we can properly unregister with finish. if (!started_) NotifyStart(); // Note: NotifyFinish() must be invoked at the end, after all other callbacks // and notifications. Once NotifyFinish() is called, the current instance of // gdata operation will be deleted from the OperationRegistry and become // invalid. NotifyFinish(OPERATION_FAILED); } std::string UrlFetchOperationBase::GetResponseHeadersAsString( const URLFetcher* url_fetcher) { // net::HttpResponseHeaders::raw_headers(), as the name implies, stores // all headers in their raw format, i.e each header is null-terminated. // So logging raw_headers() only shows the first header, which is probably // the status line. GetNormalizedHeaders, on the other hand, will show all // the headers, one per line, which is probably what we want. std::string headers; // Check that response code indicates response headers are valid (i.e. not // malformed) before we retrieve the headers. if (url_fetcher->GetResponseCode() == URLFetcher::RESPONSE_CODE_INVALID) { headers.assign("Response headers are malformed!!"); } else { url_fetcher->GetResponseHeaders()->GetNormalizedHeaders(&headers); } return headers; } //============================ EntryActionOperation ============================ EntryActionOperation::EntryActionOperation(OperationRegistry* registry, const EntryActionCallback& callback, const GURL& document_url) : UrlFetchOperationBase(registry), callback_(callback), document_url_(document_url) { } EntryActionOperation::~EntryActionOperation() {} void EntryActionOperation::ProcessURLFetchResults(const URLFetcher* source) { if (!callback_.is_null()) { GDataErrorCode code = GetErrorCode(source); callback_.Run(code, document_url_); } const bool success = true; OnProcessURLFetchResultsComplete(success); } void EntryActionOperation::RunCallbackOnPrematureFailure(GDataErrorCode code) { if (!callback_.is_null()) callback_.Run(code, document_url_); } //============================== GetDataOperation ============================== GetDataOperation::GetDataOperation(OperationRegistry* registry, const GetDataCallback& callback) : UrlFetchOperationBase(registry), callback_(callback), ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) { } GetDataOperation::~GetDataOperation() {} void GetDataOperation::ProcessURLFetchResults(const URLFetcher* source) { std::string data; source->GetResponseAsString(&data); scoped_ptr<base::Value> root_value; GDataErrorCode fetch_error_code = GetErrorCode(source); switch (fetch_error_code) { case HTTP_SUCCESS: case HTTP_CREATED: ParseResponse(fetch_error_code, data); break; default: RunCallback(fetch_error_code, scoped_ptr<base::Value>()); const bool success = false; OnProcessURLFetchResultsComplete(success); break; } } void GetDataOperation::RunCallbackOnPrematureFailure( GDataErrorCode fetch_error_code) { if (!callback_.is_null()) { scoped_ptr<base::Value> root_value; callback_.Run(fetch_error_code, root_value.Pass()); } } void GetDataOperation::ParseResponse(GDataErrorCode fetch_error_code, const std::string& data) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // Uses this hack to avoid deep-copy of json object because json might be so // big. This pointer of scped_ptr is to ensure a deletion of the parsed json // value object. scoped_ptr<base::Value>* parsed_value = new scoped_ptr<base::Value>(); BrowserThread::PostBlockingPoolTaskAndReply( FROM_HERE, base::Bind(&ParseJsonOnBlockingPool, data, parsed_value), base::Bind(&GetDataOperation::OnDataParsed, weak_ptr_factory_.GetWeakPtr(), fetch_error_code, base::Owned(parsed_value))); } void GetDataOperation::OnDataParsed( gdata::GDataErrorCode fetch_error_code, scoped_ptr<base::Value>* value) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); bool success = true; if (!value->get()) { fetch_error_code = gdata::GDATA_PARSE_ERROR; success = false; } // The ownership of the parsed json object is transfered to RunCallBack(), // keeping the ownership of the |value| here. RunCallback(fetch_error_code, value->Pass()); DCHECK(!value->get()); OnProcessURLFetchResultsComplete(success); // |value| will be deleted after return because it is base::Owned()'d. } void GetDataOperation::RunCallback(GDataErrorCode fetch_error_code, scoped_ptr<base::Value> value) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!callback_.is_null()) callback_.Run(fetch_error_code, value.Pass()); } } // namespace gdata <commit_msg>[Coverity] Fix uninitialized member in ctor<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/google_apis/operations_base.h" #include "base/json/json_reader.h" #include "base/metrics/histogram.h" #include "base/string_number_conversions.h" #include "base/stringprintf.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/common/net/url_util.h" #include "content/public/browser/browser_thread.h" #include "google_apis/gaia/gaia_urls.h" #include "google_apis/gaia/google_service_auth_error.h" #include "google_apis/gaia/oauth2_access_token_fetcher.h" #include "net/base/load_flags.h" #include "net/http/http_util.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_request_status.h" using content::BrowserThread; using net::URLFetcher; namespace { // Used for success ratio histograms. 0 for failure, 1 for success, // 2 for no connection (likely offline). const int kSuccessRatioHistogramFailure = 0; const int kSuccessRatioHistogramSuccess = 1; const int kSuccessRatioHistogramNoConnection = 2; const int kSuccessRatioHistogramMaxValue = 3; // The max value is exclusive. // Template for optional OAuth2 authorization HTTP header. const char kAuthorizationHeaderFormat[] = "Authorization: Bearer %s"; // Template for GData API version HTTP header. const char kGDataVersionHeader[] = "GData-Version: 3.0"; // Maximum number of attempts for re-authentication per operation. const int kMaxReAuthenticateAttemptsPerOperation = 1; // Parse JSON string to base::Value object. void ParseJsonOnBlockingPool(const std::string& data, scoped_ptr<base::Value>* value) { DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI)); int error_code = -1; std::string error_message; value->reset(base::JSONReader::ReadAndReturnError(data, base::JSON_PARSE_RFC, &error_code, &error_message)); if (!value->get()) { LOG(ERROR) << "Error while parsing entry response: " << error_message << ", code: " << error_code << ", data:\n" << data; } } } // namespace namespace gdata { //================================ AuthOperation =============================== AuthOperation::AuthOperation(OperationRegistry* registry, const AuthStatusCallback& callback, const std::vector<std::string>& scopes, const std::string& refresh_token) : OperationRegistry::Operation(registry), refresh_token_(refresh_token), callback_(callback), scopes_(scopes) { } AuthOperation::~AuthOperation() {} void AuthOperation::Start() { DCHECK(!refresh_token_.empty()); oauth2_access_token_fetcher_.reset(new OAuth2AccessTokenFetcher( this, g_browser_process->system_request_context())); NotifyStart(); oauth2_access_token_fetcher_->Start( GaiaUrls::GetInstance()->oauth2_chrome_client_id(), GaiaUrls::GetInstance()->oauth2_chrome_client_secret(), refresh_token_, scopes_); } void AuthOperation::DoCancel() { oauth2_access_token_fetcher_->CancelRequest(); if (!callback_.is_null()) callback_.Run(GDATA_CANCELLED, std::string()); } // Callback for OAuth2AccessTokenFetcher on success. |access_token| is the token // used to start fetching user data. void AuthOperation::OnGetTokenSuccess(const std::string& access_token, const base::Time& expiration_time) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); UMA_HISTOGRAM_ENUMERATION("GData.AuthSuccess", kSuccessRatioHistogramSuccess, kSuccessRatioHistogramMaxValue); callback_.Run(HTTP_SUCCESS, access_token); NotifyFinish(OPERATION_COMPLETED); } // Callback for OAuth2AccessTokenFetcher on failure. void AuthOperation::OnGetTokenFailure(const GoogleServiceAuthError& error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); LOG(WARNING) << "AuthOperation: token request using refresh token failed" << error.ToString(); // There are many ways to fail, but if the failure is due to connection, // it's likely that the device is off-line. We treat the error differently // so that the file manager works while off-line. if (error.state() == GoogleServiceAuthError::CONNECTION_FAILED) { UMA_HISTOGRAM_ENUMERATION("GData.AuthSuccess", kSuccessRatioHistogramNoConnection, kSuccessRatioHistogramMaxValue); callback_.Run(GDATA_NO_CONNECTION, std::string()); } else { UMA_HISTOGRAM_ENUMERATION("GData.AuthSuccess", kSuccessRatioHistogramFailure, kSuccessRatioHistogramMaxValue); callback_.Run(HTTP_UNAUTHORIZED, std::string()); } NotifyFinish(OPERATION_FAILED); } //============================ UrlFetchOperationBase =========================== UrlFetchOperationBase::UrlFetchOperationBase(OperationRegistry* registry) : OperationRegistry::Operation(registry), re_authenticate_count_(0), save_temp_file_(false), started_(false) { } UrlFetchOperationBase::UrlFetchOperationBase(OperationRegistry* registry, OperationType type, const FilePath& path) : OperationRegistry::Operation(registry, type, path), re_authenticate_count_(0), save_temp_file_(false), started_(false) { } UrlFetchOperationBase::~UrlFetchOperationBase() {} void UrlFetchOperationBase::Start(const std::string& auth_token) { DCHECK(!auth_token.empty()); GURL url = GetURL(); DCHECK(!url.is_empty()); DVLOG(1) << "URL: " << url.spec(); url_fetcher_.reset( URLFetcher::Create(url, GetRequestType(), this)); url_fetcher_->SetRequestContext(g_browser_process->system_request_context()); // Always set flags to neither send nor save cookies. url_fetcher_->SetLoadFlags( net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DISABLE_CACHE); if (save_temp_file_) { url_fetcher_->SaveResponseToTemporaryFile( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)); } else if (!output_file_path_.empty()) { url_fetcher_->SaveResponseToFileAtPath(output_file_path_, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)); } // Add request headers. // Note that SetExtraRequestHeaders clears the current headers and sets it // to the passed-in headers, so calling it for each header will result in // only the last header being set in request headers. url_fetcher_->AddExtraRequestHeader(kGDataVersionHeader); url_fetcher_->AddExtraRequestHeader( base::StringPrintf(kAuthorizationHeaderFormat, auth_token.data())); std::vector<std::string> headers = GetExtraRequestHeaders(); for (size_t i = 0; i < headers.size(); ++i) { url_fetcher_->AddExtraRequestHeader(headers[i]); DVLOG(1) << "Extra header: " << headers[i]; } // Set upload data if available. std::string upload_content_type; std::string upload_content; if (GetContentData(&upload_content_type, &upload_content)) { url_fetcher_->SetUploadData(upload_content_type, upload_content); } // Register to operation registry. NotifyStartToOperationRegistry(); url_fetcher_->Start(); started_ = true; } void UrlFetchOperationBase::SetReAuthenticateCallback( const ReAuthenticateCallback& callback) { DCHECK(re_authenticate_callback_.is_null()); re_authenticate_callback_ = callback; } URLFetcher::RequestType UrlFetchOperationBase::GetRequestType() const { return URLFetcher::GET; } std::vector<std::string> UrlFetchOperationBase::GetExtraRequestHeaders() const { return std::vector<std::string>(); } bool UrlFetchOperationBase::GetContentData(std::string* upload_content_type, std::string* upload_content) { return false; } void UrlFetchOperationBase::DoCancel() { url_fetcher_.reset(NULL); RunCallbackOnPrematureFailure(GDATA_CANCELLED); } GDataErrorCode UrlFetchOperationBase::GetErrorCode( const URLFetcher* source) const { GDataErrorCode code = static_cast<GDataErrorCode>(source->GetResponseCode()); if (code == HTTP_SUCCESS && !source->GetStatus().is_success()) { // If the HTTP response code is SUCCESS yet the URL request failed, it is // likely that the failure is due to loss of connection. code = GDATA_NO_CONNECTION; } return code; } void UrlFetchOperationBase::OnProcessURLFetchResultsComplete(bool result) { if (result) NotifySuccessToOperationRegistry(); else NotifyFinish(OPERATION_FAILED); } void UrlFetchOperationBase::OnURLFetchComplete(const URLFetcher* source) { GDataErrorCode code = GetErrorCode(source); DVLOG(1) << "Response headers:\n" << GetResponseHeadersAsString(source); if (code == HTTP_UNAUTHORIZED) { if (!re_authenticate_callback_.is_null() && ++re_authenticate_count_ <= kMaxReAuthenticateAttemptsPerOperation) { re_authenticate_callback_.Run(this); return; } OnAuthFailed(code); return; } // Overridden by each specialization ProcessURLFetchResults(source); } void UrlFetchOperationBase::NotifySuccessToOperationRegistry() { NotifyFinish(OPERATION_COMPLETED); } void UrlFetchOperationBase::NotifyStartToOperationRegistry() { NotifyStart(); } void UrlFetchOperationBase::OnAuthFailed(GDataErrorCode code) { RunCallbackOnPrematureFailure(code); // Notify authentication failed. NotifyAuthFailed(); // Check if this failed before we even started fetching. If so, register // for start so we can properly unregister with finish. if (!started_) NotifyStart(); // Note: NotifyFinish() must be invoked at the end, after all other callbacks // and notifications. Once NotifyFinish() is called, the current instance of // gdata operation will be deleted from the OperationRegistry and become // invalid. NotifyFinish(OPERATION_FAILED); } std::string UrlFetchOperationBase::GetResponseHeadersAsString( const URLFetcher* url_fetcher) { // net::HttpResponseHeaders::raw_headers(), as the name implies, stores // all headers in their raw format, i.e each header is null-terminated. // So logging raw_headers() only shows the first header, which is probably // the status line. GetNormalizedHeaders, on the other hand, will show all // the headers, one per line, which is probably what we want. std::string headers; // Check that response code indicates response headers are valid (i.e. not // malformed) before we retrieve the headers. if (url_fetcher->GetResponseCode() == URLFetcher::RESPONSE_CODE_INVALID) { headers.assign("Response headers are malformed!!"); } else { url_fetcher->GetResponseHeaders()->GetNormalizedHeaders(&headers); } return headers; } //============================ EntryActionOperation ============================ EntryActionOperation::EntryActionOperation(OperationRegistry* registry, const EntryActionCallback& callback, const GURL& document_url) : UrlFetchOperationBase(registry), callback_(callback), document_url_(document_url) { } EntryActionOperation::~EntryActionOperation() {} void EntryActionOperation::ProcessURLFetchResults(const URLFetcher* source) { if (!callback_.is_null()) { GDataErrorCode code = GetErrorCode(source); callback_.Run(code, document_url_); } const bool success = true; OnProcessURLFetchResultsComplete(success); } void EntryActionOperation::RunCallbackOnPrematureFailure(GDataErrorCode code) { if (!callback_.is_null()) callback_.Run(code, document_url_); } //============================== GetDataOperation ============================== GetDataOperation::GetDataOperation(OperationRegistry* registry, const GetDataCallback& callback) : UrlFetchOperationBase(registry), callback_(callback), ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) { } GetDataOperation::~GetDataOperation() {} void GetDataOperation::ProcessURLFetchResults(const URLFetcher* source) { std::string data; source->GetResponseAsString(&data); scoped_ptr<base::Value> root_value; GDataErrorCode fetch_error_code = GetErrorCode(source); switch (fetch_error_code) { case HTTP_SUCCESS: case HTTP_CREATED: ParseResponse(fetch_error_code, data); break; default: RunCallback(fetch_error_code, scoped_ptr<base::Value>()); const bool success = false; OnProcessURLFetchResultsComplete(success); break; } } void GetDataOperation::RunCallbackOnPrematureFailure( GDataErrorCode fetch_error_code) { if (!callback_.is_null()) { scoped_ptr<base::Value> root_value; callback_.Run(fetch_error_code, root_value.Pass()); } } void GetDataOperation::ParseResponse(GDataErrorCode fetch_error_code, const std::string& data) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // Uses this hack to avoid deep-copy of json object because json might be so // big. This pointer of scped_ptr is to ensure a deletion of the parsed json // value object. scoped_ptr<base::Value>* parsed_value = new scoped_ptr<base::Value>(); BrowserThread::PostBlockingPoolTaskAndReply( FROM_HERE, base::Bind(&ParseJsonOnBlockingPool, data, parsed_value), base::Bind(&GetDataOperation::OnDataParsed, weak_ptr_factory_.GetWeakPtr(), fetch_error_code, base::Owned(parsed_value))); } void GetDataOperation::OnDataParsed( gdata::GDataErrorCode fetch_error_code, scoped_ptr<base::Value>* value) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); bool success = true; if (!value->get()) { fetch_error_code = gdata::GDATA_PARSE_ERROR; success = false; } // The ownership of the parsed json object is transfered to RunCallBack(), // keeping the ownership of the |value| here. RunCallback(fetch_error_code, value->Pass()); DCHECK(!value->get()); OnProcessURLFetchResultsComplete(success); // |value| will be deleted after return because it is base::Owned()'d. } void GetDataOperation::RunCallback(GDataErrorCode fetch_error_code, scoped_ptr<base::Value> value) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!callback_.is_null()) callback_.Run(fetch_error_code, value.Pass()); } } // namespace gdata <|endoftext|>
<commit_before>/* The Halfling Project - A Graphics Engine and Projects * * The Halfling Project is the legal property of Adrian Astley * Copyright Adrian Astley 2013 */ #include "lighting_demo/game_state_manager.h" #include "common/math.h" #include "common/camera.h" #include "common/d3d_util.h" namespace LightingDemo { GameStateManager::GameStateManager() : GameStateManagerBase(), m_camera(1.5f * DirectX::XM_PI, 0.25f * DirectX::XM_PI, 5.0f) { } bool GameStateManager::Initialize(HWND hwnd, ID3D11Device **device) { GameStateManagerBase::Initialize(hwnd, device); BuildGeometryBuffers(); CreateLights(); // Set the view matrices to identity DirectX::XMMATRIX identity = DirectX::XMMatrixIdentity(); WorldViewProj.world = identity; WorldViewProj.view = identity; WorldViewProj.view = identity; return true; } void GameStateManager::Shutdown() { } void GameStateManager::Update() { WorldViewProj.view = m_camera.CreateViewMatrix(DirectX::XMVectorZero()); } void GameStateManager::OnResize(int newClientWidth, int newClientHeight) { // Update the aspect ratio and the projection matrix WorldViewProj.projection = DirectX::XMMatrixPerspectiveFovLH(0.25f * DirectX::XM_PI, float(newClientWidth) / newClientHeight, 1.0f, 1000.0f); } void GameStateManager::GamePaused() { } void GameStateManager::GameUnpaused() { } void GameStateManager::MouseDown(WPARAM buttonState, int x, int y) { m_mouseLastPos.x = x; m_mouseLastPos.y = y; SetCapture(m_hwnd); } void GameStateManager::MouseUp(WPARAM buttonState, int x, int y) { ReleaseCapture(); } void GameStateManager::MouseMove(WPARAM buttonState, int x, int y) { if ((buttonState & MK_LBUTTON) != 0) { // Calculate the new phi and theta based on mouse position relative to where the user clicked // Four mouse pixel movements is 1 degree float dPhi = ((float)(m_mouseLastPos.y - y) / 300); float dTheta = ((float)(x - m_mouseLastPos.x) / 300); m_camera.MoveCamera(dTheta, dPhi, 0.0f); } m_mouseLastPos.x = x; m_mouseLastPos.y = y; } void GameStateManager::MouseWheel(int zDelta) { // Make each wheel dedent correspond to 0.05 units m_camera.MoveCamera(0.0f, 0.0f, -0.005f * (float)zDelta); } void GameStateManager::BuildGeometryBuffers() { Models.push_back(Common::Model<Vertex>()); Common::Model<Vertex> *model = &Models.back(); Vertex *verticies = new Vertex[24] { // Left face {DirectX::XMFLOAT3(-1.0f, -1.0f, -1.0f), DirectX::XMFLOAT3(0.0f, 0.0f, +1.0f)}, // 0 {DirectX::XMFLOAT3(-1.0f, +1.0f, -1.0f), DirectX::XMFLOAT3(0.0f, 0.0f, +1.0f)}, // 1 {DirectX::XMFLOAT3(+1.0f, +1.0f, -1.0f), DirectX::XMFLOAT3(0.0f, 0.0f, +1.0f)}, // 2 {DirectX::XMFLOAT3(+1.0f, -1.0f, -1.0f), DirectX::XMFLOAT3(0.0f, 0.0f, +1.0f)}, // 3 // Back face {DirectX::XMFLOAT3(-1.0f, -1.0f, +1.0f), DirectX::XMFLOAT3(0.0f, 0.0f, -1.0f)}, // 4 {DirectX::XMFLOAT3(-1.0f, +1.0f, +1.0f), DirectX::XMFLOAT3(0.0f, 0.0f, -1.0f)}, // 5 {DirectX::XMFLOAT3(+1.0f, +1.0f, +1.0f), DirectX::XMFLOAT3(0.0f, 0.0f, -1.0f)}, // 6 {DirectX::XMFLOAT3(+1.0f, -1.0f, +1.0f), DirectX::XMFLOAT3(0.0f, 0.0f, -1.0f)}, // 7 // Left face {DirectX::XMFLOAT3(-1.0f, -1.0f, +1.0f), DirectX::XMFLOAT3(-1.0f, 0.0f, 0.0f)}, // 4 {DirectX::XMFLOAT3(-1.0f, +1.0f, +1.0f), DirectX::XMFLOAT3(-1.0f, 0.0f, 0.0f)}, // 5 {DirectX::XMFLOAT3(-1.0f, +1.0f, -1.0f), DirectX::XMFLOAT3(-1.0f, 0.0f, 0.0f)}, // 1 {DirectX::XMFLOAT3(-1.0f, -1.0f, -1.0f), DirectX::XMFLOAT3(-1.0f, 0.0f, 0.0f)}, // 0 // Right face {DirectX::XMFLOAT3(+1.0f, +1.0f, -1.0f), DirectX::XMFLOAT3(+1.0f, 0.0f, 0.0f)}, // 2 {DirectX::XMFLOAT3(+1.0f, -1.0f, -1.0f), DirectX::XMFLOAT3(+1.0f, 0.0f, 0.0f)}, // 3 {DirectX::XMFLOAT3(+1.0f, +1.0f, +1.0f), DirectX::XMFLOAT3(+1.0f, 0.0f, 0.0f)}, // 6 {DirectX::XMFLOAT3(+1.0f, -1.0f, +1.0f), DirectX::XMFLOAT3(+1.0f, 0.0f, 0.0f)}, // 7 // Top face {DirectX::XMFLOAT3(-1.0f, +1.0f, -1.0f), DirectX::XMFLOAT3(0.0f, +1.0f, 0.0f)}, // 1 {DirectX::XMFLOAT3(+1.0f, +1.0f, -1.0f), DirectX::XMFLOAT3(0.0f, +1.0f, 0.0f)}, // 2 {DirectX::XMFLOAT3(-1.0f, +1.0f, +1.0f), DirectX::XMFLOAT3(0.0f, +1.0f, 0.0f)}, // 5 {DirectX::XMFLOAT3(+1.0f, +1.0f, +1.0f), DirectX::XMFLOAT3(0.0f, +1.0f, 0.0f)}, // 6 // Bottom face {DirectX::XMFLOAT3(-1.0f, -1.0f, -1.0f), DirectX::XMFLOAT3(0.0f, -1.0f, 0.0f)}, // 0 {DirectX::XMFLOAT3(+1.0f, -1.0f, -1.0f), DirectX::XMFLOAT3(0.0f, -1.0f, 0.0f)}, // 3 {DirectX::XMFLOAT3(-1.0f, -1.0f, +1.0f), DirectX::XMFLOAT3(0.0f, -1.0f, 0.0f)}, // 4 {DirectX::XMFLOAT3(+1.0f, -1.0f, +1.0f), DirectX::XMFLOAT3(0.0f, -1.0f, 0.0f)}, // 7 }; model->SetVertices(*m_device, verticies, 24); // Create the index buffer uint *indicies = new uint[36] { // Front face 0, 1, 2, 0, 2, 3, // Back face 4, 6, 5, 4, 7, 6, // Left face 8, 9, 10, 8, 10, 11, // Right face 13, 12, 14, 13, 14, 15, // Top face 16, 18, 19, 16, 19, 17, // Bottom face 22, 20, 21, 22, 21, 23 }; model->SetIndices(*m_device, indicies, 36); } } // End of namespace CrateDemo <commit_msg>LIGHTING_DEMO: Utilize the GeometryGenerator instead of creating the vertices/indices manually<commit_after>/* The Halfling Project - A Graphics Engine and Projects * * The Halfling Project is the legal property of Adrian Astley * Copyright Adrian Astley 2013 */ #include "lighting_demo/game_state_manager.h" #include "common/math.h" #include "common/camera.h" #include "common/d3d_util.h" #include "common/geometry_generator.h" namespace LightingDemo { GameStateManager::GameStateManager() : GameStateManagerBase(), m_camera(1.5f * DirectX::XM_PI, 0.25f * DirectX::XM_PI, 5.0f) { } bool GameStateManager::Initialize(HWND hwnd, ID3D11Device **device) { GameStateManagerBase::Initialize(hwnd, device); BuildGeometryBuffers(); CreateLights(); // Set the view matrices to identity DirectX::XMMATRIX identity = DirectX::XMMatrixIdentity(); WorldViewProj.world = identity; WorldViewProj.view = identity; WorldViewProj.view = identity; return true; } void GameStateManager::Shutdown() { } void GameStateManager::Update() { WorldViewProj.view = m_camera.CreateViewMatrix(DirectX::XMVectorZero()); } void GameStateManager::OnResize(int newClientWidth, int newClientHeight) { // Update the aspect ratio and the projection matrix WorldViewProj.projection = DirectX::XMMatrixPerspectiveFovLH(0.25f * DirectX::XM_PI, float(newClientWidth) / newClientHeight, 1.0f, 1000.0f); } void GameStateManager::GamePaused() { } void GameStateManager::GameUnpaused() { } void GameStateManager::MouseDown(WPARAM buttonState, int x, int y) { m_mouseLastPos.x = x; m_mouseLastPos.y = y; SetCapture(m_hwnd); } void GameStateManager::MouseUp(WPARAM buttonState, int x, int y) { ReleaseCapture(); } void GameStateManager::MouseMove(WPARAM buttonState, int x, int y) { if ((buttonState & MK_LBUTTON) != 0) { // Calculate the new phi and theta based on mouse position relative to where the user clicked // Four mouse pixel movements is 1 degree float dPhi = ((float)(m_mouseLastPos.y - y) / 300); float dTheta = ((float)(x - m_mouseLastPos.x) / 300); m_camera.MoveCamera(dTheta, dPhi, 0.0f); } m_mouseLastPos.x = x; m_mouseLastPos.y = y; } void GameStateManager::MouseWheel(int zDelta) { // Make each wheel dedent correspond to 0.05 units m_camera.MoveCamera(0.0f, 0.0f, -0.005f * (float)zDelta); } void GameStateManager::BuildGeometryBuffers() { Models.push_back(Common::Model<Vertex>()); Common::Model<Vertex> *model = &Models.back(); Common::GeometryGenerator::MeshData meshData; Common::GeometryGenerator::CreateBox(1.0f, 1.0f, 1.0f, &meshData); uint vertexCount = meshData.Vertices.size(); uint indexCount = meshData.Indices.size(); Vertex *vertices = new Vertex[vertexCount]; for (uint i = 0; i < vertexCount; ++i) { vertices[i].pos = meshData.Vertices[i].Position; vertices[i].normal = meshData.Vertices[i].Normal; } model->SetVertices(*m_device, vertices, vertexCount); uint *indices = new uint[indexCount]; for (uint i = 0; i < indexCount; ++i) { indices[i] = meshData.Indices[i]; } model->SetIndices(*m_device, indices, indexCount); // Create subsets Common::ModelSubset *subsets = new Common::ModelSubset[1] { {0, vertexCount, 0, indexCount / 3, {DirectX::XMFLOAT4(0.48f, 0.77f, 0.46f, 1.0f), DirectX::XMFLOAT4(0.48f, 0.77f, 0.46f, 1.0f), DirectX::XMFLOAT4(0.2f, 0.2f, 0.2f, 96.0f)} } }; model->SetSubsets(subsets, 1); } void GameStateManager::CreateLights() { Common::DirectionalLight *directionalLight = LightManager.GetDirectionalLight(); directionalLight->Ambient = DirectX::XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f); directionalLight->Diffuse = DirectX::XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); directionalLight->Specular = DirectX::XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); directionalLight->Direction = DirectX::XMFLOAT3(0.57735f, -0.57735f, 0.57735f); } } // End of namespace CrateDemo <|endoftext|>
<commit_before>#ifndef INCLUDE_AL_GRAPHICS_STEREOGRAPHIC_HPP #define INCLUDE_AL_GRAPHICS_STEREOGRAPHIC_HPP /* * A collection of functions and classes related to application mainloops * AlloSphere Research Group / Media Arts & Technology, UCSB, 2009 */ /* Copyright (C) 2006-2008. The Regents of the University of California (REGENTS). All Rights Reserved. Permission to use, copy, modify, distribute, and distribute modified versions of this software and its documentation without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, the list of contributors, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #include "allocore/graphics/al_Graphics.hpp" #include "allocore/spatial/al_Camera.hpp" #include "allocore/spatial/al_Pose.hpp" #include "allocore/types/al_Color.hpp" namespace al{ /// A framed area on a display screen struct Viewport { float l, b, w, h; ///< left, bottom, width, height Viewport(float w=800, float h=600) : l(0), b(0), w(w), h(h) {} Viewport(float l, float b, float w, float h) : l(l), b(b), w(w), h(h) {} /// Get aspect ratio (width divided by height) float aspect() const { return (h!=0 && w!=0) ? float(w)/h : 1; } /// Set dimensions void set(float l_, float b_, float w_, float h_){ l=l_; b=b_; w=w_; h=h_; } }; /// Higher-level utility class to manage various stereo rendering techniques class Stereographic { public: enum StereoMode{ Anaglyph=0, /**< Red (left eye) / cyan (right eye) stereo */ Active, /**< Active quad-buffered stereo */ Dual, /**< Dual side-by-side stereo */ LeftEye, /**< Left eye only */ RightEye /**< Right eye only */ }; enum AnaglyphMode { RedBlue = 0, RedGreen, RedCyan, BlueRed, GreenRed, CyanRed }; Stereographic() : mMode(Anaglyph), mAnaglyphMode(RedCyan), mClearColor(Color(0)), mStereo(false), mOmni(0), mSlices(24), mOmniFov(360) {} ~Stereographic() {} /// Draw the scene according to the stored stereographic mode void draw (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); /// So many different ways to draw :-) void drawMono (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); void drawActive (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); void drawAnaglyph (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); void drawDual (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); void drawLeft (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); void drawRight (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); /// Blue line sync for active stereo (for those projectors that need it) /// add this call at the end of rendering (just before the swap buffers call) void drawBlueLine(double window_width, double window_height); Stereographic& clearColor(const Color& v){ mClearColor=v; return *this; } ///< Set background clear color Stereographic& mode(StereoMode v){ mMode=v; return *this; } ///< Set stereographic mode Stereographic& stereo(bool v){ mStereo=v; return *this; } ///< Set stereographic active Stereographic& anaglyphMode(AnaglyphMode v) { mAnaglyphMode=v; return *this; } ///< set glasses type /// Set omnigraphic mode /// slices: sets number of sub-viewport slices to render /// fov (degrees) sets field of view (horizontal) /// NOTE: cam.fovy will be ignored in omni mode Stereographic& omni(bool enable) { mOmni = enable; return *this; } Stereographic& omni(bool enable, unsigned slices, double fov=360) { mOmni = enable; mSlices = slices; mOmniFov = fov; return *this; } Stereographic& omniFov( double fov ) { mOmniFov = fov; return *this; } const Color& clearColor() const { return mClearColor; } ///< Get background clear color StereoMode mode() const { return mMode; } ///< Get stereographic mode bool stereo() const { return mStereo; } ///< Get stereographic active AnaglyphMode anaglyphMode() const { return mAnaglyphMode; } ///< get anaglyph glasses type bool omni() const { return mOmni; } // These accessors will be valid only during the Drawable's onDraw() event // they can be useful to simulate the OpenGL pipeline transforms // e.g. Matrix4d::multiply(Vec4d eyespace, stereo.modelView(), Vec4d objectspace); // e.g. Matrix4d::multiply(Vec4d clipspace, stereo.projection(), Vec4d eyespace); // e.g. Matrix4d::multiply(Vec4d clipspace, stereo.modelViewProjection(), Vec4d objectspace); // to convert in the opposite direction, use Matrix4::inverse(). const Matrix4d& modelView() const { return mModelView; } const Matrix4d& projection() const { return mProjection; } Matrix4d modelViewProjection() const { return mProjection * mModelView; } protected: StereoMode mMode; AnaglyphMode mAnaglyphMode; Color mClearColor; bool mStereo; bool mOmni; unsigned mSlices; // number of omni slices double mOmniFov; // field of view of omnigraphics Matrix4d mProjection, mModelView; }; } // al:: #endif <commit_msg>omni methods<commit_after>#ifndef INCLUDE_AL_GRAPHICS_STEREOGRAPHIC_HPP #define INCLUDE_AL_GRAPHICS_STEREOGRAPHIC_HPP /* * A collection of functions and classes related to application mainloops * AlloSphere Research Group / Media Arts & Technology, UCSB, 2009 */ /* Copyright (C) 2006-2008. The Regents of the University of California (REGENTS). All Rights Reserved. Permission to use, copy, modify, distribute, and distribute modified versions of this software and its documentation without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, the list of contributors, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #include "allocore/graphics/al_Graphics.hpp" #include "allocore/spatial/al_Camera.hpp" #include "allocore/spatial/al_Pose.hpp" #include "allocore/types/al_Color.hpp" namespace al{ /// A framed area on a display screen struct Viewport { float l, b, w, h; ///< left, bottom, width, height Viewport(float w=800, float h=600) : l(0), b(0), w(w), h(h) {} Viewport(float l, float b, float w, float h) : l(l), b(b), w(w), h(h) {} /// Get aspect ratio (width divided by height) float aspect() const { return (h!=0 && w!=0) ? float(w)/h : 1; } /// Set dimensions void set(float l_, float b_, float w_, float h_){ l=l_; b=b_; w=w_; h=h_; } }; /// Higher-level utility class to manage various stereo rendering techniques class Stereographic { public: enum StereoMode{ Anaglyph=0, /**< Red (left eye) / cyan (right eye) stereo */ Active, /**< Active quad-buffered stereo */ Dual, /**< Dual side-by-side stereo */ LeftEye, /**< Left eye only */ RightEye /**< Right eye only */ }; enum AnaglyphMode { RedBlue = 0, RedGreen, RedCyan, BlueRed, GreenRed, CyanRed }; Stereographic() : mMode(Anaglyph), mAnaglyphMode(RedCyan), mClearColor(Color(0)), mStereo(false), mOmni(0), mSlices(24), mOmniFov(360) {} ~Stereographic() {} /// Draw the scene according to the stored stereographic mode void draw (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); /// So many different ways to draw :-) void drawMono (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); void drawActive (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); void drawAnaglyph (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); void drawDual (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); void drawLeft (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); void drawRight (Graphics& gl, const Camera& cam, const Pose& pose, const Viewport& vp, Drawable& draw); /// Blue line sync for active stereo (for those projectors that need it) /// add this call at the end of rendering (just before the swap buffers call) void drawBlueLine(double window_width, double window_height); Stereographic& clearColor(const Color& v){ mClearColor=v; return *this; } ///< Set background clear color Stereographic& mode(StereoMode v){ mMode=v; return *this; } ///< Set stereographic mode Stereographic& stereo(bool v){ mStereo=v; return *this; } ///< Set stereographic active Stereographic& anaglyphMode(AnaglyphMode v) { mAnaglyphMode=v; return *this; } ///< set glasses type /// Set omnigraphic mode /// slices: sets number of sub-viewport slices to render /// fov (degrees) sets field of view (horizontal) /// NOTE: cam.fovy will be ignored in omni mode Stereographic& omni(bool enable) { mOmni = enable; return *this; } Stereographic& omni(bool enable, unsigned slices, double fov=360) { mOmni = enable; mSlices = slices; mOmniFov = fov; return *this; } Stereographic& omniFov( double fov ) { mOmniFov = fov; return *this; } Stereographic& omniSlices( int slices ) { mSlices = slices; return *this; } const Color& clearColor() const { return mClearColor; } ///< Get background clear color StereoMode mode() const { return mMode; } ///< Get stereographic mode bool stereo() const { return mStereo; } ///< Get stereographic active AnaglyphMode anaglyphMode() const { return mAnaglyphMode; } ///< get anaglyph glasses type bool omni() const { return mOmni; } // These accessors will be valid only during the Drawable's onDraw() event // they can be useful to simulate the OpenGL pipeline transforms // e.g. Matrix4d::multiply(Vec4d eyespace, stereo.modelView(), Vec4d objectspace); // e.g. Matrix4d::multiply(Vec4d clipspace, stereo.projection(), Vec4d eyespace); // e.g. Matrix4d::multiply(Vec4d clipspace, stereo.modelViewProjection(), Vec4d objectspace); // to convert in the opposite direction, use Matrix4::inverse(). const Matrix4d& modelView() const { return mModelView; } const Matrix4d& projection() const { return mProjection; } Matrix4d modelViewProjection() const { return mProjection * mModelView; } protected: StereoMode mMode; AnaglyphMode mAnaglyphMode; Color mClearColor; bool mStereo; bool mOmni; unsigned mSlices; // number of omni slices double mOmniFov; // field of view of omnigraphics Matrix4d mProjection, mModelView; }; } // al:: #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkBasicFiltersTests3.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif // this file defines the itkBasicFiltersTest for the test driver // and all it expects is that you have a function called RegisterTests #include <iostream> #include "itkTestMain.h" void RegisterTests() { REGISTER_TEST(itkCheckerBoardImageFilterTest ); REGISTER_TEST(itkHessianRecursiveGaussianFilterTest ); REGISTER_TEST(itkSymmetricEigenAnalysisImageFilterTest ); REGISTER_TEST(itkNormalizedCorrelationImageFilterTest ); REGISTER_TEST(itkTensorFractionalAnisotropyImageFilterTest ); REGISTER_TEST(itkTensorRelativeAnisotropyImageFilterTest ); REGISTER_TEST(itkTriangleMeshToBinaryImageFilterTest ); REGISTER_TEST(itkTriangleMeshToBinaryImageFilterTest2 ); REGISTER_TEST(itkVectorAnisotropicDiffusionImageFilterTest ); REGISTER_TEST(itkVectorConfidenceConnectedImageFilterTest ); REGISTER_TEST(itkVectorExpandImageFilterTest ); REGISTER_TEST(itkVectorGradientMagnitudeImageFilterTest1 ); REGISTER_TEST(itkVectorGradientMagnitudeImageFilterTest2 ); REGISTER_TEST(itkVectorNeighborhoodOperatorImageFilterTest ); REGISTER_TEST(itkVectorResampleImageFilterTest ); REGISTER_TEST(itkVectorRescaleIntensityImageFilterTest ); REGISTER_TEST(itkVotingBinaryHoleFillingImageFilterTest ); REGISTER_TEST(itkVotingBinaryImageFilterTest ); REGISTER_TEST(itkVotingBinaryIterativeHoleFillingImageFilterTest ); REGISTER_TEST(itkWarpImageFilterTest ); REGISTER_TEST(itkWarpMeshFilterTest ); REGISTER_TEST(itkWarpVectorImageFilterTest ); REGISTER_TEST(itkWeightedAddImageFilterTest); REGISTER_TEST(itkWrapPadImageTest ); REGISTER_TEST(itkXorImageFilterTest ); REGISTER_TEST(itkZeroCrossingBasedEdgeDetectionImageFilterTest ); REGISTER_TEST(itkZeroCrossingImageFilterTest ); } <commit_msg>ENH: added new test program<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkBasicFiltersTests3.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif // this file defines the itkBasicFiltersTest for the test driver // and all it expects is that you have a function called RegisterTests #include <iostream> #include "itkTestMain.h" void RegisterTests() { REGISTER_TEST(itkCheckerBoardImageFilterTest ); REGISTER_TEST(itkHessianRecursiveGaussianFilterTest ); REGISTER_TEST(itkSymmetricEigenAnalysisImageFilterTest ); REGISTER_TEST(itkNormalizedCorrelationImageFilterTest ); REGISTER_TEST(itkPolylineMaskImageFilterTest ); REGISTER_TEST(itkTensorFractionalAnisotropyImageFilterTest ); REGISTER_TEST(itkTensorRelativeAnisotropyImageFilterTest ); REGISTER_TEST(itkTriangleMeshToBinaryImageFilterTest ); REGISTER_TEST(itkTriangleMeshToBinaryImageFilterTest2 ); REGISTER_TEST(itkVectorAnisotropicDiffusionImageFilterTest ); REGISTER_TEST(itkVectorConfidenceConnectedImageFilterTest ); REGISTER_TEST(itkVectorExpandImageFilterTest ); REGISTER_TEST(itkVectorGradientMagnitudeImageFilterTest1 ); REGISTER_TEST(itkVectorGradientMagnitudeImageFilterTest2 ); REGISTER_TEST(itkVectorNeighborhoodOperatorImageFilterTest ); REGISTER_TEST(itkVectorResampleImageFilterTest ); REGISTER_TEST(itkVectorRescaleIntensityImageFilterTest ); REGISTER_TEST(itkVotingBinaryHoleFillingImageFilterTest ); REGISTER_TEST(itkVotingBinaryImageFilterTest ); REGISTER_TEST(itkVotingBinaryIterativeHoleFillingImageFilterTest ); REGISTER_TEST(itkWarpImageFilterTest ); REGISTER_TEST(itkWarpMeshFilterTest ); REGISTER_TEST(itkWarpVectorImageFilterTest ); REGISTER_TEST(itkWeightedAddImageFilterTest); REGISTER_TEST(itkWrapPadImageTest ); REGISTER_TEST(itkXorImageFilterTest ); REGISTER_TEST(itkZeroCrossingBasedEdgeDetectionImageFilterTest ); REGISTER_TEST(itkZeroCrossingImageFilterTest ); } <|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 <string> #include <vector> #include "base/message_loop.h" #include "base/process.h" #include "base/process_util.h" #include "base/scoped_ptr.h" #include "chrome/common/filter_policy.h" #include "chrome/common/render_messages.h" #include "chrome/common/resource_dispatcher.h" #include "testing/gtest/include/gtest/gtest.h" #include "webkit/appcache/appcache_interfaces.h" using webkit_glue::ResourceLoaderBridge; static const char test_page_url[] = "http://www.google.com/"; static const char test_page_headers[] = "HTTP/1.1 200 OK\nContent-Type:text/html\n\n"; static const char test_page_mime_type[] = "text/html"; static const char test_page_charset[] = ""; static const char test_page_contents[] = "<html><head><title>Google</title></head><body><h1>Google</h1></body></html>"; static const int test_page_contents_len = arraysize(test_page_contents) - 1; // Listens for request response data and stores it so that it can be compared // to the reference data. class TestRequestCallback : public ResourceLoaderBridge::Peer { public: TestRequestCallback() : complete_(false) { } virtual bool OnReceivedRedirect( const GURL& new_url, const ResourceLoaderBridge::ResponseInfo& info, bool* has_new_first_party_for_cookies, GURL* new_first_party_for_cookies) { *has_new_first_party_for_cookies = false; return true; } virtual void OnReceivedResponse( const ResourceLoaderBridge::ResponseInfo& info, bool content_filtered) { } virtual void OnReceivedData(const char* data, int len) { EXPECT_FALSE(complete_); data_.append(data, len); } virtual void OnUploadProgress(uint64 position, uint64 size) { } virtual void OnCompletedRequest(const URLRequestStatus& status, const std::string& security_info) { EXPECT_FALSE(complete_); complete_ = true; } virtual GURL GetURLForDebugging() const { return GURL(); } const std::string& data() const { return data_; } const bool complete() const { return complete_; } private: bool complete_; std::string data_; }; // Sets up the message sender override for the unit test class ResourceDispatcherTest : public testing::Test, public IPC::Message::Sender { public: // Emulates IPC send operations (IPC::Message::Sender) by adding // pending messages to the queue. virtual bool Send(IPC::Message* msg) { message_queue_.push_back(IPC::Message(*msg)); delete msg; return true; } // Emulates the browser process and processes the pending IPC messages, // returning the hardcoded file contents. void ProcessMessages() { while (!message_queue_.empty()) { int request_id; ViewHostMsg_Resource_Request request; ASSERT_TRUE(ViewHostMsg_RequestResource::Read( &message_queue_[0], &request_id, &request)); // check values EXPECT_EQ(test_page_url, request.url.spec()); // received response message ResourceResponseHead response; std::string raw_headers(test_page_headers); std::replace(raw_headers.begin(), raw_headers.end(), '\n', '\0'); response.headers = new net::HttpResponseHeaders(raw_headers); response.mime_type = test_page_mime_type; response.charset = test_page_charset; response.filter_policy = FilterPolicy::DONT_FILTER; dispatcher_->OnReceivedResponse(request_id, response); // received data message with the test contents base::SharedMemory shared_mem; EXPECT_TRUE(shared_mem.Create(std::wstring(), false, false, test_page_contents_len)); EXPECT_TRUE(shared_mem.Map(test_page_contents_len)); char* put_data_here = static_cast<char*>(shared_mem.memory()); memcpy(put_data_here, test_page_contents, test_page_contents_len); base::SharedMemoryHandle dup_handle; EXPECT_TRUE(shared_mem.GiveToProcess( base::Process::Current().handle(), &dup_handle)); dispatcher_->OnReceivedData( message_queue_[0], request_id, dup_handle, test_page_contents_len); message_queue_.erase(message_queue_.begin()); // read the ack message. Tuple1<int> request_ack; ASSERT_TRUE(ViewHostMsg_DataReceived_ACK::Read( &message_queue_[0], &request_ack)); ASSERT_EQ(request_ack.a, request_id); message_queue_.erase(message_queue_.begin()); } } protected: // testing::Test virtual void SetUp() { dispatcher_.reset(new ResourceDispatcher(this)); } virtual void TearDown() { dispatcher_.reset(); } ResourceLoaderBridge* CreateBridge() { webkit_glue::ResourceLoaderBridge::RequestInfo request_info; request_info.method = "GET"; request_info.url = GURL(test_page_url); request_info.first_party_for_cookies = GURL(test_page_url); request_info.referrer = GURL(); request_info.frame_origin = "null"; request_info.main_frame_origin = "null"; request_info.headers = std::string(); request_info.load_flags = 0; request_info.requestor_pid = 0; request_info.request_type = ResourceType::SUB_RESOURCE; request_info.appcache_host_id = 0; request_info.routing_id = appcache::kNoHostId; return dispatcher_->CreateBridge(request_info, -1, -1); } std::vector<IPC::Message> message_queue_; static scoped_ptr<ResourceDispatcher> dispatcher_; }; /*static*/ scoped_ptr<ResourceDispatcher> ResourceDispatcherTest::dispatcher_; // Does a simple request and tests that the correct data is received. TEST_F(ResourceDispatcherTest, RoundTrip) { TestRequestCallback callback; ResourceLoaderBridge* bridge = CreateBridge(); bridge->Start(&callback); ProcessMessages(); // FIXME(brettw) when the request complete messages are actually handledo // and dispatched, uncomment this. //EXPECT_TRUE(callback.complete()); //EXPECT_STREQ(test_page_contents, callback.data().c_str()); delete bridge; } // Tests that the request IDs are straight when there are multiple requests. TEST_F(ResourceDispatcherTest, MultipleRequests) { // FIXME } // Tests that the cancel method prevents other messages from being received TEST_F(ResourceDispatcherTest, Cancel) { // FIXME } TEST_F(ResourceDispatcherTest, Cookies) { // FIXME } TEST_F(ResourceDispatcherTest, SerializedPostData) { // FIXME } // This class provides functionality to validate whether the ResourceDispatcher // object honors the deferred loading contract correctly, i.e. if deferred // loading is enabled it should queue up any responses received. If deferred // loading is enabled/disabled in the context of a dispatched message, other // queued messages should not be dispatched until deferred load is turned off. class DeferredResourceLoadingTest : public ResourceDispatcherTest, public ResourceLoaderBridge::Peer { public: DeferredResourceLoadingTest() : defer_loading_(false) { } virtual bool Send(IPC::Message* msg) { delete msg; return true; } void InitMessages() { set_defer_loading(true); ResourceResponseHead response_head; response_head.status.set_status(URLRequestStatus::SUCCESS); IPC::Message* response_message = new ViewMsg_Resource_ReceivedResponse(0, 0, response_head); dispatcher_->OnMessageReceived(*response_message); delete response_message; // Duplicate the shared memory handle so both the test and the callee can // close their copy. base::SharedMemoryHandle duplicated_handle; EXPECT_TRUE(shared_handle_.ShareToProcess(base::GetCurrentProcessHandle(), &duplicated_handle)); response_message = new ViewMsg_Resource_DataReceived(0, 0, duplicated_handle, 100); dispatcher_->OnMessageReceived(*response_message); delete response_message; set_defer_loading(false); } // ResourceLoaderBridge::Peer methods. virtual void OnReceivedResponse( const ResourceLoaderBridge::ResponseInfo& info, bool content_filtered) { EXPECT_EQ(defer_loading_, false); set_defer_loading(true); } virtual bool OnReceivedRedirect( const GURL& new_url, const ResourceLoaderBridge::ResponseInfo& info, bool* has_new_first_party_for_cookies, GURL* new_first_party_for_cookies) { *has_new_first_party_for_cookies = false; return true; } virtual void OnReceivedData(const char* data, int len) { EXPECT_EQ(defer_loading_, false); set_defer_loading(false); } virtual void OnUploadProgress(uint64 position, uint64 size) { } virtual void OnCompletedRequest(const URLRequestStatus& status, const std::string& security_info) { } virtual GURL GetURLForDebugging() const { return GURL(); } protected: virtual void SetUp() { EXPECT_EQ(true, shared_handle_.Create(L"DeferredResourceLoaderTest", false, false, 100)); ResourceDispatcherTest::SetUp(); } virtual void TearDown() { shared_handle_.Close(); ResourceDispatcherTest::TearDown(); } private: void set_defer_loading(bool defer) { defer_loading_ = defer; dispatcher_->SetDefersLoading(0, defer); } bool defer_loading() const { return defer_loading_; } bool defer_loading_; base::SharedMemory shared_handle_; }; TEST_F(DeferredResourceLoadingTest, DeferredLoadTest) { MessageLoop message_loop(MessageLoop::TYPE_IO); ResourceLoaderBridge* bridge = CreateBridge(); bridge->Start(this); InitMessages(); // Dispatch deferred messages. message_loop.RunAllPending(); delete bridge; } <commit_msg>Very minor cleanup.<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 <string> #include <vector> #include "base/message_loop.h" #include "base/process.h" #include "base/process_util.h" #include "base/scoped_ptr.h" #include "chrome/common/filter_policy.h" #include "chrome/common/render_messages.h" #include "chrome/common/resource_dispatcher.h" #include "testing/gtest/include/gtest/gtest.h" #include "webkit/appcache/appcache_interfaces.h" using webkit_glue::ResourceLoaderBridge; static const char test_page_url[] = "http://www.google.com/"; static const char test_page_headers[] = "HTTP/1.1 200 OK\nContent-Type:text/html\n\n"; static const char test_page_mime_type[] = "text/html"; static const char test_page_charset[] = ""; static const char test_page_contents[] = "<html><head><title>Google</title></head><body><h1>Google</h1></body></html>"; static const int test_page_contents_len = arraysize(test_page_contents) - 1; // Listens for request response data and stores it so that it can be compared // to the reference data. class TestRequestCallback : public ResourceLoaderBridge::Peer { public: TestRequestCallback() : complete_(false) { } virtual bool OnReceivedRedirect( const GURL& new_url, const ResourceLoaderBridge::ResponseInfo& info, bool* has_new_first_party_for_cookies, GURL* new_first_party_for_cookies) { *has_new_first_party_for_cookies = false; return true; } virtual void OnReceivedResponse( const ResourceLoaderBridge::ResponseInfo& info, bool content_filtered) { } virtual void OnReceivedData(const char* data, int len) { EXPECT_FALSE(complete_); data_.append(data, len); } virtual void OnUploadProgress(uint64 position, uint64 size) { } virtual void OnCompletedRequest(const URLRequestStatus& status, const std::string& security_info) { EXPECT_FALSE(complete_); complete_ = true; } virtual GURL GetURLForDebugging() const { return GURL(); } const std::string& data() const { return data_; } const bool complete() const { return complete_; } private: bool complete_; std::string data_; }; // Sets up the message sender override for the unit test class ResourceDispatcherTest : public testing::Test, public IPC::Message::Sender { public: // Emulates IPC send operations (IPC::Message::Sender) by adding // pending messages to the queue. virtual bool Send(IPC::Message* msg) { message_queue_.push_back(IPC::Message(*msg)); delete msg; return true; } // Emulates the browser process and processes the pending IPC messages, // returning the hardcoded file contents. void ProcessMessages() { while (!message_queue_.empty()) { int request_id; ViewHostMsg_Resource_Request request; ASSERT_TRUE(ViewHostMsg_RequestResource::Read( &message_queue_[0], &request_id, &request)); // check values EXPECT_EQ(test_page_url, request.url.spec()); // received response message ResourceResponseHead response; std::string raw_headers(test_page_headers); std::replace(raw_headers.begin(), raw_headers.end(), '\n', '\0'); response.headers = new net::HttpResponseHeaders(raw_headers); response.mime_type = test_page_mime_type; response.charset = test_page_charset; response.filter_policy = FilterPolicy::DONT_FILTER; dispatcher_->OnReceivedResponse(request_id, response); // received data message with the test contents base::SharedMemory shared_mem; EXPECT_TRUE(shared_mem.Create(std::wstring(), false, false, test_page_contents_len)); EXPECT_TRUE(shared_mem.Map(test_page_contents_len)); char* put_data_here = static_cast<char*>(shared_mem.memory()); memcpy(put_data_here, test_page_contents, test_page_contents_len); base::SharedMemoryHandle dup_handle; EXPECT_TRUE(shared_mem.GiveToProcess( base::Process::Current().handle(), &dup_handle)); dispatcher_->OnReceivedData( message_queue_[0], request_id, dup_handle, test_page_contents_len); message_queue_.erase(message_queue_.begin()); // read the ack message. Tuple1<int> request_ack; ASSERT_TRUE(ViewHostMsg_DataReceived_ACK::Read( &message_queue_[0], &request_ack)); ASSERT_EQ(request_ack.a, request_id); message_queue_.erase(message_queue_.begin()); } } protected: // testing::Test virtual void SetUp() { dispatcher_.reset(new ResourceDispatcher(this)); } virtual void TearDown() { dispatcher_.reset(); } ResourceLoaderBridge* CreateBridge() { webkit_glue::ResourceLoaderBridge::RequestInfo request_info; request_info.method = "GET"; request_info.url = GURL(test_page_url); request_info.first_party_for_cookies = GURL(test_page_url); request_info.referrer = GURL(); request_info.frame_origin = "null"; request_info.main_frame_origin = "null"; request_info.headers = std::string(); request_info.load_flags = 0; request_info.requestor_pid = 0; request_info.request_type = ResourceType::SUB_RESOURCE; request_info.appcache_host_id = appcache::kNoHostId; request_info.routing_id = 0; return dispatcher_->CreateBridge(request_info, -1, -1); } std::vector<IPC::Message> message_queue_; static scoped_ptr<ResourceDispatcher> dispatcher_; }; /*static*/ scoped_ptr<ResourceDispatcher> ResourceDispatcherTest::dispatcher_; // Does a simple request and tests that the correct data is received. TEST_F(ResourceDispatcherTest, RoundTrip) { TestRequestCallback callback; ResourceLoaderBridge* bridge = CreateBridge(); bridge->Start(&callback); ProcessMessages(); // FIXME(brettw) when the request complete messages are actually handledo // and dispatched, uncomment this. //EXPECT_TRUE(callback.complete()); //EXPECT_STREQ(test_page_contents, callback.data().c_str()); delete bridge; } // Tests that the request IDs are straight when there are multiple requests. TEST_F(ResourceDispatcherTest, MultipleRequests) { // FIXME } // Tests that the cancel method prevents other messages from being received TEST_F(ResourceDispatcherTest, Cancel) { // FIXME } TEST_F(ResourceDispatcherTest, Cookies) { // FIXME } TEST_F(ResourceDispatcherTest, SerializedPostData) { // FIXME } // This class provides functionality to validate whether the ResourceDispatcher // object honors the deferred loading contract correctly, i.e. if deferred // loading is enabled it should queue up any responses received. If deferred // loading is enabled/disabled in the context of a dispatched message, other // queued messages should not be dispatched until deferred load is turned off. class DeferredResourceLoadingTest : public ResourceDispatcherTest, public ResourceLoaderBridge::Peer { public: DeferredResourceLoadingTest() : defer_loading_(false) { } virtual bool Send(IPC::Message* msg) { delete msg; return true; } void InitMessages() { set_defer_loading(true); ResourceResponseHead response_head; response_head.status.set_status(URLRequestStatus::SUCCESS); IPC::Message* response_message = new ViewMsg_Resource_ReceivedResponse(0, 0, response_head); dispatcher_->OnMessageReceived(*response_message); delete response_message; // Duplicate the shared memory handle so both the test and the callee can // close their copy. base::SharedMemoryHandle duplicated_handle; EXPECT_TRUE(shared_handle_.ShareToProcess(base::GetCurrentProcessHandle(), &duplicated_handle)); response_message = new ViewMsg_Resource_DataReceived(0, 0, duplicated_handle, 100); dispatcher_->OnMessageReceived(*response_message); delete response_message; set_defer_loading(false); } // ResourceLoaderBridge::Peer methods. virtual void OnReceivedResponse( const ResourceLoaderBridge::ResponseInfo& info, bool content_filtered) { EXPECT_EQ(defer_loading_, false); set_defer_loading(true); } virtual bool OnReceivedRedirect( const GURL& new_url, const ResourceLoaderBridge::ResponseInfo& info, bool* has_new_first_party_for_cookies, GURL* new_first_party_for_cookies) { *has_new_first_party_for_cookies = false; return true; } virtual void OnReceivedData(const char* data, int len) { EXPECT_EQ(defer_loading_, false); set_defer_loading(false); } virtual void OnUploadProgress(uint64 position, uint64 size) { } virtual void OnCompletedRequest(const URLRequestStatus& status, const std::string& security_info) { } virtual GURL GetURLForDebugging() const { return GURL(); } protected: virtual void SetUp() { EXPECT_EQ(true, shared_handle_.Create(L"DeferredResourceLoaderTest", false, false, 100)); ResourceDispatcherTest::SetUp(); } virtual void TearDown() { shared_handle_.Close(); ResourceDispatcherTest::TearDown(); } private: void set_defer_loading(bool defer) { defer_loading_ = defer; dispatcher_->SetDefersLoading(0, defer); } bool defer_loading() const { return defer_loading_; } bool defer_loading_; base::SharedMemory shared_handle_; }; TEST_F(DeferredResourceLoadingTest, DeferredLoadTest) { MessageLoop message_loop(MessageLoop::TYPE_IO); ResourceLoaderBridge* bridge = CreateBridge(); bridge->Start(this); InitMessages(); // Dispatch deferred messages. message_loop.RunAllPending(); delete bridge; } <|endoftext|>
<commit_before>#pragma once #include <vector> #include "base/helpers.hpp" #include "maths.hpp" struct maximal_element_search_tag {}; struct prime_modulo_calculations_tag {}; template<typename T> class Matrix { public: using RowStorage = std::vector<T>; using DataStorage = std::vector<RowStorage>; Matrix(const size_t rows_cnt, const size_t cols_cnt, const T mod = 1000000007) : rows_cnt_(rows_cnt), cols_cnt_(cols_cnt), data_(rows_cnt, RowStorage(cols_cnt, 0)), mod_(mod) {} Matrix() = delete; template<typename U> Matrix(const Matrix<U>& matrix) : rows_cnt_(matrix.rows_cnt()), cols_cnt_(matrix.cols_cnt()), data_(matrix.rows_cnt(), RowStorage(matrix.cols_cnt())) { for (size_t i = 0; i < rows_cnt_; ++i) { for (size_t j = 0; j < cols_cnt_; ++j) { data_[i][j] = static_cast<T>(matrix[i][j]); } } } size_t get_matrix_rank() const; size_t get_matrix_rank(maximal_element_search_tag) const; size_t get_matrix_rank(prime_modulo_calculations_tag, const T& mod) const; void swap_rows(const size_t i, const size_t j); void swap_cols(const size_t i, const size_t j); void shuffle(); void shuffle_cols(); void shuffle_rows(); typename DataStorage::iterator begin() { return data_.begin(); } typename DataStorage::const_iterator begin() const { return data_.begin(); } typename DataStorage::iterator end() { return data_.end(); } typename DataStorage::const_iterator end() const { return data_.end(); } RowStorage get_column(const size_t index) const { RowStorage column; column.reserve(rows_cnt_); for (const auto& row : data_) { column.emplace_back(row[index]); } return column; } RowStorage& operator[] (const size_t index) { return data_[index]; } const RowStorage& operator[] (const size_t index) const { return data_[index]; } size_t rows_cnt() const { return rows_cnt_; } size_t cols_cnt() const { return cols_cnt_; } Matrix operator *(const Matrix& rhs) const { Matrix result(rows_cnt_, rhs.cols_cnt_); for (size_t i = 0; i < rows_cnt_; i++) { for (size_t k = 0; k < rhs.cols_cnt_; k++) { for (size_t j = 0; j < rhs.rows_cnt_; j++) { result[i][k] += data_[i][j] * rhs[j][k]; } } } return result; } Matrix& operator *=(const Matrix& rhs) { Matrix result = operator *(rhs); swap(result); return *this; } template<typename U> Matrix binpow(U b) const { static_assert(std::is_integral<U>::value, "Degree must be integral. For real degree use pow."); Matrix ret = identity_matrix(rows_cnt_, cols_cnt_); Matrix a = *this; while (b != 0) { if ((b & 1) != 0) { ret *= a; } a *= a; b >>= 1; } return ret; } void swap(Matrix& rhs) { data_.swap(rhs.data_); std::swap(mod_, rhs.mod_); std::swap(rows_cnt_, rhs.rows_cnt_); std::swap(cols_cnt_, rhs.cols_cnt_); } static Matrix identity_matrix(const size_t rows_cnt, const size_t cols_cnt) { Matrix result(rows_cnt, cols_cnt); for (size_t i = 0; i < std::min(rows_cnt, cols_cnt); ++i) { result[i][i] = 1; } return result; } private: size_t rows_cnt_; size_t cols_cnt_; T mod_; DataStorage data_; }; template <typename T> size_t Matrix<T>::get_matrix_rank() const { Matrix<long double> tmp(*this); std::vector<bool> used(rows_cnt_, false); size_t rank = cols_cnt_; for (size_t col = 0; col < cols_cnt_; ++col) { size_t best_row = std::numeric_limits<size_t>::max(); for (size_t row = 0; row < rows_cnt_; ++row) { if (!used[row] && !is_equal_to_zero(tmp[row][col])) { best_row = row; break; } } if (best_row == std::numeric_limits<size_t>::max()) { --rank; continue; } used[best_row] = true; for (size_t j = col + 1; j < cols_cnt_; ++j) { tmp[best_row][j] /= tmp[best_row][col]; } for (size_t row = 0; row < rows_cnt_; ++row) { if (used[row] || is_equal_to_zero(tmp[row][col])) { continue; } for (size_t j = col + 1; j < cols_cnt_; ++j) { tmp[row][j] -= tmp[best_row][j] * tmp[row][col]; } } } return rank; } template <typename T> size_t Matrix<T>::get_matrix_rank(maximal_element_search_tag) const { Matrix<long double> tmp(*this); std::vector<bool> used(rows_cnt_, false); size_t rank = 0; for (size_t col = 0; col < cols_cnt_; ++col) { T max_value = EPS; size_t best_row = std::numeric_limits<size_t>::max(); for (size_t row = 0; row < rows_cnt_; ++row) { if (!used[row] && umax(max_value, abs(tmp[row][col]))) { best_row = row; } } if (best_row == std::numeric_limits<size_t>::max()) { continue; } ++rank; used[best_row] = true; for (size_t j = col + 1; j < cols_cnt_; ++j) { tmp[best_row][j] /= tmp[best_row][col]; } for (size_t row = 0; row < rows_cnt_; ++row) { if (used[row] || is_equal_to_zero(tmp[row][col])) { continue; } for (size_t j = col + 1; j < cols_cnt_; ++j) { tmp[row][j] -= tmp[best_row][j] * tmp[row][col]; } } } return rank; } template <typename T> size_t Matrix<T>::get_matrix_rank(prime_modulo_calculations_tag, const T& mod) const { static_assert(std::is_integral<T>::value, "Integral type required to process calculations by prime modulo"); Matrix<long long> tmp(*this); for (auto& row : tmp) { for (auto& col : row) { if (col < 0) { col += mod; } } } std::vector<bool> used(rows_cnt_, false); size_t rank = cols_cnt_; for (size_t col = 0; col < cols_cnt_; ++col) { size_t best_row = std::numeric_limits<size_t>::max(); for (size_t row = 0; row < rows_cnt_; ++row) { if (!used[row] && !is_equal_to_zero(tmp[row][col])) { best_row = row; break; } } if (best_row == std::numeric_limits<size_t>::max()) { --rank; continue; } used[best_row] = true; for (size_t j = col + 1; j < cols_cnt_; ++j) { mul_mod(tmp[best_row][j], inverseElement(tmp[best_row][col], mod), mod); } for (size_t row = 0; row < rows_cnt_; ++row) { if (used[row] || is_equal_to_zero(tmp[row][col])) { continue; } for (size_t j = col + 1; j < cols_cnt_; ++j) { long long x = tmp[best_row][j]; mul_mod(x, tmp[row][col], mod); sub_mod(tmp[row][j], x, mod); } } } return rank; } template<typename T> void Matrix<T>::swap_rows(const size_t i, const size_t j) { data_[i].swap(data_[j]); } template<typename T> void Matrix<T>::swap_cols(const size_t i, const size_t j) { for (auto& row : data_) { std::swap(row[i], row[j]); } } template<typename T> void Matrix<T>::shuffle_rows() { DataStorage tmp; tmp.reserve(rows_cnt_); std::vector<size_t> indices(rows_cnt_); for (size_t i = 0; i < rows_cnt_; ++i) { indices[i] = i; } std::random_shuffle(indices.begin(), indices.end()); for (const auto& index : indices) { tmp.emplace_back(data_[index]); } data_.swap(tmp); } template<typename T> void Matrix<T>::shuffle_cols() { DataStorage tmp(rows_cnt_, cols_cnt_); std::vector<size_t> indices(cols_cnt_); for (size_t i = 0; i < cols_cnt_; ++i) { indices[i] = i; } std::random_shuffle(indices.begin(), indices.end()); for (size_t j = 0; j < cols_cnt_; ++j) { size_t index = indices[j]; for (size_t row = 0; row < rows_cnt_; ++row) { tmp[row][j] = data_[row][index]; } } data_.swap(tmp); } template<typename T> void Matrix<T>::shuffle() { shuffle_rows(); shuffle_cols(); } <commit_msg>Refactored Matrix<> class.<commit_after>#pragma once #include <algorithm> #include <initializer_list> #include <stdexcept> #include <utility> #include <vector> #include "base/helpers.hpp" #include "is_equal_to_zero.hpp" #include "maths.hpp" #include "random.hpp" struct maximal_element_search_tag {}; struct prime_modulo_calculations_tag {}; template<typename T> class Matrix { public: using value_type = T; using size_type = std::size_t; using vector_container_type = std::vector<value_type>; using matrix_container_type = std::vector<vector_container_type>; Matrix(const size_type rows_cnt, const size_type cols_cnt, const value_type mod = 1000000007) : rows_cnt_(rows_cnt), cols_cnt_(cols_cnt), data_(rows_cnt, vector_container_type(cols_cnt, 0)), mod_(mod) {} explicit Matrix(const std::initializer_list<std::initializer_list<value_type>>& initializer_list, const value_type mod = 1000000007) : rows_cnt_(initializer_list.size()), cols_cnt_(0), mod_(mod) { data_.reserve(initializer_list.size()); for (const auto& row : initializer_list) { if (data_.empty()) { cols_cnt_ = row.size(); } else { if (cols_cnt_ != row.size()) { throw std::out_of_range("Matrix<T> initializer list must have rows of the same size"); } } data_.emplace_back(row); } } template<typename U> Matrix(const Matrix<U>& matrix) : rows_cnt_(matrix.rows_cnt()), cols_cnt_(matrix.cols_cnt()), data_(matrix.rows_cnt(), vector_container_type(matrix.cols_cnt())) { for (size_type i = 0; i < rows_cnt_; ++i) { for (size_type j = 0; j < cols_cnt_; ++j) { data_[i][j] = static_cast<value_type>(matrix[i][j]); } } } size_type get_matrix_rank() const; size_type get_matrix_rank(maximal_element_search_tag) const; size_type get_matrix_rank(prime_modulo_calculations_tag, const value_type& mod) const; void swap_rows(const size_type i, const size_type j) { data_[i].swap(data_[j]); } void swap_cols(const size_type i, const size_type j) { for (auto& row : data_) { std::swap(row[i], row[j]); } } void shuffle() { shuffle_rows(); shuffle_cols(); } void shuffle_cols() { matrix_container_type tmp(rows_cnt_, cols_cnt_); std::vector<size_type> indices(cols_cnt_); for (size_type i = 0; i < cols_cnt_; ++i) { indices[i] = i; } std::shuffle(indices.begin(), indices.end(), Random::random_engine()); for (size_type j = 0; j < cols_cnt_; ++j) { size_type index = indices[j]; for (size_type row = 0; row < rows_cnt_; ++row) { tmp[row][j] = data_[row][index]; } } data_.swap(tmp); } void shuffle_rows() { matrix_container_type tmp; tmp.reserve(rows_cnt_); std::vector<size_type> indices(rows_cnt_); for (size_type i = 0; i < rows_cnt_; ++i) { indices[i] = i; } std::shuffle(indices.begin(), indices.end(), Random::random_engine()); for (const auto& index : indices) { tmp.emplace_back(data_[index]); } data_.swap(tmp); } typename matrix_container_type::iterator begin() { return data_.begin(); } typename matrix_container_type::const_iterator begin() const { return data_.begin(); } typename matrix_container_type::iterator end() { return data_.end(); } typename matrix_container_type::const_iterator end() const { return data_.end(); } vector_container_type get_column(const size_type index) const { vector_container_type column; column.reserve(rows_cnt_); for (const auto& row : data_) { column.emplace_back(row[index]); } return column; } vector_container_type& operator [](const size_type index) { return data_[index]; } const vector_container_type& operator [](const size_type index) const { return data_[index]; } constexpr size_type rows_cnt() const { return rows_cnt_; } constexpr size_type cols_cnt() const { return cols_cnt_; } Matrix operator *(const Matrix& rhs) const { Matrix result(rows_cnt_, rhs.cols_cnt_); for (size_type i = 0; i < rows_cnt_; i++) { for (size_type k = 0; k < rhs.cols_cnt_; k++) { for (size_type j = 0; j < rhs.rows_cnt_; j++) { result[i][k] += data_[i][j] * rhs[j][k]; } } } return result; } Matrix& operator *=(const Matrix& rhs) { Matrix result = operator *(rhs); swap(result); return *this; } template<typename U> Matrix binpow(U b) const { static_assert(std::is_integral<U>::value, "Degree must be integral. For real degree use pow."); Matrix ret = identity_matrix(rows_cnt_, cols_cnt_); Matrix a = *this; while (b != 0) { if ((b & 1) != 0) { ret *= a; } a *= a; b >>= 1; } return ret; } void swap(Matrix& rhs) { data_.swap(rhs.data_); std::swap(mod_, rhs.mod_); std::swap(rows_cnt_, rhs.rows_cnt_); std::swap(cols_cnt_, rhs.cols_cnt_); } static Matrix identity_matrix(const size_type rows_cnt, const size_type cols_cnt) { Matrix result(rows_cnt, cols_cnt); for (size_type i = 0; i < std::min(rows_cnt, cols_cnt); ++i) { result[i][i] = 1; } return result; } private: size_type rows_cnt_; size_type cols_cnt_; value_type mod_; matrix_container_type data_; }; template <typename T> typename Matrix<T>::size_type Matrix<T>::get_matrix_rank() const { Matrix<long double> tmp(*this); std::vector<bool> used(rows_cnt_, false); size_type rank = cols_cnt_; for (size_type col = 0; col < cols_cnt_; ++col) { size_type best_row = std::numeric_limits<size_type>::max(); for (size_type row = 0; row < rows_cnt_; ++row) { if (!used[row] && !is_equal_to_zero(tmp[row][col])) { best_row = row; break; } } if (best_row == std::numeric_limits<size_type>::max()) { --rank; continue; } used[best_row] = true; for (size_type j = col + 1; j < cols_cnt_; ++j) { tmp[best_row][j] /= tmp[best_row][col]; } for (size_type row = 0; row < rows_cnt_; ++row) { if (used[row] || is_equal_to_zero(tmp[row][col])) { continue; } for (size_type j = col + 1; j < cols_cnt_; ++j) { tmp[row][j] -= tmp[best_row][j] * tmp[row][col]; } } } return rank; } template <typename T> typename Matrix<T>::size_type Matrix<T>::get_matrix_rank(maximal_element_search_tag) const { Matrix<long double> tmp(*this); std::vector<bool> used(rows_cnt_, false); size_type rank = 0; for (size_type col = 0; col < cols_cnt_; ++col) { value_type max_value = EPS; size_type best_row = std::numeric_limits<size_type>::max(); for (size_type row = 0; row < rows_cnt_; ++row) { if (!used[row] && umax(max_value, abs(tmp[row][col]))) { best_row = row; } } if (best_row == std::numeric_limits<size_type>::max()) { continue; } ++rank; used[best_row] = true; for (size_type j = col + 1; j < cols_cnt_; ++j) { tmp[best_row][j] /= tmp[best_row][col]; } for (size_type row = 0; row < rows_cnt_; ++row) { if (used[row] || is_equal_to_zero(tmp[row][col])) { continue; } for (size_type j = col + 1; j < cols_cnt_; ++j) { tmp[row][j] -= tmp[best_row][j] * tmp[row][col]; } } } return rank; } template <typename T> typename Matrix<T>::size_type Matrix<T>::get_matrix_rank(prime_modulo_calculations_tag, const value_type& mod) const { static_assert(std::is_integral<value_type>::value, "Integral type required to process calculations by prime modulo"); Matrix<long long> tmp(*this); for (auto& row : tmp) { for (auto& col : row) { if (col < 0) { col += mod; } } } std::vector<bool> used(rows_cnt_, false); size_type rank = cols_cnt_; for (size_type col = 0; col < cols_cnt_; ++col) { size_type best_row = std::numeric_limits<size_type>::max(); for (size_type row = 0; row < rows_cnt_; ++row) { if (!used[row] && !is_equal_to_zero(tmp[row][col])) { best_row = row; break; } } if (best_row == std::numeric_limits<size_type>::max()) { --rank; continue; } used[best_row] = true; for (size_type j = col + 1; j < cols_cnt_; ++j) { mul_mod(tmp[best_row][j], inverseElement(tmp[best_row][col], mod), mod); } for (size_type row = 0; row < rows_cnt_; ++row) { if (used[row] || is_equal_to_zero(tmp[row][col])) { continue; } for (size_type j = col + 1; j < cols_cnt_; ++j) { long long x = tmp[best_row][j]; mul_mod(x, tmp[row][col], mod); sub_mod(tmp[row][j], x, mod); } } } return rank; } <|endoftext|>
<commit_before>#include <set> #include <fstream> #include <queue> #include <functional> namespace cpr { namespace huffman { template<typename Freq> struct Node { Node() : character_{ 0 }, freq_{ 0 }, left_{ nullptr }, right_{ nullptr } { } Node(Node<Freq> const& other) : character_{ other.character_ }, freq_{ other.freq_ }, left_{ other.left_ }, right_{other.right_} { } unsigned char character_; Freq freq_; Node* left_, right_; }; template<typename Freq> inline bool operator > (Node<Freq> const& lhs, Node<Freq> const& rhs) { return lhs.freq_ > rhs.freq_; } template<typename Freq> class Set : public std::set<Node<Freq>> { }; template<typename Freq> Node<Freq> make_huffman_tree(Set<Node<Freq>> const& set) { using MinPreorityQuee = std::priority_queue < Node<Freq>, std::vector<Node<Freq>>, std::greater<Node<Freq>> > ; MinPreorityQuee queue; for (auto const& node : set) queue.push(node); for (int _ = 1; _ != set.size(); ++_) { Node<Freq> node; } } } }<commit_msg> modified: cpr/huffman/CharSet.hpp<commit_after>#include <set> #include <fstream> #include <queue> #include <functional> namespace cpr { namespace huffman { template<typename Freq> struct Node { Node() : character_{ 0 }, freq_{ 0 }, left_{ nullptr }, right_{ nullptr } { } Node(Node<Freq> const& other) : character_{ other.character_ }, freq_{ other.freq_ }, left_{ other.left_ }, right_{other.right_} { } unsigned char character_; Freq freq_; Node* left_, right_; }; template<typename Freq> inline bool operator > (Node<Freq> const& lhs, Node<Freq> const& rhs) { return lhs.freq_ > rhs.freq_; } template<typename Freq> class Set : public std::set<Node<Freq>> { }; template<typename Freq> Node<Freq> make_huffman_tree(Set<Node<Freq>> const& set) { using MinPreorityQuee = std::priority_queue < Node<Freq>, std::vector<Node<Freq>>, std::greater<Node<Freq>> > ; MinPreorityQuee queue; for (auto const& node : set) queue.push(node); for (int _ = 1; _ != set.size(); ++_) { Node<Freq> z; auto x = new Node<Freq>(queue.top()); queue.pop(); auto y = new Node<Freq>(queue.top()); queue.pop(); z.left_ = x, z.right_ = y; z.freq_ = x->freq_ + y->freq_; queue.push(z); } return queue.top(); } } }<|endoftext|>
<commit_before>/************************************************************************* > File Name: ruleOfFive.cpp > Author: Chan-Ho Chris Ohk > E-mail: utilForever@gmail.com, utilForever@kaist.ac.kr > Created Time: 2015/4/26 > Personal Blog: https://github.com/utilForever ************************************************************************/ #include <utility> class Resource { private: int x = 0; }; class RO3 { private: Resource* pResource; }; class RO5 { private: Resource* pResource; public: RO5() : pResource{ new Resource{} } { } RO5(const RO5& rhs) : pResource{ new Resource(*(rhs.pResource)) } { } RO5(RO5&& rhs) : pResource{ rhs.pResource } { rhs.pResource = nullptr; } RO5& operator=(const RO5& rhs) { if (&rhs != this) { delete pResource; pResource = nullptr; pResource = new Resource(*(rhs.pResource)); } return *this; } RO5& operator=(RO5&& rhs) { if (&rhs != this) { delete pResource; pResource = rhs.pResource; rhs.pResource = nullptr; } return *this; } ~RO5() { delete pResource; } };<commit_msg>Update Rule of Five Example<commit_after>/************************************************************************* > File Name: ruleOfFive.cpp > Author: Chan-Ho Chris Ohk > E-mail: utilForever@gmail.com, utilForever@kaist.ac.kr > Created Time: 2015/4/26 > Personal Blog: https://github.com/utilForever > References: http://www.cppsamples.com/common-tasks/rule-of-five.html ************************************************************************/ // Safely and efficiently implement RAII to encapsulate the management of dynamically allocated resources. // RAII = Resource Allocation is Initialization. class Resource { private: int x = 0; }; // In C++98, the rule of three specifies that if a class implements any of the following functions, // it should implement all of them: copy constructor, copy assignment operator, destructor. // These functions are usually required only when a class is manually managing a dynamically allocated resource, // and so all of them must be implemented to manage the resource safely. class RO3 { private: Resource* pResource; public: // Dynamically allocates a Resource object in its constructor. RO3() : pResource{ new Resource{} } { } // The implementations of RO3's copy constructor, copy assignment operator, and destructor ensure that // the lifetime of this resource is safely managed by RO3 object that contains it, even in the event of an exception. // Copy constructor RO3(const RO3& rhs) : pResource{ new Resource(*(rhs.pResource)) } { } // Copy assignment operator RO3& operator=(const RO3& rhs) { if (&rhs != this) { delete pResource; pResource = nullptr; pResource = new Resource(*(rhs.pResource)); } return *this; } // Destructor ~RO3() { delete pResource; } }; // In C++11, the rule of five identifies that it usually appropriate to also provide the following functions // to allow for optimized from temporary objects: move constructor, move assignment operator. class RO5 { private: Resource* pResource; public: RO5() : pResource{ new Resource{} } { } RO5(const RO5& rhs) : pResource{ new Resource(*(rhs.pResource)) } { } // We have also implemented a move constructor and move assignment operator that provide // optimized copies from temporary objects. // Rather than copy the resource, they take the resource from the original RO5 and // set its internal pointer to nullptr, effectively stealing the resource. RO5(RO5&& rhs) : pResource{ rhs.pResource } { rhs.pResource = nullptr; } // Note: The copy and move assignment operators in this example provide only basic exception safety. // They may alternatively be implemented with the copy-and-swap idiom (copyAndSwap.cpp), // which provides strong exception safety at an optimization cost. RO5& operator=(const RO5& rhs) { if (&rhs != this) { delete pResource; pResource = nullptr; pResource = new Resource(*(rhs.pResource)); } return *this; } RO5& operator=(RO5&& rhs) { if (&rhs != this) { delete pResource; pResource = rhs.pResource; rhs.pResource = nullptr; } return *this; } ~RO5() { delete pResource; } }; // Note: We can typically avoid manual memory management and having to write // the copy constructor, assignment operator, and destructor entirely by using the rule of zero (ruleOfZero.cpp). int main(int argc, char* argv[]) { RO3 ro3; RO5 ro5; return 0; }<|endoftext|>
<commit_before>#include "ITSModule.h" #include <AliITSdigitSPD.h> #include <AliITSdigitSDD.h> #include <AliITSdigitSSD.h> #include <TStyle.h> using namespace Reve; using namespace Alieve; using namespace std; Short_t ITSModule::fgSDDThreshold = 5; Short_t ITSModule::fgSDDMaxVal = 80; Short_t ITSModule::fgSSDThreshold = 2; Short_t ITSModule::fgSSDMaxVal = 100; ClassImp(ITSModule) /**************************************************************************/ ITSModule::ITSModule(const Text_t* n, const Text_t* t, Color_t col) : Reve::RenderElement(fFrameColor), QuadSet(n, t), fInfo(0), fID(-1), fDetID(-1), fLayer(-1), fLadder(-1), fDet(-1), fDx(0), fDz(0), fDy(0), fFrameColor(col) {} ITSModule::ITSModule(Int_t id, ITSDigitsInfo* info, Color_t col) : Reve::RenderElement(fFrameColor), QuadSet(Form("ITS module %d", id)), fInfo (0), fID(-1), fDetID(-1), fLayer(-1), fLadder(-1), fDet(-1), fDx(0), fDz(0), fDy(0), fFrameColor(col) { SetDigitsInfo(info); SetID(id); } ITSModule::~ITSModule() { if(fInfo) fInfo->DecRefCount(); } /**************************************************************************/ void ITSModule::SetMainColor(Color_t col) { Reve::RenderElement::SetMainColor(col); if(!fQuads.empty()) { fQuads.front().ColorFromIdx(col); } } /**************************************************************************/ void ITSModule::SetDigitsInfo(ITSDigitsInfo* info) { if(fInfo) fInfo->DecRefCount(); fInfo = info; if(fInfo) fInfo->IncRefCount(); } void ITSModule::SetID(Int_t id) { static const Exc_t eH("ITSModule::SetID "); if(fInfo == 0) throw(eH + "ITSDigitsInfo not set."); if (id < fInfo->fGeom->GetStartSPD() || id > fInfo->fGeom->GetLastSSD()) throw(eH + Form("%d is not valid. ID range from %d to %d", id, fInfo->fGeom->GetStartSPD(), fInfo->fGeom->GetLastSSD())); fID = id; InitModule(); } /**************************************************************************/ void ITSModule::InitModule() { fInfo->fGeom->GetModuleId(fID,fLayer,fLadder,fDet); SetName(Form("ITSModule %d", fID)); if (fID <= fInfo->fGeom->GetLastSPD()) { fDetID = 0; fDx = fInfo->fSegSPD->Dx()*0.00005; fDz = 3.48; fDy = fInfo->fSegSPD->Dy()*0.00005; } else if (fID <= fInfo->fGeom->GetLastSDD()) { fDetID = 1; fDx = fInfo->fSegSDD->Dx()*0.0001; fDz = fInfo->fSegSDD->Dz()*0.00005; fDy = fInfo->fSegSDD->Dy()*0.00005; } else { fDetID = 2; fInfo->fSegSSD->SetLayer(fLayer); fDx = fInfo->fSegSSD->Dx()*0.00005; fDz = fInfo->fSegSSD->Dz()*0.00005; fDy = fInfo->fSegSSD->Dy()*0.00005; } LoadQuads(); ComputeBBox(); SetTrans(); } void ITSModule::LoadQuads() { // printf("its module load quads \n"); Float_t x = fDx; Float_t z = fDz; Bool_t aboveThreshold = false; // Module frame in xy plane fQuads.push_back(Reve::Quad(fFrameColor)); Float_t dy = -0.; Float_t* p = fQuads.back().vertices; p[0] = -x; p[1] = dy; p[2] = -z; p[3] = -x; p[4] = dy; p[5] = z; p[6] = x; p[7] = dy; p[8] = z; p[9] = x; p[10] = dy; p[11] = -z; // Digits TClonesArray *digits; Int_t ndigits; Float_t dpx,dpz; Int_t i,j; digits = fInfo->GetDigits(fID, fDetID ); ndigits = digits->GetEntriesFast(); Int_t n_col = gStyle->GetNumberOfColors(); switch(fDetID) { case 0: { // SPD aboveThreshold = true; AliITSsegmentationSPD* seg = fInfo->fSegSPD; AliITSdigitSPD *d=0; for (Int_t k=0; k<ndigits; k++) { d=(AliITSdigitSPD*)digits->UncheckedAt(k); j = d->GetCoord1(); i = d->GetCoord2(); x = -seg->Dx()/2 + seg->Dpx(0) *i; x *= 0.0001; fInfo->GetSPDLocalZ(j,z); dpx = seg->Dpx(i)*0.0001; dpz = seg->Dpz(j)*0.0001; fQuads.push_back(Reve::Quad(7)); Float_t* p = fQuads.back().vertices; p[0] = x; p[1] = 0.; p[2] = z; p[3] = x; p[4] = 0.; p[5] = z + dpz; p[6] = x + dpx; p[7] = 0.; p[8] = z + dpz; p[9] = x + dpx; p[10] =0.; p[11] = z; } break; } case 1: { // SDD AliITSsegmentationSDD* seg = fInfo->fSegSDD; AliITSdigitSDD *d=0; x = 2*fDx; z = 2*fDz; for (Int_t k=0; k<ndigits; k++) { d=(AliITSdigitSDD*)digits->UncheckedAt(k); if (d->GetSignal() > fgSDDThreshold) { j = d->GetCoord1(); i = d->GetCoord2(); aboveThreshold = true; seg->DetToLocal(i,j,x,z); dpx = seg->Dpx(i)*0.0001; dpz = seg->Dpz(j)*0.0001; Int_t ci = gStyle->GetColorPalette (TMath::Min(n_col - 1, (n_col*(d->GetSignal() - fgSDDThreshold))/(fgSDDMaxVal - fgSDDThreshold))); fQuads.push_back(Reve::Quad(ci, p)); Float_t* p = fQuads.back().vertices; p[0] = x; p[1] = 0.; p[2] = z; p[3] = x; p[4] = 0.; p[5] = z + dpz; p[6] = x + dpx; p[7] = 0.; p[8] = z + dpz; p[9] = x + dpx; p[10] =0.; p[11] = z; } } break; } case 2: { // SSD AliITSsegmentationSSD* seg = fInfo->fSegSSD; AliITSdigitSSD *d=0; Float_t ap,an,a; seg->Angles(ap,an); for (Int_t k=0; k<ndigits; k++) { d=(AliITSdigitSSD*)digits->UncheckedAt(k); if(d->GetSignal() > fgSSDThreshold){ aboveThreshold = true; j = d->GetCoord1(); i = d->GetCoord2(); seg->DetToLocal(i,j,x,z); if( d->GetCoord1() == 1) { a = ap; } else { a = -an; } fQuads.push_back(Reve::Quad()); Int_t ci = gStyle->GetColorPalette (TMath::Min(n_col - 1, (n_col*(d->GetSignal() - fgSSDThreshold))/(fgSSDMaxVal - fgSSDThreshold))); fQuads.back().ColorFromIdx(ci); Float_t* p = fQuads.back().vertices; p[0] = x-TMath::Tan(a)*fDz; p[1] = 0; p[2] = -fDz; p[3] = x+TMath::Tan(a)*fDz; p[4] = 0; p[5] = fDz ; p[6] = x+TMath::Tan(a)*fDz; p[7] = 0; p[8] = fDz ; p[9] = x-TMath::Tan(a)*fDz; p[10] = 0; p[11] = -fDz; // printf("%3d -> %3d -> %8x\n", d->GetSignal(), ci, fQuads.back().color); } } break; } } } /**************************************************************************/ void ITSModule::SetTrans() { Double_t pos[3]; Double_t rot[9]; fInfo->fGeom->GetTrans(fID,pos); fInfo->fGeom->GetRotMatrix(fID,rot); Double_t *s, *d; // column major ii s = &rot[0]; d = &fMatrix[0]; d[0] = s[0]; d[1] = s[3]; d[2] = s[6]; d[3] = 0; s = &rot[1]; d = &fMatrix[4]; d[0] = s[0]; d[1] = s[3]; d[2] = s[6]; d[3] = 0; s = &rot[2]; d = &fMatrix[8]; d[0] = s[0]; d[1] = s[3]; d[2] = s[6]; d[3] = 0; s = &pos[0]; d = &fMatrix[12]; d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; d[3] = 1; fTrans = true; } /**************************************************************************/ void ITSModule::Print(Option_t* ) const { printf("ID %d, layer %d, ladder %d, det %d \n", fID, fLayer, fLadder, fDetID); } <commit_msg>From Raffaele: implemented naming scheme used for alignable volumes.<commit_after>#include "ITSModule.h" #include <AliITSdigitSPD.h> #include <AliITSdigitSDD.h> #include <AliITSdigitSSD.h> #include <TStyle.h> using namespace Reve; using namespace Alieve; using namespace std; Short_t ITSModule::fgSDDThreshold = 5; Short_t ITSModule::fgSDDMaxVal = 80; Short_t ITSModule::fgSSDThreshold = 2; Short_t ITSModule::fgSSDMaxVal = 100; ClassImp(ITSModule) /**************************************************************************/ ITSModule::ITSModule(const Text_t* n, const Text_t* t, Color_t col) : Reve::RenderElement(fFrameColor), QuadSet(n, t), fInfo(0), fID(-1), fDetID(-1), fLayer(-1), fLadder(-1), fDet(-1), fDx(0), fDz(0), fDy(0), fFrameColor(col) {} ITSModule::ITSModule(Int_t id, ITSDigitsInfo* info, Color_t col) : Reve::RenderElement(fFrameColor), QuadSet(Form("ITS module %d", id)), fInfo (0), fID(-1), fDetID(-1), fLayer(-1), fLadder(-1), fDet(-1), fDx(0), fDz(0), fDy(0), fFrameColor(col) { SetDigitsInfo(info); SetID(id); } ITSModule::~ITSModule() { if(fInfo) fInfo->DecRefCount(); } /**************************************************************************/ void ITSModule::SetMainColor(Color_t col) { Reve::RenderElement::SetMainColor(col); if(!fQuads.empty()) { fQuads.front().ColorFromIdx(col); } } /**************************************************************************/ void ITSModule::SetDigitsInfo(ITSDigitsInfo* info) { if(fInfo) fInfo->DecRefCount(); fInfo = info; if(fInfo) fInfo->IncRefCount(); } void ITSModule::SetID(Int_t id) { static const Exc_t eH("ITSModule::SetID "); if(fInfo == 0) throw(eH + "ITSDigitsInfo not set."); if (id < fInfo->fGeom->GetStartSPD() || id > fInfo->fGeom->GetLastSSD()) throw(eH + Form("%d is not valid. ID range from %d to %d", id, fInfo->fGeom->GetStartSPD(), fInfo->fGeom->GetLastSSD())); fID = id; InitModule(); } /**************************************************************************/ void ITSModule::InitModule() { fInfo->fGeom->GetModuleId(fID,fLayer,fLadder,fDet); TString strLadder = "Ladder"; TString strSensor = "Sensor"; TString symname; Int_t id, nsector, nstave, nladder, rest; if (fID <= fInfo->fGeom->GetLastSPD()) { symname+=strLadder; if (fID<80) { nsector = fID/8; rest=fID-nsector*8; nstave=1; if (rest<4) nstave=0; rest-=nstave*4; symname+=rest; SetName(symname.Data()); fDetID = 0; fDx = fInfo->fSegSPD->Dx()*0.00005; fDz = 3.48; fDy = fInfo->fSegSPD->Dy()*0.00005; } else { id=fID-80; nsector = id/8; rest=id-nsector*8; nstave=1; if (rest<4) nstave=0; rest-=nstave*4; symname+=rest; SetName(symname.Data()); fDetID = 0; fDx = fInfo->fSegSPD->Dx()*0.00005; fDz = 3.48; fDy = fInfo->fSegSPD->Dy()*0.00005; fDetID = 0; fDx = fInfo->fSegSPD->Dx()*0.00005; fDz = 3.48; fDy = fInfo->fSegSPD->Dy()*0.00005; } } else if (fID <= fInfo->fGeom->GetLastSDD()) { symname+=strSensor; if (fID<324) { id = fID-240; nladder = id/6; rest=id-nladder*6; symname+=rest; SetName(symname.Data()); fDetID = 1; fDx = fInfo->fSegSDD->Dx()*0.0001; fDz = fInfo->fSegSDD->Dz()*0.00005; fDy = fInfo->fSegSDD->Dy()*0.00005; } else { id = fID-324; nladder = id/8; rest=id-nladder*8; symname+=rest; SetName(symname.Data()); fDetID = 1; fDx = fInfo->fSegSDD->Dx()*0.0001; fDz = fInfo->fSegSDD->Dz()*0.00005; fDy = fInfo->fSegSDD->Dy()*0.00005; } } else { symname+=strSensor; if (fID<1248) { id = fID-500; nladder = id/22; rest=id-nladder*22; symname+=rest; SetName(symname.Data()); fDetID = 2; fInfo->fSegSSD->SetLayer(fLayer); fDx = fInfo->fSegSSD->Dx()*0.00005; fDz = fInfo->fSegSSD->Dz()*0.00005; fDy = fInfo->fSegSSD->Dy()*0.00005; } else { id = fID-1248; nladder = id/25; rest=id-nladder*25; symname+=rest; SetName(symname.Data()); fDetID = 2; fInfo->fSegSSD->SetLayer(fLayer); fDx = fInfo->fSegSSD->Dx()*0.00005; fDz = fInfo->fSegSSD->Dz()*0.00005; fDy = fInfo->fSegSSD->Dy()*0.00005; } } LoadQuads(); ComputeBBox(); SetTrans(); } void ITSModule::LoadQuads() { // printf("its module load quads \n"); Float_t x = fDx; Float_t z = fDz; Bool_t aboveThreshold = false; // Module frame in xy plane fQuads.push_back(Reve::Quad(fFrameColor)); Float_t dy = -0.; Float_t* p = fQuads.back().vertices; p[0] = -x; p[1] = dy; p[2] = -z; p[3] = -x; p[4] = dy; p[5] = z; p[6] = x; p[7] = dy; p[8] = z; p[9] = x; p[10] = dy; p[11] = -z; // Digits TClonesArray *digits; Int_t ndigits; Float_t dpx,dpz; Int_t i,j; digits = fInfo->GetDigits(fID, fDetID ); ndigits = digits->GetEntriesFast(); Int_t n_col = gStyle->GetNumberOfColors(); switch(fDetID) { case 0: { // SPD aboveThreshold = true; AliITSsegmentationSPD* seg = fInfo->fSegSPD; AliITSdigitSPD *d=0; for (Int_t k=0; k<ndigits; k++) { d=(AliITSdigitSPD*)digits->UncheckedAt(k); j = d->GetCoord1(); i = d->GetCoord2(); x = -seg->Dx()/2 + seg->Dpx(0) *i; x *= 0.0001; fInfo->GetSPDLocalZ(j,z); dpx = seg->Dpx(i)*0.0001; dpz = seg->Dpz(j)*0.0001; fQuads.push_back(Reve::Quad(7)); Float_t* p = fQuads.back().vertices; p[0] = x; p[1] = 0.; p[2] = z; p[3] = x; p[4] = 0.; p[5] = z + dpz; p[6] = x + dpx; p[7] = 0.; p[8] = z + dpz; p[9] = x + dpx; p[10] =0.; p[11] = z; } break; } case 1: { // SDD AliITSsegmentationSDD* seg = fInfo->fSegSDD; AliITSdigitSDD *d=0; x = 2*fDx; z = 2*fDz; for (Int_t k=0; k<ndigits; k++) { d=(AliITSdigitSDD*)digits->UncheckedAt(k); if (d->GetSignal() > fgSDDThreshold) { j = d->GetCoord1(); i = d->GetCoord2(); aboveThreshold = true; seg->DetToLocal(i,j,x,z); dpx = seg->Dpx(i)*0.0001; dpz = seg->Dpz(j)*0.0001; Int_t ci = gStyle->GetColorPalette (TMath::Min(n_col - 1, (n_col*(d->GetSignal() - fgSDDThreshold))/(fgSDDMaxVal - fgSDDThreshold))); fQuads.push_back(Reve::Quad(ci, p)); Float_t* p = fQuads.back().vertices; p[0] = x; p[1] = 0.; p[2] = z; p[3] = x; p[4] = 0.; p[5] = z + dpz; p[6] = x + dpx; p[7] = 0.; p[8] = z + dpz; p[9] = x + dpx; p[10] =0.; p[11] = z; } } break; } case 2: { // SSD AliITSsegmentationSSD* seg = fInfo->fSegSSD; AliITSdigitSSD *d=0; Float_t ap,an,a; seg->Angles(ap,an); for (Int_t k=0; k<ndigits; k++) { d=(AliITSdigitSSD*)digits->UncheckedAt(k); if(d->GetSignal() > fgSSDThreshold){ aboveThreshold = true; j = d->GetCoord1(); i = d->GetCoord2(); seg->DetToLocal(i,j,x,z); if( d->GetCoord1() == 1) { a = ap; } else { a = -an; } fQuads.push_back(Reve::Quad()); Int_t ci = gStyle->GetColorPalette (TMath::Min(n_col - 1, (n_col*(d->GetSignal() - fgSSDThreshold))/(fgSSDMaxVal - fgSSDThreshold))); fQuads.back().ColorFromIdx(ci); Float_t* p = fQuads.back().vertices; p[0] = x-TMath::Tan(a)*fDz; p[1] = 0; p[2] = -fDz; p[3] = x+TMath::Tan(a)*fDz; p[4] = 0; p[5] = fDz ; p[6] = x+TMath::Tan(a)*fDz; p[7] = 0; p[8] = fDz ; p[9] = x-TMath::Tan(a)*fDz; p[10] = 0; p[11] = -fDz; // printf("%3d -> %3d -> %8x\n", d->GetSignal(), ci, fQuads.back().color); } } break; } } } /**************************************************************************/ void ITSModule::SetTrans() { Double_t pos[3]; Double_t rot[9]; fInfo->fGeom->GetTrans(fID,pos); fInfo->fGeom->GetRotMatrix(fID,rot); Double_t *s, *d; // column major ii s = &rot[0]; d = &fMatrix[0]; d[0] = s[0]; d[1] = s[3]; d[2] = s[6]; d[3] = 0; s = &rot[1]; d = &fMatrix[4]; d[0] = s[0]; d[1] = s[3]; d[2] = s[6]; d[3] = 0; s = &rot[2]; d = &fMatrix[8]; d[0] = s[0]; d[1] = s[3]; d[2] = s[6]; d[3] = 0; s = &pos[0]; d = &fMatrix[12]; d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; d[3] = 1; fTrans = true; } /**************************************************************************/ void ITSModule::Print(Option_t* ) const { printf("ID %d, layer %d, ladder %d, det %d \n", fID, fLayer, fLadder, fDetID); } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_posh/iceoryx_posh_types.hpp" #include "iceoryx_posh/internal/popo/ports/publisher_port_roudi.hpp" #include "iceoryx_posh/internal/popo/ports/publisher_port_user.hpp" #include "iceoryx_posh/internal/popo/ports/subscriber_port_multi_producer.hpp" #include "iceoryx_posh/internal/popo/ports/subscriber_port_single_producer.hpp" #include "iceoryx_posh/internal/popo/ports/subscriber_port_user.hpp" #include "iceoryx_posh/mepoo/mepoo_config.hpp" #include "iceoryx_posh/popo/wait_set.hpp" #include "iceoryx_utils/cxx/generic_raii.hpp" #include "iceoryx_utils/error_handling/error_handling.hpp" #include "iceoryx_utils/internal/concurrent/smart_lock.hpp" #include "test.hpp" #include <chrono> #include <sstream> #include <thread> using namespace ::testing; using namespace iox::popo; using namespace iox::capro; using namespace iox::cxx; using namespace iox::mepoo; using namespace iox::posix; using ::testing::Return; struct DummySample { uint64_t m_dummy{42}; }; static const ServiceDescription TEST_SERVICE_DESCRIPTION("x", "y", "z"); static const iox::ProcessName_t TEST_SUBSCRIBER_APP_NAME("mySubscriberApp"); static const iox::ProcessName_t TEST_PUBLISHER_APP_NAME("myPublisherApp"); static constexpr uint32_t NUMBER_OF_PUBLISHERS = 42; static constexpr uint32_t ITERATIONS = 1000; static constexpr uint32_t NUM_CHUNKS_IN_POOL = NUMBER_OF_PUBLISHERS * 3 * iox::MAX_RECEIVER_QUEUE_CAPACITY; static constexpr uint32_t SMALL_CHUNK = 128; static constexpr uint32_t CHUNK_META_INFO_SIZE = 256; static constexpr size_t MEMORY_SIZE = NUM_CHUNKS_IN_POOL * (SMALL_CHUNK + CHUNK_META_INFO_SIZE); alignas(64) static uint8_t g_memory[MEMORY_SIZE]; class PortUser_IntegrationTest : public Test { public: PortUser_IntegrationTest() { m_mempoolConfig.addMemPool({SMALL_CHUNK, NUM_CHUNKS_IN_POOL}); m_memoryManager.configureMemoryManager(m_mempoolConfig, &m_memoryAllocator, &m_memoryAllocator); } ~PortUser_IntegrationTest() { } void SetUp() { for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++) { std::stringstream publisherAppName; publisherAppName << TEST_PUBLISHER_APP_NAME << i; iox::cxx::string<100> processName(TruncateToCapacity, publisherAppName.str().c_str()); m_publisherPortDataVector.emplace_back(TEST_SERVICE_DESCRIPTION, processName, &m_memoryManager); m_publisherUserSideVector.emplace_back(&m_publisherPortDataVector.back()); m_publisherRouDiSideVector.emplace_back(&m_publisherPortDataVector.back()); } } void TearDown() { m_publisherUserSide.stopOffer(); m_subscriberPortUserSingleProducer.unsubscribe(); m_subscriberPortUserMultiProducer.unsubscribe(); static_cast<void>(m_publisherRouDiSide.getCaProMessage()); static_cast<void>(m_subscriberPortRouDiSideSingleProducer.getCaProMessage()); static_cast<void>(m_subscriberPortRouDiMultiSingleProducer.getCaProMessage()); if (m_subscriberPortUserSingleProducer.isConditionVariableAttached()) { static_cast<void>(m_subscriberPortUserSingleProducer.detachConditionVariable()); } if (m_subscriberPortUserMultiProducer.isConditionVariableAttached()) { static_cast<void>(m_subscriberPortUserMultiProducer.detachConditionVariable()); } m_waiter.reset(); } GenericRAII m_uniqueRouDiId{[] { iox::popo::internal::setUniqueRouDiId(0); }, [] { iox::popo::internal::unsetUniqueRouDiId(); }}; std::atomic<uint64_t> m_sendCounter{0}; uint64_t m_receiveCounter{0}; std::atomic<bool> m_publisherRun{true}; // Memory objects Allocator m_memoryAllocator{g_memory, MEMORY_SIZE}; MePooConfig m_mempoolConfig; MemoryManager m_memoryManager; ConditionVariableData m_condVarData; ConditionVariableWaiter m_waiter{&m_condVarData}; using ConcurrentCaproMessageVector_t = iox::concurrent::smart_lock<vector<CaproMessage, 1>>; ConcurrentCaproMessageVector_t m_concurrentCaproMessageVector; iox::concurrent::smart_lock<vector<CaproMessage, 1>> m_caproMessageRx; // subscriber port for single producer SubscriberPortData m_subscriberPortDataSingleProducer{ TEST_SERVICE_DESCRIPTION, TEST_SUBSCRIBER_APP_NAME, VariantQueueTypes::SoFi_SingleProducerSingleConsumer}; SubscriberPortUser m_subscriberPortUserSingleProducer{&m_subscriberPortDataSingleProducer}; SubscriberPortSingleProducer m_subscriberPortRouDiSideSingleProducer{&m_subscriberPortDataSingleProducer}; // subscriber port for multi producer SubscriberPortData m_subscriberPortDataMultiProducer{ TEST_SERVICE_DESCRIPTION, TEST_SUBSCRIBER_APP_NAME, VariantQueueTypes::SoFi_MultiProducerSingleConsumer}; SubscriberPortUser m_subscriberPortUserMultiProducer{&m_subscriberPortDataMultiProducer}; SubscriberPortMultiProducer m_subscriberPortRouDiMultiSingleProducer{&m_subscriberPortDataMultiProducer}; // publisher port w/o history PublisherPortData m_publisherPortData{TEST_SERVICE_DESCRIPTION, TEST_PUBLISHER_APP_NAME, &m_memoryManager}; PublisherPortUser m_publisherUserSide{&m_publisherPortData}; PublisherPortRouDi m_publisherRouDiSide{&m_publisherPortData}; vector<PublisherPortData, NUMBER_OF_PUBLISHERS> m_publisherPortDataVector; vector<PublisherPortUser, NUMBER_OF_PUBLISHERS> m_publisherUserSideVector; vector<PublisherPortRouDi, NUMBER_OF_PUBLISHERS> m_publisherRouDiSideVector; inline CaproMessage waitForCaproMessage(const ConcurrentCaproMessageVector_t& concurrentCaproMessageVector, const CaproMessageType& caproMessageType) { bool finished{false}; CaproMessage caproMessage; do { std::this_thread::sleep_for(std::chrono::microseconds(10)); { auto guardedVector = concurrentCaproMessageVector.GetScopeGuard(); if (guardedVector->size() != 0) { caproMessage = guardedVector->back(); if (caproMessage.m_type == caproMessageType) { guardedVector->pop_back(); finished = true; } } } } while (!finished); return caproMessage; } template <typename SubscriberPortProducerType> void subscriberThread(SubscriberPortProducerType& subscriberPortProducer, SubscriberPortUser& subscriberPortUser) { bool finished{false}; optional<CaproMessage> maybeCaproMessage; CaproMessage caproMessage; subscriberPortUser.attachConditionVariable(&m_condVarData); // Wait for publisher to be ready caproMessage = waitForCaproMessage(m_concurrentCaproMessageVector, CaproMessageType::OFFER); // Subscribe to publisher subscriberPortUser.subscribe(); maybeCaproMessage = subscriberPortProducer.getCaProMessage(); if (maybeCaproMessage.has_value()) { caproMessage = maybeCaproMessage.value(); m_concurrentCaproMessageVector->push_back(caproMessage); } // Wait for subscription ACK from publisher caproMessage = waitForCaproMessage(m_concurrentCaproMessageVector, CaproMessageType::ACK); // Let RouDi change state to finish subscription static_cast<void>(subscriberPortProducer.dispatchCaProMessage(caproMessage)); // Subscription done and ready to receive samples while (!finished) { if (m_waiter.timedWait(1000_ms)) { // Condition variable triggered subscriberPortUser.getChunk() .and_then([&](optional<const ChunkHeader*>& maybeChunkHeader) { if (maybeChunkHeader.has_value()) { auto chunkHeader = maybeChunkHeader.value(); m_receiveCounter++; subscriberPortUser.releaseChunk(chunkHeader); } }) .or_else([](ChunkReceiveError) { // Errors shall never occur FAIL(); }); } else { // Timeout -> check if publisher is still going if (!m_publisherRun.load(std::memory_order_relaxed)) { finished = true; } } } } void publisherThread(uint32_t publisherThreadIndex, PublisherPortRouDi& publisherPortRouDi, PublisherPortUser& publisherPortUser) { optional<CaproMessage> maybeCaproMessage; CaproMessage caproMessage; // Publisher offers its service publisherPortUser.offer(); // Let RouDi change state and send OFFER to subscriber maybeCaproMessage = publisherPortRouDi.getCaProMessage(); if (publisherThreadIndex == 0) { if (maybeCaproMessage.has_value()) { caproMessage = maybeCaproMessage.value(); auto guardedVector = m_concurrentCaproMessageVector.GetScopeGuard(); guardedVector->push_back(caproMessage); } // Wait for subscriber to subscribe caproMessage = waitForCaproMessage(m_concurrentCaproMessageVector, CaproMessageType::SUB); m_caproMessageRx->push_back(caproMessage); // Send ACK to subscriber maybeCaproMessage = publisherPortRouDi.dispatchCaProMessage(m_caproMessageRx->back()); if (maybeCaproMessage.has_value()) { caproMessage = maybeCaproMessage.value(); m_concurrentCaproMessageVector->push_back(caproMessage); } } else { CaproMessage caproMessageRouDi(CaproMessageType::UNSUB, TEST_SERVICE_DESCRIPTION); do { std::this_thread::sleep_for(std::chrono::microseconds(10)); if (m_caproMessageRx->size() != 0) { caproMessageRouDi = m_caproMessageRx->back(); } } while (caproMessageRouDi.m_type != CaproMessageType::SUB); static_cast<void>(publisherPortRouDi.dispatchCaProMessage(caproMessageRouDi)); } // Subscriber is ready to receive -> start sending samples for (size_t i = 0; i < ITERATIONS; i++) { publisherPortUser.allocateChunk(sizeof(DummySample)) .and_then([&](ChunkHeader* chunkHeader) { auto sample = chunkHeader->payload(); new (sample) DummySample(); static_cast<DummySample*>(sample)->m_dummy = i; publisherPortUser.sendChunk(chunkHeader); m_sendCounter++; }) .or_else([](AllocationError) { // Errors shall never occur FAIL(); }); /// Add some jitter to make thread breathe std::this_thread::sleep_for(std::chrono::nanoseconds(rand() % 100)); } // Signal the subscriber thread we're done m_publisherRun = false; } }; TEST_F(PortUser_IntegrationTest, SingleProducer) { std::thread subscribingThread(std::bind(&PortUser_IntegrationTest::subscriberThread<SubscriberPortSingleProducer>, this, std::ref(PortUser_IntegrationTest::m_subscriberPortRouDiSideSingleProducer), std::ref(PortUser_IntegrationTest::m_subscriberPortUserSingleProducer))); std::thread publishingThread(std::bind(&PortUser_IntegrationTest::publisherThread, this, 0, std::ref(PortUser_IntegrationTest::m_publisherRouDiSide), std::ref(PortUser_IntegrationTest::m_publisherUserSide))); if (subscribingThread.joinable()) { subscribingThread.join(); } if (publishingThread.joinable()) { publishingThread.join(); } EXPECT_EQ(m_sendCounter.load(std::memory_order_relaxed), m_receiveCounter); } TEST_F(PortUser_IntegrationTest, MultiProducer) { std::thread subscribingThread( std::bind(&PortUser_IntegrationTest::subscriberThread<SubscriberPortMultiProducer>, this, std::ref(PortUser_IntegrationTest::m_subscriberPortRouDiMultiSingleProducer), std::ref(PortUser_IntegrationTest::m_subscriberPortUserMultiProducer))); vector<std::thread, NUMBER_OF_PUBLISHERS> publisherThreadVector; for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++) { publisherThreadVector.emplace_back(std::bind(&PortUser_IntegrationTest::publisherThread, this, i, std::ref(PortUser_IntegrationTest::m_publisherRouDiSideVector[i]), std::ref(PortUser_IntegrationTest::m_publisherUserSideVector[i]))); } if (subscribingThread.joinable()) { subscribingThread.join(); } for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++) { if (publisherThreadVector[i].joinable()) { publisherThreadVector[i].join(); } } EXPECT_EQ(m_sendCounter.load(std::memory_order_relaxed), m_receiveCounter); } <commit_msg>iox-#25: Some clean-up<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_posh/iceoryx_posh_types.hpp" #include "iceoryx_posh/internal/popo/ports/publisher_port_roudi.hpp" #include "iceoryx_posh/internal/popo/ports/publisher_port_user.hpp" #include "iceoryx_posh/internal/popo/ports/subscriber_port_multi_producer.hpp" #include "iceoryx_posh/internal/popo/ports/subscriber_port_single_producer.hpp" #include "iceoryx_posh/internal/popo/ports/subscriber_port_user.hpp" #include "iceoryx_posh/mepoo/mepoo_config.hpp" #include "iceoryx_posh/popo/wait_set.hpp" #include "iceoryx_utils/cxx/generic_raii.hpp" #include "iceoryx_utils/error_handling/error_handling.hpp" #include "iceoryx_utils/internal/concurrent/smart_lock.hpp" #include "test.hpp" #include <chrono> #include <sstream> #include <thread> using namespace ::testing; using namespace iox::popo; using namespace iox::capro; using namespace iox::cxx; using namespace iox::mepoo; using namespace iox::posix; using ::testing::Return; struct DummySample { uint64_t m_dummy{42}; }; static const ServiceDescription TEST_SERVICE_DESCRIPTION("x", "y", "z"); static const iox::ProcessName_t TEST_SUBSCRIBER_APP_NAME("mySubscriberApp"); static const iox::ProcessName_t TEST_PUBLISHER_APP_NAME("myPublisherApp"); static constexpr uint32_t NUMBER_OF_PUBLISHERS = 42; static constexpr uint32_t ITERATIONS = 1000; static constexpr uint32_t NUM_CHUNKS_IN_POOL = NUMBER_OF_PUBLISHERS * 3 * iox::MAX_RECEIVER_QUEUE_CAPACITY; static constexpr uint32_t SMALL_CHUNK = 128; static constexpr uint32_t CHUNK_META_INFO_SIZE = 256; static constexpr size_t MEMORY_SIZE = NUM_CHUNKS_IN_POOL * (SMALL_CHUNK + CHUNK_META_INFO_SIZE); alignas(64) static uint8_t g_memory[MEMORY_SIZE]; class PortUser_IntegrationTest : public Test { public: PortUser_IntegrationTest() { m_mempoolConfig.addMemPool({SMALL_CHUNK, NUM_CHUNKS_IN_POOL}); m_memoryManager.configureMemoryManager(m_mempoolConfig, &m_memoryAllocator, &m_memoryAllocator); } ~PortUser_IntegrationTest() { } void SetUp() { for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++) { std::stringstream publisherAppName; publisherAppName << TEST_PUBLISHER_APP_NAME << i; iox::cxx::string<100> processName(TruncateToCapacity, publisherAppName.str().c_str()); m_publisherPortDataVector.emplace_back(TEST_SERVICE_DESCRIPTION, processName, &m_memoryManager); m_publisherPortUserVector.emplace_back(&m_publisherPortDataVector.back()); m_publisherPortRouDiVector.emplace_back(&m_publisherPortDataVector.back()); } } void TearDown() { for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++) { m_publisherPortUserVector[i].stopOffer(); static_cast<void>(m_publisherPortRouDiVector[i].getCaProMessage()); } m_subscriberPortUserSingleProducer.unsubscribe(); m_subscriberPortUserMultiProducer.unsubscribe(); static_cast<void>(m_subscriberPortRouDiSingleProducer.getCaProMessage()); static_cast<void>(m_subscriberPortRouDiMultiProducer.getCaProMessage()); if (m_subscriberPortUserSingleProducer.isConditionVariableAttached()) { static_cast<void>(m_subscriberPortUserSingleProducer.detachConditionVariable()); } if (m_subscriberPortUserMultiProducer.isConditionVariableAttached()) { static_cast<void>(m_subscriberPortUserMultiProducer.detachConditionVariable()); } m_waiter.reset(); } GenericRAII m_uniqueRouDiId{[] { iox::popo::internal::setUniqueRouDiId(0); }, [] { iox::popo::internal::unsetUniqueRouDiId(); }}; std::atomic<uint64_t> m_sendCounter{0}; uint64_t m_receiveCounter{0}; std::atomic<bool> m_publisherRun{true}; // Memory objects Allocator m_memoryAllocator{g_memory, MEMORY_SIZE}; MePooConfig m_mempoolConfig; MemoryManager m_memoryManager; ConditionVariableData m_condVarData; ConditionVariableWaiter m_waiter{&m_condVarData}; using ConcurrentCaproMessageVector_t = iox::concurrent::smart_lock<vector<CaproMessage, 1>>; ConcurrentCaproMessageVector_t m_concurrentCaproMessageVector; iox::concurrent::smart_lock<vector<CaproMessage, 1>> m_caproMessageRx; // subscriber port for single producer SubscriberPortData m_subscriberPortDataSingleProducer{ TEST_SERVICE_DESCRIPTION, TEST_SUBSCRIBER_APP_NAME, VariantQueueTypes::SoFi_SingleProducerSingleConsumer}; SubscriberPortUser m_subscriberPortUserSingleProducer{&m_subscriberPortDataSingleProducer}; SubscriberPortSingleProducer m_subscriberPortRouDiSingleProducer{&m_subscriberPortDataSingleProducer}; // subscriber port for multi producer SubscriberPortData m_subscriberPortDataMultiProducer{ TEST_SERVICE_DESCRIPTION, TEST_SUBSCRIBER_APP_NAME, VariantQueueTypes::SoFi_MultiProducerSingleConsumer}; SubscriberPortUser m_subscriberPortUserMultiProducer{&m_subscriberPortDataMultiProducer}; SubscriberPortMultiProducer m_subscriberPortRouDiMultiProducer{&m_subscriberPortDataMultiProducer}; // publisher port vector<PublisherPortData, NUMBER_OF_PUBLISHERS> m_publisherPortDataVector; vector<PublisherPortUser, NUMBER_OF_PUBLISHERS> m_publisherPortUserVector; vector<PublisherPortRouDi, NUMBER_OF_PUBLISHERS> m_publisherPortRouDiVector; inline CaproMessage waitForCaproMessage(const ConcurrentCaproMessageVector_t& concurrentCaproMessageVector, const CaproMessageType& caproMessageType) { bool finished{false}; CaproMessage caproMessage; do { std::this_thread::sleep_for(std::chrono::microseconds(10)); { auto guardedVector = concurrentCaproMessageVector.GetScopeGuard(); if (guardedVector->size() != 0) { caproMessage = guardedVector->back(); if (caproMessage.m_type == caproMessageType) { guardedVector->pop_back(); finished = true; } } } } while (!finished); return caproMessage; } template <typename SubscriberPortProducerType> void subscriberThread(SubscriberPortProducerType& subscriberPortRouDi, SubscriberPortUser& subscriberPortUser) { bool finished{false}; optional<CaproMessage> maybeCaproMessage; CaproMessage caproMessage; subscriberPortUser.attachConditionVariable(&m_condVarData); // Wait for publisher to be ready caproMessage = waitForCaproMessage(m_concurrentCaproMessageVector, CaproMessageType::OFFER); // Subscribe to publisher subscriberPortUser.subscribe(); maybeCaproMessage = subscriberPortRouDi.getCaProMessage(); if (maybeCaproMessage.has_value()) { caproMessage = maybeCaproMessage.value(); m_concurrentCaproMessageVector->push_back(caproMessage); } // Wait for subscription ACK from publisher caproMessage = waitForCaproMessage(m_concurrentCaproMessageVector, CaproMessageType::ACK); // Let RouDi change state to finish subscription static_cast<void>(subscriberPortRouDi.dispatchCaProMessage(caproMessage)); // Subscription done and ready to receive samples while (!finished) { if (m_waiter.timedWait(100_ms)) { // Condition variable triggered subscriberPortUser.getChunk() .and_then([&](optional<const ChunkHeader*>& maybeChunkHeader) { if (maybeChunkHeader.has_value()) { auto chunkHeader = maybeChunkHeader.value(); m_receiveCounter++; subscriberPortUser.releaseChunk(chunkHeader); } }) .or_else([](ChunkReceiveError) { // Errors shall never occur FAIL(); }); } else { // Timeout -> check if publisher is still going if (!m_publisherRun.load(std::memory_order_relaxed)) { finished = true; } } } } void publisherThread(uint32_t publisherThreadIndex, PublisherPortRouDi& publisherPortRouDi, PublisherPortUser& publisherPortUser) { optional<CaproMessage> maybeCaproMessage; CaproMessage caproMessage; // Publisher offers its service publisherPortUser.offer(); // Let RouDi change state and send OFFER to subscriber maybeCaproMessage = publisherPortRouDi.getCaProMessage(); if (publisherThreadIndex == 0) { if (maybeCaproMessage.has_value()) { caproMessage = maybeCaproMessage.value(); auto guardedVector = m_concurrentCaproMessageVector.GetScopeGuard(); guardedVector->push_back(caproMessage); } // Wait for subscriber to subscribe caproMessage = waitForCaproMessage(m_concurrentCaproMessageVector, CaproMessageType::SUB); m_caproMessageRx->push_back(caproMessage); // Send ACK to subscriber maybeCaproMessage = publisherPortRouDi.dispatchCaProMessage(m_caproMessageRx->back()); if (maybeCaproMessage.has_value()) { caproMessage = maybeCaproMessage.value(); m_concurrentCaproMessageVector->push_back(caproMessage); } } else { CaproMessage caproMessageRouDi(CaproMessageType::UNSUB, TEST_SERVICE_DESCRIPTION); do { std::this_thread::sleep_for(std::chrono::microseconds(10)); if (m_caproMessageRx->size() != 0) { caproMessageRouDi = m_caproMessageRx->back(); } } while (caproMessageRouDi.m_type != CaproMessageType::SUB); static_cast<void>(publisherPortRouDi.dispatchCaProMessage(caproMessageRouDi)); } // Subscriber is ready to receive -> start sending samples for (size_t i = 0; i < ITERATIONS; i++) { publisherPortUser.allocateChunk(sizeof(DummySample)) .and_then([&](ChunkHeader* chunkHeader) { auto sample = chunkHeader->payload(); new (sample) DummySample(); static_cast<DummySample*>(sample)->m_dummy = i; publisherPortUser.sendChunk(chunkHeader); m_sendCounter++; }) .or_else([](AllocationError) { // Errors shall never occur FAIL(); }); /// Add some jitter to make thread breathe std::this_thread::sleep_for(std::chrono::nanoseconds(rand() % 100)); } // Signal the subscriber thread we're done m_publisherRun = false; } }; TEST_F(PortUser_IntegrationTest, SingleProducer) { std::thread subscribingThread(std::bind(&PortUser_IntegrationTest::subscriberThread<SubscriberPortSingleProducer>, this, std::ref(PortUser_IntegrationTest::m_subscriberPortRouDiSingleProducer), std::ref(PortUser_IntegrationTest::m_subscriberPortUserSingleProducer))); std::thread publishingThread(std::bind(&PortUser_IntegrationTest::publisherThread, this, 0, std::ref(PortUser_IntegrationTest::m_publisherPortRouDiVector.front()), std::ref(PortUser_IntegrationTest::m_publisherPortUserVector.front()))); if (subscribingThread.joinable()) { subscribingThread.join(); } if (publishingThread.joinable()) { publishingThread.join(); } EXPECT_EQ(m_sendCounter.load(std::memory_order_relaxed), m_receiveCounter); } TEST_F(PortUser_IntegrationTest, MultiProducer) { std::thread subscribingThread(std::bind(&PortUser_IntegrationTest::subscriberThread<SubscriberPortMultiProducer>, this, std::ref(PortUser_IntegrationTest::m_subscriberPortRouDiMultiProducer), std::ref(PortUser_IntegrationTest::m_subscriberPortUserMultiProducer))); vector<std::thread, NUMBER_OF_PUBLISHERS> publisherThreadVector; for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++) { publisherThreadVector.emplace_back(std::bind(&PortUser_IntegrationTest::publisherThread, this, i, std::ref(PortUser_IntegrationTest::m_publisherPortRouDiVector[i]), std::ref(PortUser_IntegrationTest::m_publisherPortUserVector[i]))); } if (subscribingThread.joinable()) { subscribingThread.join(); } for (uint32_t i = 0; i < NUMBER_OF_PUBLISHERS; i++) { if (publisherThreadVector[i].joinable()) { publisherThreadVector[i].join(); } } EXPECT_EQ(m_sendCounter.load(std::memory_order_relaxed), m_receiveCounter); } <|endoftext|>
<commit_before>// Time: O(n) // Space: O(c), c is unique count of pattern and words class Solution { public: bool wordPattern(string pattern, string str) { int word_cnt = str.empty() ? 0 : 1; for (const auto& c : str) { if (c == ' ') { ++word_cnt; } } if (pattern.size() != word_cnt) { return false; } unordered_map<string, char> word2pattern; unordered_map<char, string> pattern2word; int i = 0, j = 0; for (const auto& p : pattern) { j = str.find(" ", i); if (j == string::npos) { j = str.length(); } const string word = str.substr(i, j - i); if (!word2pattern.count(word) && !pattern2word.count(p)) { word2pattern[word] = p; pattern2word[p] = word; } else if (word2pattern[word] != p) { return false; } i = j + 1; } return true; } }; <commit_msg>Update word-pattern.cpp<commit_after>// Time: O(n) // Space: O(c), c is unique count of pattern and words class Solution { public: bool wordPattern(string pattern, string str) { int cnt = str.empty() ? 0 : 1; for (const auto& c : str) { if (c == ' ') { ++cnt; } } if (pattern.size() != cnt) { return false; } unordered_map<string, char> w2p; unordered_map<char, string> p2w; int i = 0, j = 0; for (const auto& p : pattern) { j = str.find(" ", i); if (j == string::npos) { j = str.length(); } const string word = str.substr(i, j - i); if (!w2p.count(word) && !p2w.count(p)) { w2p[word] = p; p2w[p] = word; } else if (w2p[word] != p) { return false; } i = j + 1; } return true; } }; <|endoftext|>
<commit_before>// // ServiceRegistryWrapper.cpp // // $Id: //poco/1.4/OSP/JS/src/ServiceRegistryWrapper.cpp#4 $ // // Copyright (c) 2013-2014, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: Apache-2.0 // #include "Poco/OSP/JS/ServiceRegistryWrapper.h" #include "Poco/OSP/JS/ServiceRefWrapper.h" namespace Poco { namespace OSP { namespace JS { ServiceRegistryWrapper::ServiceRegistryWrapper() { } ServiceRegistryWrapper::~ServiceRegistryWrapper() { } v8::Handle<v8::ObjectTemplate> ServiceRegistryWrapper::objectTemplate(v8::Isolate* pIsolate) { v8::EscapableHandleScope handleScope(pIsolate); v8::Local<v8::ObjectTemplate> serviceRegistryTemplate = v8::ObjectTemplate::New(pIsolate); serviceRegistryTemplate->SetInternalFieldCount(1); serviceRegistryTemplate->Set(v8::String::NewFromUtf8(pIsolate, "find"), v8::FunctionTemplate::New(pIsolate, find)); serviceRegistryTemplate->Set(v8::String::NewFromUtf8(pIsolate, "findByName"), v8::FunctionTemplate::New(pIsolate, findByName)); return handleScope.Escape(serviceRegistryTemplate); } void ServiceRegistryWrapper::findByName(const v8::FunctionCallbackInfo<v8::Value>& args) { Poco::OSP::ServiceRegistry* pServiceRegistry = Poco::JS::Core::Wrapper::unwrapNative<Poco::OSP::ServiceRegistry>(args); try { if (args.Length() == 1) { std::string serviceName = toString(args[0]); Poco::OSP::ServiceRef::Ptr pServiceRef = pServiceRegistry->findByName(serviceName); if (pServiceRef) { ServiceRefWrapper wrapper; v8::Persistent<v8::Object> serviceRefObject(args.GetIsolate(), wrapper.wrapNativePersistent(args.GetIsolate(), pServiceRef)); args.GetReturnValue().Set(serviceRefObject); return; } args.GetReturnValue().Set(v8::Null(args.GetIsolate())); } else { returnException(args, std::string("bad arguments - service name required")); } } catch (Poco::Exception& exc) { returnException(args, exc); } } void ServiceRegistryWrapper::find(const v8::FunctionCallbackInfo<v8::Value>& args) { Poco::OSP::ServiceRegistry* pServiceRegistry = Poco::JS::Core::Wrapper::unwrapNative<Poco::OSP::ServiceRegistry>(args); try { if (args.Length() == 1) { ServiceRefWrapper wrapper; std::string serviceQuery = toString(args[0]); std::vector<Poco::OSP::ServiceRef::Ptr> services; v8::Local<v8::Array> result = v8::Array::New(args.GetIsolate()); int i = 0; if (pServiceRegistry->find(serviceQuery, services)) { for (std::vector<Poco::OSP::ServiceRef::Ptr>::iterator it = services.begin(); it != services.end(); ++it) { v8::Persistent<v8::Object>& serviceRefObject(wrapper.wrapNativePersistent(args.GetIsolate(), *it)); v8::Local<v8::Object> localServiceRefObject = v8::Local<v8::Object>::New(args.GetIsolate(), serviceRefObject); result->Set(i++, localServiceRefObject); } } args.GetReturnValue().Set(result); } else { returnException(args, std::string("bad arguments - service query required")); } } catch (Poco::Exception& exc) { returnException(args, exc); } } } } } // namespace Poco::OSP::JS <commit_msg>handle potential empty handle returned by v8::Array::New<commit_after>// // ServiceRegistryWrapper.cpp // // $Id: //poco/1.4/OSP/JS/src/ServiceRegistryWrapper.cpp#4 $ // // Copyright (c) 2013-2014, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: Apache-2.0 // #include "Poco/OSP/JS/ServiceRegistryWrapper.h" #include "Poco/OSP/JS/ServiceRefWrapper.h" namespace Poco { namespace OSP { namespace JS { ServiceRegistryWrapper::ServiceRegistryWrapper() { } ServiceRegistryWrapper::~ServiceRegistryWrapper() { } v8::Handle<v8::ObjectTemplate> ServiceRegistryWrapper::objectTemplate(v8::Isolate* pIsolate) { v8::EscapableHandleScope handleScope(pIsolate); v8::Local<v8::ObjectTemplate> serviceRegistryTemplate = v8::ObjectTemplate::New(pIsolate); serviceRegistryTemplate->SetInternalFieldCount(1); serviceRegistryTemplate->Set(v8::String::NewFromUtf8(pIsolate, "find"), v8::FunctionTemplate::New(pIsolate, find)); serviceRegistryTemplate->Set(v8::String::NewFromUtf8(pIsolate, "findByName"), v8::FunctionTemplate::New(pIsolate, findByName)); return handleScope.Escape(serviceRegistryTemplate); } void ServiceRegistryWrapper::findByName(const v8::FunctionCallbackInfo<v8::Value>& args) { Poco::OSP::ServiceRegistry* pServiceRegistry = Poco::JS::Core::Wrapper::unwrapNative<Poco::OSP::ServiceRegistry>(args); try { if (args.Length() == 1) { std::string serviceName = toString(args[0]); Poco::OSP::ServiceRef::Ptr pServiceRef = pServiceRegistry->findByName(serviceName); if (pServiceRef) { ServiceRefWrapper wrapper; v8::Persistent<v8::Object> serviceRefObject(args.GetIsolate(), wrapper.wrapNativePersistent(args.GetIsolate(), pServiceRef)); args.GetReturnValue().Set(serviceRefObject); return; } args.GetReturnValue().Set(v8::Null(args.GetIsolate())); } else { returnException(args, std::string("bad arguments - service name required")); } } catch (Poco::Exception& exc) { returnException(args, exc); } } void ServiceRegistryWrapper::find(const v8::FunctionCallbackInfo<v8::Value>& args) { Poco::OSP::ServiceRegistry* pServiceRegistry = Poco::JS::Core::Wrapper::unwrapNative<Poco::OSP::ServiceRegistry>(args); try { if (args.Length() == 1) { ServiceRefWrapper wrapper; std::string serviceQuery = toString(args[0]); std::vector<Poco::OSP::ServiceRef::Ptr> services; v8::Local<v8::Array> result = v8::Array::New(args.GetIsolate()); if (!result.IsEmpty()) { int i = 0; if (pServiceRegistry->find(serviceQuery, services)) { for (std::vector<Poco::OSP::ServiceRef::Ptr>::iterator it = services.begin(); it != services.end(); ++it) { v8::Persistent<v8::Object>& serviceRefObject(wrapper.wrapNativePersistent(args.GetIsolate(), *it)); v8::Local<v8::Object> localServiceRefObject = v8::Local<v8::Object>::New(args.GetIsolate(), serviceRefObject); result->Set(i++, localServiceRefObject); } } } args.GetReturnValue().Set(result); } else { returnException(args, std::string("bad arguments - service query required")); } } catch (Poco::Exception& exc) { returnException(args, exc); } } } } } // namespace Poco::OSP::JS <|endoftext|>
<commit_before>#include <VBE/graphics/MeshBatched.hpp> #include <algorithm> #include <VBE/system/Log.hpp> #include "ShaderBinding.hpp" bool MeshBatched::batching = false; MeshBatched::Buffer* MeshBatched::batchingBuffer = nullptr; const ShaderProgram* MeshBatched::batchingProgram = nullptr; MeshBase::PrimitiveType MeshBatched::batchingPrimitive = MeshBase::TRIANGLES; GLuint MeshBatched::perDrawAttribBuffer = 0; unsigned int MeshBatched::perDrawAttribBufferSize = 0; std::vector<MeshBatched::DrawIndirectCommand> MeshBatched::commands; std::set<MeshBatched::Buffer*> MeshBatched::buffers; MeshBatched::MeshBatched() : MeshBatched(Vertex::Format()) { } MeshBatched::MeshBatched(const Vertex::Format& format) : MeshBase(format, STREAM) { ensureInitBuffers(); Buffer* b = getBuffer(); if(b == nullptr) { b = new Buffer(format); buffers.insert(b); } b->addMesh(this); } MeshBatched::~MeshBatched() { Buffer* b = getBuffer(); b->deleteMesh(this); if(b->getMeshCount() == 0) { buffers.erase(b); delete b; } } MeshBatched::MeshBatched(MeshBatched&& rhs) : MeshBase(Vertex::Format(std::vector<Vertex::Attribute>())) { using std::swap; swap(*this, rhs); } MeshBatched& MeshBatched::operator=(MeshBatched&& rhs) { using std::swap; swap(*this, rhs); return *this; } void MeshBatched::draw(const ShaderProgram* program) { draw(program, 0, vertexCount); } void MeshBatched::draw(const ShaderProgram* program, unsigned int offset, unsigned int length) { VBE_ASSERT(program != nullptr, "program cannot be null"); VBE_ASSERT(program->getHandle() != 0, "program cannot be null"); VBE_ASSERT(length != 0, "length must not be zero"); VBE_ASSERT(offset < getVertexCount(), "offset must be smaller than vertex count"); VBE_ASSERT(offset + length <= getVertexCount(), "offset plus length must be smaller or equal to vertex count"); Buffer* b = getBuffer(); b->setupBinding(program); GL_ASSERT(glDrawArrays(getPrimitiveType(), b->getMeshOffset(this) + offset, length)); } void MeshBatched::drawBatched(const ShaderProgram* program) { drawBatched(program, 0, vertexCount); } void MeshBatched::drawBatched(const ShaderProgram* program, unsigned int offset, unsigned int length) { VBE_ASSERT(batching, "Cannot draw a MeshBatched with batching without calling startBatch() first."); Buffer* b = getBuffer(); if(batchingBuffer == nullptr) { //first command batchingBuffer = b; batchingProgram = program; batchingPrimitive = getPrimitiveType(); } VBE_ASSERT(batchingBuffer == b, "Cannot send two MeshBatched with different formats under the same batch."); VBE_ASSERT(batchingProgram == program, "Cannot use two different programs during the same batch."); VBE_ASSERT(batchingPrimitive == getPrimitiveType(), "Cannot use two different primitives during the same batch."); commands.push_back(DrawIndirectCommand(length, 1, b->getMeshOffset(this) + offset, commands.size())); } void MeshBatched::setVertexData(const void* vertexData, unsigned int newVertexCount) { Buffer* b = getBuffer(); vertexCount = newVertexCount; b->submitData(this, vertexData, newVertexCount); } void MeshBatched::resetBatch() { commands.clear(); } void MeshBatched::startBatch() { VBE_ASSERT(!batching, "Cannot start a new batch without ending the previous one."); resetBatch(); batching = true; } void MeshBatched::endBatch() { VBE_ASSERT(batching, "Cannot end a batch that wasn't started."); batching = false; if(commands.size() == 0) return; uploadPerDrawData(commands.size()); //uploadIndirectCommands(); batchingBuffer->setupBinding(batchingProgram); GL_ASSERT(glMultiDrawArraysIndirect(batchingPrimitive, &commands[0], commands.size(), 0)); commands.clear(); batchingBuffer = nullptr; batchingProgram = nullptr; } MeshBatched::Buffer* MeshBatched::getBuffer() const { for(Buffer* b : buffers) if(b->bufferFormat == getVertexFormat()) return b; return nullptr; } void MeshBatched::ensureInitBuffers() { if(perDrawAttribBuffer == 0) { GL_ASSERT(glGenBuffers(1, &perDrawAttribBuffer)); uploadPerDrawData(1); } } void MeshBatched::uploadPerDrawData(unsigned int size) { if(size <= perDrawAttribBufferSize) return; perDrawAttribBufferSize = size; GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, perDrawAttribBuffer)); GL_ASSERT(glBufferData(GL_ARRAY_BUFFER, size*sizeof(unsigned int), 0, STATIC)); GLuint* draw_index = nullptr; GL_ASSERT(draw_index = (GLuint *)glMapBufferRange(GL_ARRAY_BUFFER, 0, size * sizeof(GLuint), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT)); for(unsigned int i = 0; i < size; i++) draw_index[i] = i; GL_ASSERT(glUnmapBuffer(GL_ARRAY_BUFFER)); } void MeshBatched::bindPerDrawBuffers() { GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, perDrawAttribBuffer)); } void swap(MeshBatched& a, MeshBatched& b) { using std::swap; swap(static_cast<MeshBase&>(a), static_cast<MeshBase&>(b)); } MeshBatched::Buffer::Buffer(const Vertex::Format& format) : bufferFormat(format), vertexBuffer(0), totalBufferSize(1 << 10) { GL_ASSERT(glGenBuffers(1, &vertexBuffer)); GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer)); GL_ASSERT(glBufferData(GL_ARRAY_BUFFER, totalBufferSize*bufferFormat.vertexSize(), 0, MeshBase::STREAM)); freeInterval(Interval(0, 1 << 10)); } MeshBatched::Buffer::~Buffer() { GL_ASSERT(glDeleteBuffers(1, &vertexBuffer)); } void MeshBatched::Buffer::addMesh(MeshBatched* mesh) { usedIntervals.insert(std::pair<MeshBatched*, Interval>(mesh, Interval(0,0))); } void MeshBatched::Buffer::deleteMesh(MeshBatched* mesh) { freeInterval(usedIntervals.at(mesh)); usedIntervals.erase(mesh); } void MeshBatched::Buffer::submitData(MeshBatched* mesh, const void* data, unsigned int vCount) { Interval& i = usedIntervals.at(mesh); freeInterval(i); i = Interval(0,0); i = allocateInterval(vCount); GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer)); GL_ASSERT(glBufferSubData(GL_ARRAY_BUFFER, i.start*bufferFormat.vertexSize(), vCount*bufferFormat.vertexSize(), data)); } unsigned int MeshBatched::Buffer::getMeshCount() { return usedIntervals.size(); } unsigned long MeshBatched::Buffer::getMeshOffset(MeshBatched* mesh) { return usedIntervals.at(mesh).start; } void MeshBatched::Buffer::setupBinding(const ShaderProgram* program) { // Get the binding from the cache. If it does not exist, create it. GLuint handle = program->getHandle(); if(bindings.find(handle) == bindings.end()) bindings.insert(std::pair<GLuint, const ShaderBinding*>(handle, new ShaderBinding(program, this))); const ShaderBinding* binding = bindings.at(handle); // Bind the program and the binding program->use(); ShaderBinding::bind(binding); } void MeshBatched::Buffer::bindBuffers() const { GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer)); } void MeshBatched::Buffer::freeInterval(Interval i) { VBE_ASSERT(i.start + i.count <= totalBufferSize, "Free out of bounds GPU memory"); if(i.count == 0) return; bool merged = false; //merge with previous one if possible std::set<Interval>::iterator lower = std::lower_bound(freeIntervals.begin(), freeIntervals.end(), i); if(lower != freeIntervals.end() && lower != freeIntervals.begin()) { --lower; Interval previous = *lower; if(previous.start + previous.count == i.start) { freeIntervals.erase(previous); previous.count += i.count; freeIntervals.insert(previous); i = previous; merged = true; } } //merge with next one if possible std::set<Interval>::iterator upper = std::upper_bound(freeIntervals.begin(), freeIntervals.end(), i); if(upper != freeIntervals.end()) { Interval next = *upper; if(next.start == i.start + i.count) { freeIntervals.erase(next); freeIntervals.erase(i); i.count += next.count; freeIntervals.insert(i); merged = true; } } //else, push it standalone if(!merged) freeIntervals.insert(i); } MeshBatched::Buffer::Interval MeshBatched::Buffer::allocateInterval(unsigned int vCount) { Interval ret(0, vCount); Interval toReplace(0,0); bool spaceAvailable = false; for(const Interval& i : freeIntervals) { if(i.count >= vCount) { toReplace = i; spaceAvailable = true; break; } } if(spaceAvailable) { ret.start = toReplace.start; freeIntervals.erase(toReplace); if(toReplace.count > vCount) freeIntervals.insert(Interval(toReplace.start + vCount, toReplace.count - vCount)); } else { //buffer must be resized ret.start = totalBufferSize; int newSize = totalBufferSize; while(vCount > newSize-totalBufferSize) newSize *= 2; resizeBuffer(newSize); ret = allocateInterval(vCount); //...meh } return ret; } void MeshBatched::Buffer::resizeBuffer(unsigned int newSize) { VBE_ASSERT(newSize > totalBufferSize, "Cannot resize to a smaller size"); //copy contents into new buffer GLuint newVBO = 0; GL_ASSERT(glGenBuffers(1, &newVBO)); GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, newVBO)); GL_ASSERT(glBufferData(GL_ARRAY_BUFFER, newSize*bufferFormat.vertexSize(), 0, MeshBase::STREAM)); GL_ASSERT(glBindBuffer(GL_COPY_READ_BUFFER, vertexBuffer)); GL_ASSERT(glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_ARRAY_BUFFER, 0, 0, bufferFormat.vertexSize()*totalBufferSize)); GL_ASSERT(glInvalidateBufferData(vertexBuffer)); GL_ASSERT(glDeleteBuffers(1, &vertexBuffer)); for(std::pair<const GLuint, const ShaderBinding*> bind : bindings) delete bind.second; bindings.clear(); vertexBuffer = newVBO; unsigned int oldSize = totalBufferSize; totalBufferSize = newSize; //Mark the new memory as free freeInterval(Interval(oldSize, totalBufferSize-oldSize)); } <commit_msg>Nvidia 346 driver behaves weird. Why is glMultiDrawArraysIndirect failing?<commit_after>#include <VBE/graphics/MeshBatched.hpp> #include <algorithm> #include <VBE/system/Log.hpp> #include "ShaderBinding.hpp" bool MeshBatched::batching = false; MeshBatched::Buffer* MeshBatched::batchingBuffer = nullptr; const ShaderProgram* MeshBatched::batchingProgram = nullptr; MeshBase::PrimitiveType MeshBatched::batchingPrimitive = MeshBase::TRIANGLES; GLuint MeshBatched::perDrawAttribBuffer = 0; unsigned int MeshBatched::perDrawAttribBufferSize = 0; std::vector<MeshBatched::DrawIndirectCommand> MeshBatched::commands; std::set<MeshBatched::Buffer*> MeshBatched::buffers; MeshBatched::MeshBatched() : MeshBatched(Vertex::Format()) { } MeshBatched::MeshBatched(const Vertex::Format& format) : MeshBase(format, STREAM) { ensureInitBuffers(); Buffer* b = getBuffer(); if(b == nullptr) { b = new Buffer(format); buffers.insert(b); } b->addMesh(this); } MeshBatched::~MeshBatched() { Buffer* b = getBuffer(); b->deleteMesh(this); if(b->getMeshCount() == 0) { buffers.erase(b); delete b; } } MeshBatched::MeshBatched(MeshBatched&& rhs) : MeshBase(Vertex::Format(std::vector<Vertex::Attribute>())) { using std::swap; swap(*this, rhs); } MeshBatched& MeshBatched::operator=(MeshBatched&& rhs) { using std::swap; swap(*this, rhs); return *this; } void MeshBatched::draw(const ShaderProgram* program) { draw(program, 0, vertexCount); } void MeshBatched::draw(const ShaderProgram* program, unsigned int offset, unsigned int length) { VBE_ASSERT(program != nullptr, "program cannot be null"); VBE_ASSERT(program->getHandle() != 0, "program cannot be null"); VBE_ASSERT(length != 0, "length must not be zero"); VBE_ASSERT(offset < getVertexCount(), "offset must be smaller than vertex count"); VBE_ASSERT(offset + length <= getVertexCount(), "offset plus length must be smaller or equal to vertex count"); Buffer* b = getBuffer(); b->setupBinding(program); GL_ASSERT(glDrawArrays(getPrimitiveType(), b->getMeshOffset(this) + offset, length)); } void MeshBatched::drawBatched(const ShaderProgram* program) { drawBatched(program, 0, vertexCount); } void MeshBatched::drawBatched(const ShaderProgram* program, unsigned int offset, unsigned int length) { VBE_ASSERT(batching, "Cannot draw a MeshBatched with batching without calling startBatch() first."); Buffer* b = getBuffer(); if(batchingBuffer == nullptr) { //first command batchingBuffer = b; batchingProgram = program; batchingPrimitive = getPrimitiveType(); } VBE_ASSERT(batchingBuffer == b, "Cannot send two MeshBatched with different formats under the same batch."); VBE_ASSERT(batchingProgram == program, "Cannot use two different programs during the same batch."); VBE_ASSERT(batchingPrimitive == getPrimitiveType(), "Cannot use two different primitives during the same batch."); commands.push_back(DrawIndirectCommand(length, 1, b->getMeshOffset(this) + offset, commands.size())); } void MeshBatched::setVertexData(const void* vertexData, unsigned int newVertexCount) { Buffer* b = getBuffer(); vertexCount = newVertexCount; b->submitData(this, vertexData, newVertexCount); } void MeshBatched::resetBatch() { commands.clear(); } void MeshBatched::startBatch() { VBE_ASSERT(!batching, "Cannot start a new batch without ending the previous one."); resetBatch(); batching = true; } void MeshBatched::endBatch() { VBE_ASSERT(batching, "Cannot end a batch that wasn't started."); batching = false; if(commands.size() == 0) return; uploadPerDrawData(commands.size()); //uploadIndirectCommands(); batchingBuffer->setupBinding(batchingProgram); GL_ASSERT(glMultiDrawArraysIndirect(batchingPrimitive, &commands[0], commands.size(), 0)); commands.clear(); batchingBuffer = nullptr; batchingProgram = nullptr; } MeshBatched::Buffer* MeshBatched::getBuffer() const { for(Buffer* b : buffers) if(b->bufferFormat == getVertexFormat()) return b; return nullptr; } void MeshBatched::ensureInitBuffers() { if(perDrawAttribBuffer == 0) { GL_ASSERT(glGenBuffers(1, &perDrawAttribBuffer)); uploadPerDrawData(1); } } void MeshBatched::uploadPerDrawData(unsigned int size) { if(size <= perDrawAttribBufferSize) return; perDrawAttribBufferSize = size; GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, perDrawAttribBuffer)); GL_ASSERT(glBufferData(GL_ARRAY_BUFFER, size*sizeof(unsigned int), 0, STATIC)); GLuint* draw_index = nullptr; GL_ASSERT(draw_index = (GLuint *)glMapBufferRange(GL_ARRAY_BUFFER, 0, size * sizeof(GLuint), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT)); VBE_ASSERT(draw_index != nullptr, "glMapBufferRange Failed!"); for(unsigned int i = 0; i < size; i++) draw_index[i] = i; GL_ASSERT(glUnmapBuffer(GL_ARRAY_BUFFER)); } void MeshBatched::bindPerDrawBuffers() { GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, perDrawAttribBuffer)); } void swap(MeshBatched& a, MeshBatched& b) { using std::swap; swap(static_cast<MeshBase&>(a), static_cast<MeshBase&>(b)); } MeshBatched::Buffer::Buffer(const Vertex::Format& format) : bufferFormat(format), vertexBuffer(0), totalBufferSize(1 << 10) { GL_ASSERT(glGenBuffers(1, &vertexBuffer)); GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer)); GL_ASSERT(glBufferData(GL_ARRAY_BUFFER, totalBufferSize*bufferFormat.vertexSize(), 0, MeshBase::STREAM)); freeInterval(Interval(0, 1 << 10)); } MeshBatched::Buffer::~Buffer() { GL_ASSERT(glDeleteBuffers(1, &vertexBuffer)); } void MeshBatched::Buffer::addMesh(MeshBatched* mesh) { usedIntervals.insert(std::pair<MeshBatched*, Interval>(mesh, Interval(0,0))); } void MeshBatched::Buffer::deleteMesh(MeshBatched* mesh) { freeInterval(usedIntervals.at(mesh)); usedIntervals.erase(mesh); } void MeshBatched::Buffer::submitData(MeshBatched* mesh, const void* data, unsigned int vCount) { Interval& i = usedIntervals.at(mesh); freeInterval(i); i = Interval(0,0); i = allocateInterval(vCount); GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer)); GL_ASSERT(glBufferSubData(GL_ARRAY_BUFFER, i.start*bufferFormat.vertexSize(), vCount*bufferFormat.vertexSize(), data)); } unsigned int MeshBatched::Buffer::getMeshCount() { return usedIntervals.size(); } unsigned long MeshBatched::Buffer::getMeshOffset(MeshBatched* mesh) { return usedIntervals.at(mesh).start; } void MeshBatched::Buffer::setupBinding(const ShaderProgram* program) { // Get the binding from the cache. If it does not exist, create it. GLuint handle = program->getHandle(); if(bindings.find(handle) == bindings.end()) bindings.insert(std::pair<GLuint, const ShaderBinding*>(handle, new ShaderBinding(program, this))); const ShaderBinding* binding = bindings.at(handle); // Bind the program and the binding program->use(); ShaderBinding::bind(binding); } void MeshBatched::Buffer::bindBuffers() const { GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer)); } void MeshBatched::Buffer::freeInterval(Interval i) { VBE_ASSERT(i.start + i.count <= totalBufferSize, "Free out of bounds GPU memory"); if(i.count == 0) return; bool merged = false; //merge with previous one if possible std::set<Interval>::iterator lower = std::lower_bound(freeIntervals.begin(), freeIntervals.end(), i); if(lower != freeIntervals.end() && lower != freeIntervals.begin()) { --lower; Interval previous = *lower; if(previous.start + previous.count == i.start) { freeIntervals.erase(previous); previous.count += i.count; freeIntervals.insert(previous); i = previous; merged = true; } } //merge with next one if possible std::set<Interval>::iterator upper = std::upper_bound(freeIntervals.begin(), freeIntervals.end(), i); if(upper != freeIntervals.end()) { Interval next = *upper; if(next.start == i.start + i.count) { freeIntervals.erase(next); freeIntervals.erase(i); i.count += next.count; freeIntervals.insert(i); merged = true; } } //else, push it standalone if(!merged) freeIntervals.insert(i); } MeshBatched::Buffer::Interval MeshBatched::Buffer::allocateInterval(unsigned int vCount) { Interval ret(0, vCount); Interval toReplace(0,0); bool spaceAvailable = false; for(const Interval& i : freeIntervals) { if(i.count >= vCount) { toReplace = i; spaceAvailable = true; break; } } if(spaceAvailable) { ret.start = toReplace.start; freeIntervals.erase(toReplace); if(toReplace.count > vCount) freeIntervals.insert(Interval(toReplace.start + vCount, toReplace.count - vCount)); } else { //buffer must be resized ret.start = totalBufferSize; int newSize = totalBufferSize; while(vCount > newSize-totalBufferSize) newSize *= 2; resizeBuffer(newSize); ret = allocateInterval(vCount); //...meh } return ret; } void MeshBatched::Buffer::resizeBuffer(unsigned int newSize) { VBE_ASSERT(newSize > totalBufferSize, "Cannot resize to a smaller size"); //copy contents into new buffer GLuint newVBO = 0; GL_ASSERT(glGenBuffers(1, &newVBO)); GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, newVBO)); GL_ASSERT(glBufferData(GL_ARRAY_BUFFER, newSize*bufferFormat.vertexSize(), 0, MeshBase::STREAM)); GL_ASSERT(glBindBuffer(GL_COPY_READ_BUFFER, vertexBuffer)); GL_ASSERT(glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_ARRAY_BUFFER, 0, 0, bufferFormat.vertexSize()*totalBufferSize)); GL_ASSERT(glInvalidateBufferData(vertexBuffer)); GL_ASSERT(glDeleteBuffers(1, &vertexBuffer)); for(std::pair<const GLuint, const ShaderBinding*> bind : bindings) delete bind.second; bindings.clear(); vertexBuffer = newVBO; unsigned int oldSize = totalBufferSize; totalBufferSize = newSize; //Mark the new memory as free freeInterval(Interval(oldSize, totalBufferSize-oldSize)); } <|endoftext|>
<commit_before>#pragma once #ifndef NIFTY_GRAPH_SHORTEST_PATH_DIJKSTRA_HXX #define NIFTY_GRAPH_SHORTEST_PATH_DIJKSTRA_HXX #include "nifty/graph/subgraph_mask.hxx" #include "vigra/priority_queue.hxx" namespace nifty{ namespace graph{ template<class GRAPH, class WEIGHT_TYPE> class ShortestPathDijkstra{ public: typedef GRAPH Graph; typedef WEIGHT_TYPE WeightType; typedef typename Graph:: template NodeMap<int64_t> PredecessorsMap; typedef typename Graph:: template NodeMap<WeightType> DistanceMap; private: typedef vigra::ChangeablePriorityQueue<WeightType> PqType; public: ShortestPathDijkstra(const Graph & g) : g_(g), pq_(g.nodeIdUpperBound()+1), predMap_(g), distMap_(g){ } // run single source single target // no callback no mask exposed template<class EDGE_WEGIHTS> void runSingleSourceSingleTarget( const EDGE_WEGIHTS & edgeWeights, // why wasn't this a call by ref ? const int64_t source, const int64_t target = -1 ){ // subgraph mask DefaultSubgraphMask<Graph> subgraphMask; // visitor auto visitor = [&] ( int64_t topNode, const DistanceMap & distances, const PredecessorsMap & predecessors ){ return topNode != target; }; this->initializeMaps(&source, &source +1); runImpl(edgeWeights, subgraphMask, visitor); } // run single source multiple targets // no callback no mask exposed template<class EDGE_WEGIHTS> void runSingleSourceMultiTarget( const EDGE_WEGIHTS & edgeWeights, // why wasn't this a call by ref ? const int64_t source, const std::vector<int64_t> & targets ){ // subgraph mask DefaultSubgraphMask<Graph> subgraphMask; // visitor // TODO does this work ??? auto visitor = [&targets] ( int64_t topNode, const DistanceMap & distances, const PredecessorsMap & predecessors ){ thread_local size_t trgtsFound = 0; // this is declared to be thread local to be thread safe if( std::find(targets.begin(), targets.end(), topNode) != targets.end() ) ++trgtsFound; if( trgtsFound >= targets.size() ) { trgtsFound = 0; return false; } return true; }; this->initializeMaps(&source, &source +1); runImpl(edgeWeights, subgraphMask, visitor); } // run single source ALL targets // no callback no mask exposed template<class EDGE_WEGIHTS> void runSingleSource( EDGE_WEGIHTS edgeWeights, const int64_t source ){ // subgraph mask DefaultSubgraphMask<Graph> subgraphMask; this->initializeMaps(&source, &source +1); // visitor auto visitor = []( int64_t topNode, const DistanceMap & distances, const PredecessorsMap & predecessors ){ return true; }; runImpl(edgeWeights, subgraphMask, visitor); } template<class EDGE_WEGIHTS, class SOURCE_ITER, class SUBGRAPH_MASK, class VISITOR> void run( EDGE_WEGIHTS edgeWeights, SOURCE_ITER sourceBegin, SOURCE_ITER sourceEnd, const SUBGRAPH_MASK & subgraphMask, VISITOR && visitor ){ this->initializeMaps(sourceBegin, sourceEnd); this->runImpl(edgeWeights,subgraphMask,visitor); } const DistanceMap & distances()const{ return distMap_; } const PredecessorsMap & predecessors()const{ // is there a reason that this was not returned by ref before ? return predMap_; } private: template< class EDGE_WEGIHTS, class SUBGRAPH_MASK, class VISITOR > void runImpl( const EDGE_WEGIHTS & edgeWeights, // why wasn't this a call by ref ? const SUBGRAPH_MASK & subgraphMask, VISITOR && visitor ){ //target_ = lemon::INVALID; while(!pq_.empty() ){ //&& !finished){ const auto topNode = pq_.top(); pq_.pop(); if(!visitor(topNode, distMap_, predMap_)){ break; } if(subgraphMask.useNode(topNode)){ // loop over all neigbours for(auto adj : g_.adjacency(topNode)){ auto otherNode = adj.node(); const auto edge = adj.edge(); if(subgraphMask.useNode(otherNode) && subgraphMask.useEdge(otherNode)){ if(pq_.contains(otherNode)){ const WeightType currentDist = distMap_[otherNode]; const WeightType alternativeDist = distMap_[topNode]+edgeWeights[edge]; if(alternativeDist<currentDist){ pq_.push(otherNode,alternativeDist); distMap_[otherNode]=alternativeDist; predMap_[otherNode]=topNode; } } else if(predMap_[otherNode]==-1){ const WeightType initialDist = distMap_[topNode]+edgeWeights[edge]; //if(initialDist<=maxDistance) //{ pq_.push(otherNode,initialDist); distMap_[otherNode]=initialDist; predMap_[otherNode]=topNode; //} } } } } } while(!pq_.empty() ){ const auto topNode = pq_.top(); predMap_[topNode] = -1; pq_.pop(); } } template<class SOURCE_ITER> void initializeMaps(SOURCE_ITER sourceBegin, SOURCE_ITER sourceEnd){ for(auto node : g_.nodes()){ predMap_[node] = -1; } for( ; sourceBegin!=sourceEnd; ++sourceBegin){ auto n = *sourceBegin; distMap_[n] = static_cast<WeightType>(0); predMap_[n] = n; pq_.push(n,static_cast<WeightType>(0)); } } const GRAPH & g_; PqType pq_; PredecessorsMap predMap_; DistanceMap distMap_; }; } // namespace nifty::graph } // namespace nifty #endif // NIFTY_GRAPH_SHORTEST_PATH_DIJKSTRA_HXX <commit_msg>removing the f*cking thread local shit<commit_after>#pragma once #ifndef NIFTY_GRAPH_SHORTEST_PATH_DIJKSTRA_HXX #define NIFTY_GRAPH_SHORTEST_PATH_DIJKSTRA_HXX #include "nifty/graph/subgraph_mask.hxx" #include "vigra/priority_queue.hxx" namespace nifty{ namespace graph{ template<class GRAPH, class WEIGHT_TYPE> class ShortestPathDijkstra{ public: typedef GRAPH Graph; typedef WEIGHT_TYPE WeightType; typedef typename Graph:: template NodeMap<int64_t> PredecessorsMap; typedef typename Graph:: template NodeMap<WeightType> DistanceMap; private: typedef vigra::ChangeablePriorityQueue<WeightType> PqType; public: ShortestPathDijkstra(const Graph & g) : g_(g), pq_(g.nodeIdUpperBound()+1), predMap_(g), distMap_(g){ } // run single source single target // no callback no mask exposed template<class EDGE_WEGIHTS> void runSingleSourceSingleTarget( const EDGE_WEGIHTS & edgeWeights, // why wasn't this a call by ref ? const int64_t source, const int64_t target = -1 ){ // subgraph mask DefaultSubgraphMask<Graph> subgraphMask; // visitor auto visitor = [&] ( int64_t topNode, const DistanceMap & distances, const PredecessorsMap & predecessors ){ return topNode != target; }; this->initializeMaps(&source, &source +1); runImpl(edgeWeights, subgraphMask, visitor); } // run single source multiple targets // no callback no mask exposed template<class EDGE_WEGIHTS> void runSingleSourceMultiTarget( const EDGE_WEGIHTS & edgeWeights, // why wasn't this a call by ref ? const int64_t source, const std::vector<int64_t> & targets ){ // subgraph mask DefaultSubgraphMask<Graph> subgraphMask; // visitor // TODO does this work ??? size_t trgtsFound = 0; auto visitor = [&targets, &trgtsFound] ( int64_t topNode, const DistanceMap & distances, const PredecessorsMap & predecessors ){ // this is declared to be thread local to be thread safe if( std::find(targets.begin(), targets.end(), topNode) != targets.end() ) ++trgtsFound; if( trgtsFound >= targets.size() ) { trgtsFound = 0; return false; } return true; }; this->initializeMaps(&source, &source +1); runImpl(edgeWeights, subgraphMask, visitor); } // run single source ALL targets // no callback no mask exposed template<class EDGE_WEGIHTS> void runSingleSource( EDGE_WEGIHTS edgeWeights, const int64_t source ){ // subgraph mask DefaultSubgraphMask<Graph> subgraphMask; this->initializeMaps(&source, &source +1); // visitor auto visitor = []( int64_t topNode, const DistanceMap & distances, const PredecessorsMap & predecessors ){ return true; }; runImpl(edgeWeights, subgraphMask, visitor); } template<class EDGE_WEGIHTS, class SOURCE_ITER, class SUBGRAPH_MASK, class VISITOR> void run( EDGE_WEGIHTS edgeWeights, SOURCE_ITER sourceBegin, SOURCE_ITER sourceEnd, const SUBGRAPH_MASK & subgraphMask, VISITOR && visitor ){ this->initializeMaps(sourceBegin, sourceEnd); this->runImpl(edgeWeights,subgraphMask,visitor); } const DistanceMap & distances()const{ return distMap_; } const PredecessorsMap & predecessors()const{ // is there a reason that this was not returned by ref before ? return predMap_; } private: template< class EDGE_WEGIHTS, class SUBGRAPH_MASK, class VISITOR > void runImpl( const EDGE_WEGIHTS & edgeWeights, // why wasn't this a call by ref ? const SUBGRAPH_MASK & subgraphMask, VISITOR && visitor ){ //target_ = lemon::INVALID; while(!pq_.empty() ){ //&& !finished){ const auto topNode = pq_.top(); pq_.pop(); if(!visitor(topNode, distMap_, predMap_)){ break; } if(subgraphMask.useNode(topNode)){ // loop over all neigbours for(auto adj : g_.adjacency(topNode)){ auto otherNode = adj.node(); const auto edge = adj.edge(); if(subgraphMask.useNode(otherNode) && subgraphMask.useEdge(otherNode)){ if(pq_.contains(otherNode)){ const WeightType currentDist = distMap_[otherNode]; const WeightType alternativeDist = distMap_[topNode]+edgeWeights[edge]; if(alternativeDist<currentDist){ pq_.push(otherNode,alternativeDist); distMap_[otherNode]=alternativeDist; predMap_[otherNode]=topNode; } } else if(predMap_[otherNode]==-1){ const WeightType initialDist = distMap_[topNode]+edgeWeights[edge]; //if(initialDist<=maxDistance) //{ pq_.push(otherNode,initialDist); distMap_[otherNode]=initialDist; predMap_[otherNode]=topNode; //} } } } } } while(!pq_.empty() ){ const auto topNode = pq_.top(); predMap_[topNode] = -1; pq_.pop(); } } template<class SOURCE_ITER> void initializeMaps(SOURCE_ITER sourceBegin, SOURCE_ITER sourceEnd){ for(auto node : g_.nodes()){ predMap_[node] = -1; } for( ; sourceBegin!=sourceEnd; ++sourceBegin){ auto n = *sourceBegin; distMap_[n] = static_cast<WeightType>(0); predMap_[n] = n; pq_.push(n,static_cast<WeightType>(0)); } } const GRAPH & g_; PqType pq_; PredecessorsMap predMap_; DistanceMap distMap_; }; } // namespace nifty::graph } // namespace nifty #endif // NIFTY_GRAPH_SHORTEST_PATH_DIJKSTRA_HXX <|endoftext|>
<commit_before>// Copyright 2015-2018 Elviss Strazdins. All rights reserved. #include "MouseDeviceWin.hpp" #include "core/Engine.hpp" #include "core/windows/NativeWindowWin.hpp" #include "utils/Errors.hpp" namespace ouzel { namespace input { void MouseDeviceWin::setPosition(const Vector2& position) { Vector2 windowLocation = engine->getWindow()->convertNormalizedToWindowLocation(position); HWND nativeWindow = static_cast<NativeWindowWin*>(engine->getWindow()->getNativeWindow())->getNativeWindow(); POINT p; p.x = static_cast<LONG>(windowLocation.x); p.y = static_cast<LONG>(windowLocation.y); ClientToScreen(nativeWindow, &p); SetCursorPos(static_cast<int>(p.x), static_cast<int>(p.y)); } void MouseDeviceWin::setCursorVisible(bool visible) { cursorVisible = visible; } void MouseDeviceWin::setCursorLocked(bool locked) { if (locked) { HWND nativeWindow = static_cast<NativeWindowWin*>(engine->getWindow()->getNativeWindow())->getNativeWindow(); RECT rect; GetWindowRect(nativeWindow, &rect); LONG centerX = (rect.left + rect.right) / 2; LONG centerY = (rect.top + rect.bottom) / 2; rect.left = centerX; rect.right = centerX + 1; rect.top = centerY; rect.bottom = centerY + 1; if (!ClipCursor(&rect)) throw SystemError("Failed to grab pointer"); } else ClipCursor(nullptr); } void MouseDeviceWin::setCursor(NativeCursorWin* newCursor) { cursor = newCursor; } } // namespace input } // namespace ouzel <commit_msg>Throw system_error in MouseDeviceWin<commit_after>// Copyright 2015-2018 Elviss Strazdins. All rights reserved. #include <system_error> #include "MouseDeviceWin.hpp" #include "core/Engine.hpp" #include "core/windows/NativeWindowWin.hpp" namespace ouzel { namespace input { void MouseDeviceWin::setPosition(const Vector2& position) { Vector2 windowLocation = engine->getWindow()->convertNormalizedToWindowLocation(position); HWND nativeWindow = static_cast<NativeWindowWin*>(engine->getWindow()->getNativeWindow())->getNativeWindow(); POINT p; p.x = static_cast<LONG>(windowLocation.x); p.y = static_cast<LONG>(windowLocation.y); ClientToScreen(nativeWindow, &p); SetCursorPos(static_cast<int>(p.x), static_cast<int>(p.y)); } void MouseDeviceWin::setCursorVisible(bool visible) { cursorVisible = visible; } void MouseDeviceWin::setCursorLocked(bool locked) { if (locked) { HWND nativeWindow = static_cast<NativeWindowWin*>(engine->getWindow()->getNativeWindow())->getNativeWindow(); RECT rect; GetWindowRect(nativeWindow, &rect); LONG centerX = (rect.left + rect.right) / 2; LONG centerY = (rect.top + rect.bottom) / 2; rect.left = centerX; rect.right = centerX + 1; rect.top = centerY; rect.bottom = centerY + 1; if (!ClipCursor(&rect)) throw std::system_error(GetLastError(), std::system_category(), "Failed to grab pointer"); } else if (!ClipCursor(nullptr)) throw std::system_error(GetLastError(), std::system_category(), "Failed to free pointer"); } void MouseDeviceWin::setCursor(NativeCursorWin* newCursor) { cursor = newCursor; } } // namespace input } // namespace ouzel <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkObject.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkObject.h" #include "vtkDebugLeaks.h" #include "vtkCommand.h" // Initialize static member that controls warning display static int vtkObjectGlobalWarningDisplay = 1; // avoid dll boundary problems #ifdef _WIN32 void* vtkObject::operator new(size_t nSize) { void* p=malloc(nSize); return p; } void vtkObject::operator delete( void *p ) { free(p); } #endif void vtkObject::SetGlobalWarningDisplay(int val) { vtkObjectGlobalWarningDisplay = val; } int vtkObject::GetGlobalWarningDisplay() { return vtkObjectGlobalWarningDisplay; } //----------------------------------Command/Observer stuff------------------- // class vtkObserver { public: vtkObserver():Command(0),Event(0),Tag(0),Next(0) {} ~vtkObserver(); void PrintSelf(ostream& os, vtkIndent indent); float Priority; vtkCommand *Command; unsigned long Event; unsigned long Tag; vtkObserver *Next; }; void vtkObserver::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "vtkObserver (" << this << ")\n"; indent = indent.GetNextIndent(); os << indent << "Event: " << this->Event << "\n"; os << indent << "EventName: " << vtkCommand::GetStringFromEventId(this->Event) << "\n"; os << indent << "Command: " << this->Command << "\n"; os << indent << "Priority: " << this->Priority << "\n"; os << indent << "Tag: " << this->Tag << "\n"; } class vtkSubjectHelper { public: vtkSubjectHelper():Start(0),Count(1) {} ~vtkSubjectHelper(); unsigned long AddObserver(unsigned long event, vtkCommand *cmd, float p); void RemoveObserver(unsigned long tag); void RemoveObservers(unsigned long event); void InvokeEvent(unsigned long event, void *callData, vtkObject *self); vtkCommand *GetCommand(unsigned long tag); unsigned long GetTag(vtkCommand*); int HasObserver(unsigned long event); void PrintSelf(ostream& os, vtkIndent indent); protected: vtkObserver *Start; unsigned long Count; }; // ------------------------------------vtkObject---------------------- // This operator allows all subclasses of vtkObject to be printed via <<. // It in turn invokes the Print method, which in turn will invoke the // PrintSelf method that all objects should define, if they have anything // interesting to print out. ostream& operator<<(ostream& os, vtkObject& o) { o.Print(os); return os; } // Create an object with Debug turned off and modified time initialized // to zero. vtkObject::vtkObject() { this->Debug = 0; this->ReferenceCount = 1; this->SubjectHelper = NULL; this->Modified(); // Insures modified time > than any other time // initial reference count = 1 and reference counting on. } vtkObject::~vtkObject() { vtkDebugMacro(<< "Destructing!"); // warn user if reference counting is on and the object is being referenced // by another object if ( this->ReferenceCount > 0) { vtkErrorMacro(<< "Trying to delete object with non-zero reference count."); } delete this->SubjectHelper; this->SubjectHelper = NULL; } // Delete a vtk object. This method should always be used to delete an object // when the new operator was used to create it. Using the C++ delete method // will not work with reference counting. void vtkObject::Delete() { this->UnRegister((vtkObject *)NULL); } // Return the modification for this object. unsigned long int vtkObject::GetMTime() { return this->MTime.GetMTime(); } void vtkObject::Print(ostream& os) { vtkIndent indent; this->PrintHeader(os,0); this->PrintSelf(os, indent.GetNextIndent()); this->PrintTrailer(os,0); } void vtkObject::PrintHeader(ostream& os, vtkIndent indent) { os << indent << this->GetClassName() << " (" << this << ")\n"; } // Chaining method to print an object's instance variables, as well as // its superclasses. void vtkObject::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "Debug: " << (this->Debug ? "On\n" : "Off\n"); os << indent << "Modified Time: " << this->GetMTime() << "\n"; os << indent << "Reference Count: " << this->ReferenceCount << "\n"; if ( this->SubjectHelper ) { this->SubjectHelper->PrintSelf(os,indent); } else { os << indent << "Registered Events: (none)\n"; } } void vtkObject::PrintTrailer(ostream& os, vtkIndent indent) { os << indent << "\n"; } // Turn debugging output on. void vtkObject::DebugOn() { this->Debug = 1; } // Turn debugging output off. void vtkObject::DebugOff() { this->Debug = 0; } // Get the value of the debug flag. unsigned char vtkObject::GetDebug() { return this->Debug; } // Set the value of the debug flag. A non-zero value turns debugging on. void vtkObject::SetDebug(unsigned char debugFlag) { this->Debug = debugFlag; } // This method is called when vtkErrorMacro executes. It allows // the debugger to break on error. void vtkObject::BreakOnError() { } // Description: // Sets the reference count (use with care) void vtkObject::SetReferenceCount(int ref) { this->ReferenceCount = ref; vtkDebugMacro(<< "Reference Count set to " << this->ReferenceCount); } // Description: // Increase the reference count (mark as used by another object). void vtkObject::Register(vtkObject* o) { this->ReferenceCount++; if ( o ) { vtkDebugMacro(<< "Registered by " << o->GetClassName() << " (" << o << "), ReferenceCount = " << this->ReferenceCount); } else { vtkDebugMacro(<< "Registered by NULL, ReferenceCount = " << this->ReferenceCount); } if (this->ReferenceCount <= 0) { delete this; } } // Description: // Decrease the reference count (release by another object). void vtkObject::UnRegister(vtkObject* o) { if (o) { vtkDebugMacro(<< "UnRegistered by " << o->GetClassName() << " (" << o << "), ReferenceCount = " << (this->ReferenceCount-1)); } else { vtkDebugMacro(<< "UnRegistered by NULL, ReferenceCount = " << (this->ReferenceCount-1)); } if (--this->ReferenceCount <= 0) { #ifdef VTK_DEBUG_LEAKS vtkDebugLeaks::DestructClass(this->GetClassName()); #endif // invoke the delete method this->InvokeEvent(vtkCommand::DeleteEvent,NULL); delete this; } } int vtkObject::IsTypeOf(const char *name) { if ( !strcmp("vtkObject",name) ) { return 1; } return 0; } int vtkObject::IsA(const char *type) { return this->vtkObject::IsTypeOf(type); } vtkObject *vtkObject::SafeDownCast(vtkObject *o) { return (vtkObject *)o; } void vtkObject::CollectRevisions(ostream& os) { os << "vtkObject 1.73\n"; } //----------------------------------Command/Observer stuff------------------- // vtkObserver::~vtkObserver() { this->Command->UnRegister(); } vtkSubjectHelper::~vtkSubjectHelper() { vtkObserver *elem = this->Start; vtkObserver *next; while (elem) { next = elem->Next; delete elem; elem = next; } this->Start = NULL; } unsigned long vtkSubjectHelper:: AddObserver(unsigned long event, vtkCommand *cmd, float p) { vtkObserver *elem; // initialize the new observer element elem = new vtkObserver; elem->Priority = p; elem->Next = NULL; elem->Event = event; elem->Command = cmd; cmd->Register(); elem->Tag = this->Count; this->Count++; // now insert into the list // if no other elements in the list then this is Start if (!this->Start) { this->Start = elem; } else { // insert high priority first vtkObserver* prev = 0; vtkObserver* pos = this->Start; while(pos->Priority >= elem->Priority && pos->Next) { prev = pos; pos = pos->Next; } // pos is Start and elem should not be start if(pos->Priority > elem->Priority) { pos->Next = elem; } else { if(prev) { prev->Next = elem; } elem->Next = pos; // check to see if the new element is the start if(pos == this->Start) { this->Start = elem; } } } return elem->Tag; } void vtkSubjectHelper::RemoveObserver(unsigned long tag) { vtkObserver *elem; vtkObserver *prev; vtkObserver *next; elem = this->Start; prev = NULL; while (elem) { if (elem->Tag == tag) { if (prev) { prev->Next = elem->Next; next = prev->Next; } else { this->Start = elem->Next; next = this->Start; } delete elem; elem = next; } else { prev = elem; elem = elem->Next; } } } void vtkSubjectHelper::RemoveObservers(unsigned long event) { vtkObserver *elem; vtkObserver *prev; vtkObserver *next; elem = this->Start; prev = NULL; while (elem) { if (elem->Event == event) { if (prev) { prev->Next = elem->Next; next = prev->Next; } else { this->Start = elem->Next; next = this->Start; } delete elem; elem = next; } else { prev = elem; elem = elem->Next; } } } int vtkSubjectHelper::HasObserver(unsigned long event) { vtkObserver *elem = this->Start; while (elem) { if (elem->Event == event || elem->Event == vtkCommand::AnyEvent) { return 1; } elem = elem->Next; } return 0; } void vtkSubjectHelper::InvokeEvent(unsigned long event, void *callData, vtkObject *self) { vtkObserver *elem = this->Start; vtkObserver *next; while (elem) { // store the next pointer because elem could disappear due to Command next = elem->Next; if (elem->Event == event || elem->Event == vtkCommand::AnyEvent) { int abort = 0; elem->Command->SetAbortFlagPointer(&abort); elem->Command->Execute(self,event,callData); // if the command set the abort flag, then stop firing events // and return if(abort) { return; } } elem = next; } } unsigned long vtkSubjectHelper::GetTag(vtkCommand* cmd) { vtkObserver *elem = this->Start; while (elem) { if (elem->Command == cmd) { return elem->Tag; } elem = elem->Next; } return 0; } vtkCommand *vtkSubjectHelper::GetCommand(unsigned long tag) { vtkObserver *elem = this->Start; while (elem) { if (elem->Tag == tag) { return elem->Command; } elem = elem->Next; } return NULL; } void vtkSubjectHelper::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "Registered Observers:\n"; indent = indent.GetNextIndent(); vtkObserver *elem = this->Start; if ( !elem ) { os << indent << "(none)\n"; return; } for ( ; elem; elem=elem->Next ) { elem->PrintSelf(os, indent); } } //--------------------------------vtkObject observer----------------------- unsigned long vtkObject::AddObserver(unsigned long event, vtkCommand *cmd, float p) { if (!this->SubjectHelper) { this->SubjectHelper = new vtkSubjectHelper; } return this->SubjectHelper->AddObserver(event,cmd, p); } unsigned long vtkObject::AddObserver(const char *event,vtkCommand *cmd, float p) { return this->AddObserver(vtkCommand::GetEventIdFromString(event), cmd, p); } vtkCommand *vtkObject::GetCommand(unsigned long tag) { if (this->SubjectHelper) { return this->SubjectHelper->GetCommand(tag); } return NULL; } void vtkObject::RemoveObserver(unsigned long tag) { if (this->SubjectHelper) { this->SubjectHelper->RemoveObserver(tag); } } void vtkObject::RemoveObserver(vtkCommand* c) { if (this->SubjectHelper) { unsigned long tag = this->SubjectHelper->GetTag(c); while(tag) { this->SubjectHelper->RemoveObserver(tag); tag = this->SubjectHelper->GetTag(c); } } } void vtkObject::RemoveObservers(unsigned long event) { if (this->SubjectHelper) { this->SubjectHelper->RemoveObservers(event); } } void vtkObject::RemoveObservers(const char *event) { this->RemoveObservers(vtkCommand::GetEventIdFromString(event)); } void vtkObject::InvokeEvent(unsigned long event, void *callData) { if (this->SubjectHelper) { this->SubjectHelper->InvokeEvent(event,callData, this); } } void vtkObject::InvokeEvent(const char *event, void *callData) { this->InvokeEvent(vtkCommand::GetEventIdFromString(event), callData); } int vtkObject::HasObserver(unsigned long event) { if (this->SubjectHelper) { return this->SubjectHelper->HasObserver(event); } return 0; } int vtkObject::HasObserver(const char *event) { return this->HasObserver(vtkCommand::GetEventIdFromString(event)); } void vtkObject::Modified() { this->MTime.Modified(); this->InvokeEvent(vtkCommand::ModifiedEvent,NULL); } <commit_msg>ENH: Initialize Priority in constructor<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkObject.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkObject.h" #include "vtkDebugLeaks.h" #include "vtkCommand.h" // Initialize static member that controls warning display static int vtkObjectGlobalWarningDisplay = 1; // avoid dll boundary problems #ifdef _WIN32 void* vtkObject::operator new(size_t nSize) { void* p=malloc(nSize); return p; } void vtkObject::operator delete( void *p ) { free(p); } #endif void vtkObject::SetGlobalWarningDisplay(int val) { vtkObjectGlobalWarningDisplay = val; } int vtkObject::GetGlobalWarningDisplay() { return vtkObjectGlobalWarningDisplay; } //----------------------------------Command/Observer stuff------------------- // class vtkObserver { public: vtkObserver():Command(0),Event(0),Tag(0),Next(0),Priority(0.0) {} ~vtkObserver(); void PrintSelf(ostream& os, vtkIndent indent); float Priority; vtkCommand *Command; unsigned long Event; unsigned long Tag; vtkObserver *Next; }; void vtkObserver::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "vtkObserver (" << this << ")\n"; indent = indent.GetNextIndent(); os << indent << "Event: " << this->Event << "\n"; os << indent << "EventName: " << vtkCommand::GetStringFromEventId(this->Event) << "\n"; os << indent << "Command: " << this->Command << "\n"; os << indent << "Priority: " << this->Priority << "\n"; os << indent << "Tag: " << this->Tag << "\n"; } class vtkSubjectHelper { public: vtkSubjectHelper():Start(0),Count(1) {} ~vtkSubjectHelper(); unsigned long AddObserver(unsigned long event, vtkCommand *cmd, float p); void RemoveObserver(unsigned long tag); void RemoveObservers(unsigned long event); void InvokeEvent(unsigned long event, void *callData, vtkObject *self); vtkCommand *GetCommand(unsigned long tag); unsigned long GetTag(vtkCommand*); int HasObserver(unsigned long event); void PrintSelf(ostream& os, vtkIndent indent); protected: vtkObserver *Start; unsigned long Count; }; // ------------------------------------vtkObject---------------------- // This operator allows all subclasses of vtkObject to be printed via <<. // It in turn invokes the Print method, which in turn will invoke the // PrintSelf method that all objects should define, if they have anything // interesting to print out. ostream& operator<<(ostream& os, vtkObject& o) { o.Print(os); return os; } // Create an object with Debug turned off and modified time initialized // to zero. vtkObject::vtkObject() { this->Debug = 0; this->ReferenceCount = 1; this->SubjectHelper = NULL; this->Modified(); // Insures modified time > than any other time // initial reference count = 1 and reference counting on. } vtkObject::~vtkObject() { vtkDebugMacro(<< "Destructing!"); // warn user if reference counting is on and the object is being referenced // by another object if ( this->ReferenceCount > 0) { vtkErrorMacro(<< "Trying to delete object with non-zero reference count."); } delete this->SubjectHelper; this->SubjectHelper = NULL; } // Delete a vtk object. This method should always be used to delete an object // when the new operator was used to create it. Using the C++ delete method // will not work with reference counting. void vtkObject::Delete() { this->UnRegister((vtkObject *)NULL); } // Return the modification for this object. unsigned long int vtkObject::GetMTime() { return this->MTime.GetMTime(); } void vtkObject::Print(ostream& os) { vtkIndent indent; this->PrintHeader(os,0); this->PrintSelf(os, indent.GetNextIndent()); this->PrintTrailer(os,0); } void vtkObject::PrintHeader(ostream& os, vtkIndent indent) { os << indent << this->GetClassName() << " (" << this << ")\n"; } // Chaining method to print an object's instance variables, as well as // its superclasses. void vtkObject::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "Debug: " << (this->Debug ? "On\n" : "Off\n"); os << indent << "Modified Time: " << this->GetMTime() << "\n"; os << indent << "Reference Count: " << this->ReferenceCount << "\n"; if ( this->SubjectHelper ) { this->SubjectHelper->PrintSelf(os,indent); } else { os << indent << "Registered Events: (none)\n"; } } void vtkObject::PrintTrailer(ostream& os, vtkIndent indent) { os << indent << "\n"; } // Turn debugging output on. void vtkObject::DebugOn() { this->Debug = 1; } // Turn debugging output off. void vtkObject::DebugOff() { this->Debug = 0; } // Get the value of the debug flag. unsigned char vtkObject::GetDebug() { return this->Debug; } // Set the value of the debug flag. A non-zero value turns debugging on. void vtkObject::SetDebug(unsigned char debugFlag) { this->Debug = debugFlag; } // This method is called when vtkErrorMacro executes. It allows // the debugger to break on error. void vtkObject::BreakOnError() { } // Description: // Sets the reference count (use with care) void vtkObject::SetReferenceCount(int ref) { this->ReferenceCount = ref; vtkDebugMacro(<< "Reference Count set to " << this->ReferenceCount); } // Description: // Increase the reference count (mark as used by another object). void vtkObject::Register(vtkObject* o) { this->ReferenceCount++; if ( o ) { vtkDebugMacro(<< "Registered by " << o->GetClassName() << " (" << o << "), ReferenceCount = " << this->ReferenceCount); } else { vtkDebugMacro(<< "Registered by NULL, ReferenceCount = " << this->ReferenceCount); } if (this->ReferenceCount <= 0) { delete this; } } // Description: // Decrease the reference count (release by another object). void vtkObject::UnRegister(vtkObject* o) { if (o) { vtkDebugMacro(<< "UnRegistered by " << o->GetClassName() << " (" << o << "), ReferenceCount = " << (this->ReferenceCount-1)); } else { vtkDebugMacro(<< "UnRegistered by NULL, ReferenceCount = " << (this->ReferenceCount-1)); } if (--this->ReferenceCount <= 0) { #ifdef VTK_DEBUG_LEAKS vtkDebugLeaks::DestructClass(this->GetClassName()); #endif // invoke the delete method this->InvokeEvent(vtkCommand::DeleteEvent,NULL); delete this; } } int vtkObject::IsTypeOf(const char *name) { if ( !strcmp("vtkObject",name) ) { return 1; } return 0; } int vtkObject::IsA(const char *type) { return this->vtkObject::IsTypeOf(type); } vtkObject *vtkObject::SafeDownCast(vtkObject *o) { return (vtkObject *)o; } void vtkObject::CollectRevisions(ostream& os) { os << "vtkObject 1.74\n"; } //----------------------------------Command/Observer stuff------------------- // vtkObserver::~vtkObserver() { this->Command->UnRegister(); } vtkSubjectHelper::~vtkSubjectHelper() { vtkObserver *elem = this->Start; vtkObserver *next; while (elem) { next = elem->Next; delete elem; elem = next; } this->Start = NULL; } unsigned long vtkSubjectHelper:: AddObserver(unsigned long event, vtkCommand *cmd, float p) { vtkObserver *elem; // initialize the new observer element elem = new vtkObserver; elem->Priority = p; elem->Next = NULL; elem->Event = event; elem->Command = cmd; cmd->Register(); elem->Tag = this->Count; this->Count++; // now insert into the list // if no other elements in the list then this is Start if (!this->Start) { this->Start = elem; } else { // insert high priority first vtkObserver* prev = 0; vtkObserver* pos = this->Start; while(pos->Priority >= elem->Priority && pos->Next) { prev = pos; pos = pos->Next; } // pos is Start and elem should not be start if(pos->Priority > elem->Priority) { pos->Next = elem; } else { if(prev) { prev->Next = elem; } elem->Next = pos; // check to see if the new element is the start if(pos == this->Start) { this->Start = elem; } } } return elem->Tag; } void vtkSubjectHelper::RemoveObserver(unsigned long tag) { vtkObserver *elem; vtkObserver *prev; vtkObserver *next; elem = this->Start; prev = NULL; while (elem) { if (elem->Tag == tag) { if (prev) { prev->Next = elem->Next; next = prev->Next; } else { this->Start = elem->Next; next = this->Start; } delete elem; elem = next; } else { prev = elem; elem = elem->Next; } } } void vtkSubjectHelper::RemoveObservers(unsigned long event) { vtkObserver *elem; vtkObserver *prev; vtkObserver *next; elem = this->Start; prev = NULL; while (elem) { if (elem->Event == event) { if (prev) { prev->Next = elem->Next; next = prev->Next; } else { this->Start = elem->Next; next = this->Start; } delete elem; elem = next; } else { prev = elem; elem = elem->Next; } } } int vtkSubjectHelper::HasObserver(unsigned long event) { vtkObserver *elem = this->Start; while (elem) { if (elem->Event == event || elem->Event == vtkCommand::AnyEvent) { return 1; } elem = elem->Next; } return 0; } void vtkSubjectHelper::InvokeEvent(unsigned long event, void *callData, vtkObject *self) { vtkObserver *elem = this->Start; vtkObserver *next; while (elem) { // store the next pointer because elem could disappear due to Command next = elem->Next; if (elem->Event == event || elem->Event == vtkCommand::AnyEvent) { int abort = 0; elem->Command->SetAbortFlagPointer(&abort); elem->Command->Execute(self,event,callData); // if the command set the abort flag, then stop firing events // and return if(abort) { return; } } elem = next; } } unsigned long vtkSubjectHelper::GetTag(vtkCommand* cmd) { vtkObserver *elem = this->Start; while (elem) { if (elem->Command == cmd) { return elem->Tag; } elem = elem->Next; } return 0; } vtkCommand *vtkSubjectHelper::GetCommand(unsigned long tag) { vtkObserver *elem = this->Start; while (elem) { if (elem->Tag == tag) { return elem->Command; } elem = elem->Next; } return NULL; } void vtkSubjectHelper::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "Registered Observers:\n"; indent = indent.GetNextIndent(); vtkObserver *elem = this->Start; if ( !elem ) { os << indent << "(none)\n"; return; } for ( ; elem; elem=elem->Next ) { elem->PrintSelf(os, indent); } } //--------------------------------vtkObject observer----------------------- unsigned long vtkObject::AddObserver(unsigned long event, vtkCommand *cmd, float p) { if (!this->SubjectHelper) { this->SubjectHelper = new vtkSubjectHelper; } return this->SubjectHelper->AddObserver(event,cmd, p); } unsigned long vtkObject::AddObserver(const char *event,vtkCommand *cmd, float p) { return this->AddObserver(vtkCommand::GetEventIdFromString(event), cmd, p); } vtkCommand *vtkObject::GetCommand(unsigned long tag) { if (this->SubjectHelper) { return this->SubjectHelper->GetCommand(tag); } return NULL; } void vtkObject::RemoveObserver(unsigned long tag) { if (this->SubjectHelper) { this->SubjectHelper->RemoveObserver(tag); } } void vtkObject::RemoveObserver(vtkCommand* c) { if (this->SubjectHelper) { unsigned long tag = this->SubjectHelper->GetTag(c); while(tag) { this->SubjectHelper->RemoveObserver(tag); tag = this->SubjectHelper->GetTag(c); } } } void vtkObject::RemoveObservers(unsigned long event) { if (this->SubjectHelper) { this->SubjectHelper->RemoveObservers(event); } } void vtkObject::RemoveObservers(const char *event) { this->RemoveObservers(vtkCommand::GetEventIdFromString(event)); } void vtkObject::InvokeEvent(unsigned long event, void *callData) { if (this->SubjectHelper) { this->SubjectHelper->InvokeEvent(event,callData, this); } } void vtkObject::InvokeEvent(const char *event, void *callData) { this->InvokeEvent(vtkCommand::GetEventIdFromString(event), callData); } int vtkObject::HasObserver(unsigned long event) { if (this->SubjectHelper) { return this->SubjectHelper->HasObserver(event); } return 0; } int vtkObject::HasObserver(const char *event) { return this->HasObserver(vtkCommand::GetEventIdFromString(event)); } void vtkObject::Modified() { this->MTime.Modified(); this->InvokeEvent(vtkCommand::ModifiedEvent,NULL); } <|endoftext|>
<commit_before>#ifndef INCLUDE_ACKWARD_QUEUE_EXCEPTIONS_HPP #define INCLUDE_ACKWARD_QUEUE_EXCEPTIONS_HPP #include <ackward/core/Exceptions.hpp> namespace ackward { namespace queue { /** \\rst Exception raised when non-blocking ``get()`` (or ``get_nowait()``) is called on a ``Queue`` object which is empty. See `<http://docs.python.org/library/queue.html#Queue.Empty>`_. \endrst */ class Full : public core::Exception {}; /** \\rst Exception raised when non-blocking ``put()`` (or ``put_nowait()``) is called on a ``Queue`` object which is full. See `<http://docs.python.org/library/queue.html#Queue.Full>`_. \endrst */ class Empty : public core::Exception {}; } } #endif <commit_msg>fixed formatting problem in queue exceptions.<commit_after>#ifndef INCLUDE_ACKWARD_QUEUE_EXCEPTIONS_HPP #define INCLUDE_ACKWARD_QUEUE_EXCEPTIONS_HPP #include <ackward/core/Exceptions.hpp> namespace ackward { namespace queue { /** \rst Exception raised when non-blocking ``get()`` (or ``get_nowait()``) is called on a ``Queue`` object which is empty. See `<http://docs.python.org/library/queue.html#Queue.Empty>`_. \endrst */ class Full : public core::Exception {}; /** \rst Exception raised when non-blocking ``put()`` (or ``put_nowait()``) is called on a ``Queue`` object which is full. See `<http://docs.python.org/library/queue.html#Queue.Full>`_. \endrst */ class Empty : public core::Exception {}; } } #endif <|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_CORE_MAIN_MENU_MAIN_MENU_HPP #define RJ_CORE_MAIN_MENU_MAIN_MENU_HPP #include "component_manager.hpp" #include "items.hpp" #include "menu_levels.hpp" #include "menu_start.hpp" #include "title.hpp" #include <rectojump/core/game_window.hpp> #include <rectojump/core/render.hpp> #include <rectojump/game/components/player.hpp> #include <rectojump/game/factory.hpp> #include <rectojump/global/common.hpp> #include <rectojump/shared/level_manager/level_manager.hpp> #include <rectojump/shared/data_manager.hpp> #include <rectojump/shared/utils.hpp> #include <mlk/signals_slots/slot.h> #include <mlk/tools/bitset.h> #include <mlk/tools/enum_utl.h> #include <SFML/Graphics.hpp> namespace rj { class game; class game_handler; class main_menu { friend class component_manager<main_menu>; game& m_game; game_window& m_gamewindow; data_manager& m_datamgr; level_manager& m_lvmgr; sf::Font m_font{m_datamgr.get_as<sf::Font>("Fipps-Regular.otf")}; const vec2f m_center{static_cast<vec2f>(m_gamewindow.get_size()) / 2.f}; const sf::Color m_def_fontcolor{to_rgb("#797979") /*"#797979"_rgb*/}; // TODO: QTC dont supports that custom literals yet const sf::Color m_act_fontcolor{to_rgb("#f15ede") /*"#f15ede"_rgb*/}; // background sf::RectangleShape m_background; sf::Texture m_background_texture{m_datamgr.get_as<sf::Texture>("menu_side.png")}; // menu components component_manager<main_menu> m_componentmgr{*this}; comp_ptr<menu_start<main_menu>> m_start{m_componentmgr.create_comp<menu_start<main_menu>, menu_state::menu_start>()}; comp_ptr<menu_levels<main_menu>> m_levels{m_componentmgr.create_comp<menu_levels<main_menu>, menu_state::menu_levels>()}; comp_ptr<title<main_menu>> m_title{m_componentmgr.create_comp<title<main_menu>, menu_state::title>()}; // menu states mlk::ebitset<menu_state, menu_state::num> m_current_menu; public: main_menu(game& g, game_window& gw, data_manager& dm, level_manager& lvmgr) : m_game{g}, m_gamewindow{gw}, m_datamgr{dm}, m_lvmgr{lvmgr} {this->init();} bool is_active(menu_state s) {return m_current_menu & s;} void exec_current_itemevent() {m_start->get_items().call_current_event();} template<menu_state new_state> void do_menu_switch() { m_current_menu.remove_all(); m_current_menu |= new_state; m_current_menu |= menu_state::title; } void update(dur duration) { m_componentmgr.update(duration); } void render() { render::render_object(m_game, m_background); m_componentmgr.render(); } // getters items& get_items() noexcept {return m_start->get_items();} level_squares& get_squares() noexcept {return m_levels->get_squares();} game_window& get_gamewindow() noexcept {return m_gamewindow;} data_manager& get_datamgr() const noexcept {return m_datamgr;} level_manager& get_lvmgr() const noexcept {return m_lvmgr;} const sf::Color& get_act_fontcolor() const noexcept {return m_act_fontcolor;} const sf::Color& get_def_fontcolor() const noexcept {return m_def_fontcolor;} private: void init() { m_current_menu |= menu_state::menu_start; m_current_menu |= menu_state::title; this->setup_events(); this->setup_interface(); } void setup_events() { m_start->get_items().on_event("play", [this] { this->do_menu_switch<menu_state::menu_levels>(); m_title->set_text("Levels"); }); } void setup_interface() { // background m_background.setSize(vec2f{m_gamewindow.get_size()}); m_background.setPosition({0.f, 0.f}); m_background.setTexture(&m_background_texture); } }; } #endif // RJ_CORE_MAIN_MENU_MAIN_MENU_HPP <commit_msg>only one possible current state & other<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_CORE_MAIN_MENU_MAIN_MENU_HPP #define RJ_CORE_MAIN_MENU_MAIN_MENU_HPP #include "component_manager.hpp" #include "items.hpp" #include "menu_levels.hpp" #include "menu_start.hpp" #include "title.hpp" #include <rectojump/core/game_window.hpp> #include <rectojump/core/render.hpp> #include <rectojump/game/components/player.hpp> #include <rectojump/game/factory.hpp> #include <rectojump/global/common.hpp> #include <rectojump/shared/level_manager/level_manager.hpp> #include <rectojump/shared/data_manager.hpp> #include <rectojump/shared/utils.hpp> #include <mlk/signals_slots/slot.h> #include <mlk/tools/bitset.h> #include <mlk/tools/enum_utl.h> #include <SFML/Graphics.hpp> namespace rj { class game; class game_handler; class main_menu { friend class component_manager<main_menu>; game& m_game; game_window& m_gamewindow; data_manager& m_datamgr; level_manager& m_lvmgr; sf::Font m_font{m_datamgr.get_as<sf::Font>("Fipps-Regular.otf")}; const vec2f m_center{static_cast<vec2f>(m_gamewindow.get_size()) / 2.f}; const sf::Color m_def_fontcolor{to_rgb("#797979") /*"#797979"_rgb*/}; // TODO: QTC dont supports that custom literals yet const sf::Color m_act_fontcolor{to_rgb("#f15ede") /*"#f15ede"_rgb*/}; // background sf::RectangleShape m_background; sf::Texture m_background_texture{m_datamgr.get_as<sf::Texture>("menu_side.png")}; // components (menus) component_manager<main_menu> m_componentmgr{*this}; comp_ptr<menu_start<main_menu>> m_start{m_componentmgr.create_comp<menu_start<main_menu>, menu_state::menu_start>()}; comp_ptr<menu_levels<main_menu>> m_levels{m_componentmgr.create_comp<menu_levels<main_menu>, menu_state::menu_levels>()}; // other components (not menus) title m_title{m_game, m_font, m_center}; // menu state menu_state m_current_state{menu_state::menu_start}; public: main_menu(game& g, game_window& gw, data_manager& dm, level_manager& lvmgr) : m_game{g}, m_gamewindow{gw}, m_datamgr{dm}, m_lvmgr{lvmgr} {this->init();} bool is_active(menu_state s) {return m_current_state == s;} void call_current_itemevent() { auto ptr(m_componentmgr.get_comp_from_type(m_current_state)); if(ptr != nullptr) ptr->get_items().call_current_event(); } template<menu_state new_state> void do_menu_switch() { m_current_state = new_state; } void update(dur duration) { m_componentmgr.update(duration); m_title.update(duration); } void render() { render::render_object(m_game, m_background); // render bg first !! m_componentmgr.render(); m_title.render(); } void on_key_up() { auto ptr(m_componentmgr.get_comp_from_type(m_current_state)); if(ptr != nullptr) ptr->on_key_up(); } void on_key_down() { auto ptr(m_componentmgr.get_comp_from_type(m_current_state)); if(ptr != nullptr) ptr->on_key_down(); } // getters items& get_items() noexcept {return m_start->get_items();} level_squares& get_squares() noexcept {return m_levels->get_squares();} game_window& get_gamewindow() noexcept {return m_gamewindow;} data_manager& get_datamgr() const noexcept {return m_datamgr;} level_manager& get_lvmgr() const noexcept {return m_lvmgr;} const sf::Color& get_act_fontcolor() const noexcept {return m_act_fontcolor;} const sf::Color& get_def_fontcolor() const noexcept {return m_def_fontcolor;} private: void init() { this->setup_events(); this->setup_interface(); } void setup_events() { m_start->get_items().on_event("play", [this] { this->do_menu_switch<menu_state::menu_levels>(); m_title.set_text("Levels"); }); m_start->get_items().on_event("quit", [this]{m_gamewindow.stop();}); m_levels->get_items().on_event("lv_local", []{std::cout << "local pressed" << std::endl;}); } void setup_interface() { // background m_background.setSize(vec2f{m_gamewindow.get_size()}); m_background.setPosition({0.f, 0.f}); m_background.setTexture(&m_background_texture); } }; } #endif // RJ_CORE_MAIN_MENU_MAIN_MENU_HPP <|endoftext|>
<commit_before>#include <jni.h> #include <errno.h> #include <EGL/egl.h> #include <GLES/gl.h> #include <android_native_app_glue.h> #include <squirrel.h> #include <sqstdio.h> #include <sqstdaux.h> #include <main.h> #include <sqfunc.h> /* global pointer to application engine */ struct engine *g_engine; /* * extern common functions */ extern void LOGI(const SQChar* msg); extern void LOGW(const SQChar* msg); extern void LOGE(const SQChar* msg); extern SQInteger sq_lexer(SQUserPointer asset); extern SQInteger emoImportScript(HSQUIRRELVM v); extern SQInteger emoSetOptions(HSQUIRRELVM v); extern void emoUpdateOptions(SQInteger value); extern SQBool loadScriptFromAsset(const char* fname); /** * Initialize the framework */ void emo_init_engine(struct engine* engine) { engine->sqvm = sq_open(SQUIRREL_VM_INITIAL_STACK_SIZE); engine->lastError = EMO_NO_ERROR; // disable drawframe callback to improve performance (default) engine->enableOnDrawFrame = SQFalse; // enable perspective hint to nicest (default) engine->enablePerspectiveNicest = SQTrue; // init Squirrel VM initSQVM(engine->sqvm); // initialize squirrel functions register_global_func(engine->sqvm, emoImportScript, "emo_import"); register_global_func(engine->sqvm, emoSetOptions, "emo_options"); // load main script loadScriptFromAsset(SQUIRREL_MAIN_SCRIPT); // force fullscreen emoUpdateOptions(OPT_WINDOW_FORCE_FULLSCREEN); // call onLoad() callSqFunction(engine->sqvm, "onLoad"); } /* * Initialize the display */ void emo_init_display(struct engine* engine) { /* initialize OpenGL state */ if (engine->enablePerspectiveNicest) { glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } else { glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); } glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glDisable(GL_MULTISAMPLE); glDisable(GL_DITHER); glDisable(GL_COLOR_ARRAY); glEnable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_COORD_ARRAY); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_VERTEX_ARRAY); glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glCullFace(GL_BACK); } /* * Draw current frame */ void emo_draw_frame(struct engine* engine) { glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); if (engine->enableOnDrawFrame) { callSqFunction(engine->sqvm, "onDrawFrame"); } } /* * Terminate the framework */ void emo_dispose_engine(struct engine* engine) { callSqFunction(engine->sqvm, "onDispose"); sq_close(engine->sqvm); } /* * Process motion event */ static int32_t emo_event_motion(struct android_app* app, AInputEvent* event) { struct engine* engine = (struct engine*)app->userData; size_t pointerCount = AMotionEvent_getPointerCount(event); const int paramCount = 8; for (size_t i = 0; i < pointerCount; i++) { size_t pointerId = AMotionEvent_getPointerId(event, i); size_t action = AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_MASK; size_t pointerIndex = i; if (action == AMOTION_EVENT_ACTION_POINTER_DOWN || action == AMOTION_EVENT_ACTION_POINTER_UP) { pointerIndex = (AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; pointerId = AMotionEvent_getPointerId(event, pointerIndex); } float param[paramCount] = { pointerId, action, AMotionEvent_getX(event, pointerIndex), AMotionEvent_getY(event, pointerIndex), AMotionEvent_getDownTime(event), AMotionEvent_getEventTime(event), AInputEvent_getDeviceId(event), AInputEvent_getSource(event) }; if (callSqFunction_Bool_Floats(engine->sqvm, "onMotionEvent", param, paramCount, false)) { return 1; } } return 0; } /* * Process key event */ static int32_t emo_event_key(struct android_app* app, AInputEvent* event) { struct engine* engine = (struct engine*)app->userData; float param[MOTION_EVENT_PARAMS_SIZE] = { AKeyEvent_getAction(event), AKeyEvent_getKeyCode(event), AKeyEvent_getRepeatCount(event), AKeyEvent_getMetaState(event), AKeyEvent_getDownTime(event), AKeyEvent_getEventTime(event), AInputEvent_getDeviceId(event), AInputEvent_getSource(event) }; if (callSqFunction_Bool_Floats(engine->sqvm, "onKeyEvent", param, MOTION_EVENT_PARAMS_SIZE, false)) { return 1; } return 0; } /** * Process the input event. */ int32_t emo_handle_input(struct android_app* app, AInputEvent* event) { if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { return emo_event_motion(app, event); } else if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY) { return emo_event_key(app, event); } return 0; } /* * Gained focus */ void emo_gained_focus(struct engine* engine) { callSqFunction(engine->sqvm, "onGainedFocus"); engine->animating = 1; } /* * Lost focus */ void emo_lost_focus(struct engine* engine) { callSqFunction(engine->sqvm, "onLostFocus"); engine->animating = 0; } /** * Command from main thread: the system is running low on memory. * Try to reduce your memory use. */ void emo_low_memory(struct engine* engine) { callSqFunction(engine->sqvm, "onLowMemory"); } /** * Initialize an EGL context for the current display. */ static int engine_init_display(struct engine* engine) { /* * Here specify the attributes of the desired configuration. * Below, we select an EGLConfig with at least 8 bits per color * component compatible with on-screen windows */ const EGLint attribs[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8, EGL_NONE }; EGLint w, h, format; EGLint numConfigs; EGLConfig config; EGLSurface surface; EGLContext context; EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(display, 0, 0); /* Here, the application chooses the configuration it desires. In this * sample, we have a very simplified selection process, where we pick * the first EGLConfig that matches our criteria */ eglChooseConfig(display, attribs, &config, 1, &numConfigs); /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is * guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). * As soon as we picked a EGLConfig, we can safely reconfigure the * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */ eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format); surface = eglCreateWindowSurface(display, config, engine->app->window, NULL); context = eglCreateContext(display, config, NULL, NULL); if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) { LOGW("Unable to eglMakeCurrent"); return -1; } eglQuerySurface(display, surface, EGL_WIDTH, &w); eglQuerySurface(display, surface, EGL_HEIGHT, &h); engine->display = display; engine->context = context; engine->surface = surface; engine->width = w; engine->height = h; emo_init_display(engine); return 0; } /** * Just the current frame in the display. */ static void engine_draw_frame(struct engine* engine) { if (engine->display == NULL) { return; } emo_draw_frame(engine); eglSwapBuffers(engine->display, engine->surface); } /** * Tear down the EGL context currently associated with the display. */ static void engine_term_display(struct engine* engine) { if (engine->display != EGL_NO_DISPLAY) { eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (engine->context != EGL_NO_CONTEXT) { eglDestroyContext(engine->display, engine->context); } if (engine->surface != EGL_NO_SURFACE) { eglDestroySurface(engine->display, engine->surface); } eglTerminate(engine->display); } engine->animating = 0; engine->display = EGL_NO_DISPLAY; engine->context = EGL_NO_CONTEXT; engine->surface = EGL_NO_SURFACE; } /** * Process the next main command. */ static void engine_handle_cmd(struct android_app* app, int32_t cmd) { struct engine* engine = (struct engine*)app->userData; switch (cmd) { case APP_CMD_SAVE_STATE: engine->app->savedState = malloc(sizeof(struct saved_state)); *((struct saved_state*)engine->app->savedState) = engine->state; engine->app->savedStateSize = sizeof(struct saved_state); break; case APP_CMD_INIT_WINDOW: if (engine->app->window != NULL) { engine_init_display(engine); engine_draw_frame(engine); } break; case APP_CMD_TERM_WINDOW: engine_term_display(engine); break; case APP_CMD_GAINED_FOCUS: emo_gained_focus(engine); break; case APP_CMD_LOST_FOCUS: emo_lost_focus(engine); break; case APP_CMD_LOW_MEMORY: emo_low_memory(engine); break; } } /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main(struct android_app* state) { struct engine engine; app_dummy(); memset(&engine, 0, sizeof(engine)); state->userData = &engine; state->onAppCmd = engine_handle_cmd; state->onInputEvent = emo_handle_input; engine.app = state; if (state->savedState != NULL) { engine.state = *(struct saved_state*)state->savedState; } g_engine = &engine; /* Initialize the framework */ emo_init_engine(&engine); while (1) { int ident; int events; struct android_poll_source* source; // If not animating, we will block forever waiting for events. // If animating, we loop until all events are read, then continue // to draw the next frame of animation. while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events, (void**)&source)) >= 0) { // Process this event. if (source != NULL) { source->process(state, source); } // Process the user queue. if (ident == LOOPER_ID_USER) { } // Check if we are exiting. if (state->destroyRequested != 0) { engine_term_display(&engine); emo_dispose_engine(&engine); return; } } if (engine.animating) { // Drawing is throttled to the screen update rate, so there // is no need to do timing here. engine_draw_frame(&engine); } } } <commit_msg>add constants<commit_after>#include <jni.h> #include <errno.h> #include <EGL/egl.h> #include <GLES/gl.h> #include <android_native_app_glue.h> #include <squirrel.h> #include <sqstdio.h> #include <sqstdaux.h> #include <main.h> #include <sqfunc.h> /* global pointer to application engine */ struct engine *g_engine; /* * extern common functions */ extern void LOGI(const SQChar* msg); extern void LOGW(const SQChar* msg); extern void LOGE(const SQChar* msg); extern SQInteger sq_lexer(SQUserPointer asset); extern SQInteger emoImportScript(HSQUIRRELVM v); extern SQInteger emoSetOptions(HSQUIRRELVM v); extern void emoUpdateOptions(SQInteger value); extern SQBool loadScriptFromAsset(const char* fname); /** * Initialize the framework */ void emo_init_engine(struct engine* engine) { engine->sqvm = sq_open(SQUIRREL_VM_INITIAL_STACK_SIZE); engine->lastError = EMO_NO_ERROR; // disable drawframe callback to improve performance (default) engine->enableOnDrawFrame = SQFalse; // enable perspective hint to nicest (default) engine->enablePerspectiveNicest = SQTrue; // init Squirrel VM initSQVM(engine->sqvm); // initialize squirrel functions register_global_func(engine->sqvm, emoImportScript, "emo_import"); register_global_func(engine->sqvm, emoSetOptions, "emo_options"); // load main script loadScriptFromAsset(SQUIRREL_MAIN_SCRIPT); // force fullscreen emoUpdateOptions(OPT_WINDOW_FORCE_FULLSCREEN); // call onLoad() callSqFunction(engine->sqvm, "onLoad"); } /* * Initialize the display */ void emo_init_display(struct engine* engine) { /* initialize OpenGL state */ if (engine->enablePerspectiveNicest) { glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } else { glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST); } glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glDisable(GL_MULTISAMPLE); glDisable(GL_DITHER); glDisable(GL_COLOR_ARRAY); glEnable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_COORD_ARRAY); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_VERTEX_ARRAY); glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glCullFace(GL_BACK); } /* * Draw current frame */ void emo_draw_frame(struct engine* engine) { glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); if (engine->enableOnDrawFrame) { callSqFunction(engine->sqvm, "onDrawFrame"); } } /* * Terminate the framework */ void emo_dispose_engine(struct engine* engine) { callSqFunction(engine->sqvm, "onDispose"); sq_close(engine->sqvm); } /* * Process motion event */ static int32_t emo_event_motion(struct android_app* app, AInputEvent* event) { struct engine* engine = (struct engine*)app->userData; size_t pointerCount = AMotionEvent_getPointerCount(event); for (size_t i = 0; i < pointerCount; i++) { size_t pointerId = AMotionEvent_getPointerId(event, i); size_t action = AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_MASK; size_t pointerIndex = i; if (action == AMOTION_EVENT_ACTION_POINTER_DOWN || action == AMOTION_EVENT_ACTION_POINTER_UP) { pointerIndex = (AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; pointerId = AMotionEvent_getPointerId(event, pointerIndex); } float param[MOTION_EVENT_PARAMS_SIZE] = { pointerId, action, AMotionEvent_getX(event, pointerIndex), AMotionEvent_getY(event, pointerIndex), AMotionEvent_getDownTime(event), AMotionEvent_getEventTime(event), AInputEvent_getDeviceId(event), AInputEvent_getSource(event) }; if (callSqFunction_Bool_Floats(engine->sqvm, "onMotionEvent", param, MOTION_EVENT_PARAMS_SIZE, false)) { return 1; } } return 0; } /* * Process key event */ static int32_t emo_event_key(struct android_app* app, AInputEvent* event) { struct engine* engine = (struct engine*)app->userData; float param[KEY_EVENT_PARAMS_SIZE] = { AKeyEvent_getAction(event), AKeyEvent_getKeyCode(event), AKeyEvent_getRepeatCount(event), AKeyEvent_getMetaState(event), AKeyEvent_getDownTime(event), AKeyEvent_getEventTime(event), AInputEvent_getDeviceId(event), AInputEvent_getSource(event) }; if (callSqFunction_Bool_Floats(engine->sqvm, "onKeyEvent", param, KEY_EVENT_PARAMS_SIZE, false)) { return 1; } return 0; } /** * Process the input event. */ int32_t emo_handle_input(struct android_app* app, AInputEvent* event) { if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { return emo_event_motion(app, event); } else if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY) { return emo_event_key(app, event); } return 0; } /* * Gained focus */ void emo_gained_focus(struct engine* engine) { callSqFunction(engine->sqvm, "onGainedFocus"); engine->animating = 1; } /* * Lost focus */ void emo_lost_focus(struct engine* engine) { callSqFunction(engine->sqvm, "onLostFocus"); engine->animating = 0; } /** * Command from main thread: the system is running low on memory. * Try to reduce your memory use. */ void emo_low_memory(struct engine* engine) { callSqFunction(engine->sqvm, "onLowMemory"); } /** * Initialize an EGL context for the current display. */ static int engine_init_display(struct engine* engine) { /* * Here specify the attributes of the desired configuration. * Below, we select an EGLConfig with at least 8 bits per color * component compatible with on-screen windows */ const EGLint attribs[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8, EGL_NONE }; EGLint w, h, format; EGLint numConfigs; EGLConfig config; EGLSurface surface; EGLContext context; EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(display, 0, 0); /* Here, the application chooses the configuration it desires. In this * sample, we have a very simplified selection process, where we pick * the first EGLConfig that matches our criteria */ eglChooseConfig(display, attribs, &config, 1, &numConfigs); /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is * guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). * As soon as we picked a EGLConfig, we can safely reconfigure the * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */ eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format); surface = eglCreateWindowSurface(display, config, engine->app->window, NULL); context = eglCreateContext(display, config, NULL, NULL); if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) { LOGW("Unable to eglMakeCurrent"); return -1; } eglQuerySurface(display, surface, EGL_WIDTH, &w); eglQuerySurface(display, surface, EGL_HEIGHT, &h); engine->display = display; engine->context = context; engine->surface = surface; engine->width = w; engine->height = h; emo_init_display(engine); return 0; } /** * Just the current frame in the display. */ static void engine_draw_frame(struct engine* engine) { if (engine->display == NULL) { return; } emo_draw_frame(engine); eglSwapBuffers(engine->display, engine->surface); } /** * Tear down the EGL context currently associated with the display. */ static void engine_term_display(struct engine* engine) { if (engine->display != EGL_NO_DISPLAY) { eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (engine->context != EGL_NO_CONTEXT) { eglDestroyContext(engine->display, engine->context); } if (engine->surface != EGL_NO_SURFACE) { eglDestroySurface(engine->display, engine->surface); } eglTerminate(engine->display); } engine->animating = 0; engine->display = EGL_NO_DISPLAY; engine->context = EGL_NO_CONTEXT; engine->surface = EGL_NO_SURFACE; } /** * Process the next main command. */ static void engine_handle_cmd(struct android_app* app, int32_t cmd) { struct engine* engine = (struct engine*)app->userData; switch (cmd) { case APP_CMD_SAVE_STATE: engine->app->savedState = malloc(sizeof(struct saved_state)); *((struct saved_state*)engine->app->savedState) = engine->state; engine->app->savedStateSize = sizeof(struct saved_state); break; case APP_CMD_INIT_WINDOW: if (engine->app->window != NULL) { engine_init_display(engine); engine_draw_frame(engine); } break; case APP_CMD_TERM_WINDOW: engine_term_display(engine); break; case APP_CMD_GAINED_FOCUS: emo_gained_focus(engine); break; case APP_CMD_LOST_FOCUS: emo_lost_focus(engine); break; case APP_CMD_LOW_MEMORY: emo_low_memory(engine); break; } } /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main(struct android_app* state) { struct engine engine; app_dummy(); memset(&engine, 0, sizeof(engine)); state->userData = &engine; state->onAppCmd = engine_handle_cmd; state->onInputEvent = emo_handle_input; engine.app = state; if (state->savedState != NULL) { engine.state = *(struct saved_state*)state->savedState; } g_engine = &engine; /* Initialize the framework */ emo_init_engine(&engine); while (1) { int ident; int events; struct android_poll_source* source; // If not animating, we will block forever waiting for events. // If animating, we loop until all events are read, then continue // to draw the next frame of animation. while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events, (void**)&source)) >= 0) { // Process this event. if (source != NULL) { source->process(state, source); } // Process the user queue. if (ident == LOOPER_ID_USER) { } // Check if we are exiting. if (state->destroyRequested != 0) { engine_term_display(&engine); emo_dispose_engine(&engine); return; } } if (engine.animating) { // Drawing is throttled to the screen update rate, so there // is no need to do timing here. engine_draw_frame(&engine); } } } <|endoftext|>
<commit_before>#include "DHASLogging.h" #include "IOBoard.h" REGISTER_NODE_NAME(IOBoard,"EDISON IO CONTROLLER"); IOBoard::IOBoard() { mPgms = 0; mPgmCount = 0; } IOBoard::~IOBoard() { } bool IOBoard::processData(char* buf, size_t size, Dumais::JSON::JSON& json) { std::string st(buf,size); Dumais::JSON::JSON data; data.parse(st); LOG("IOBoard received " << st); if (data["type"].str() == "initial") { json.addValue("ioboardnode","node"); json.addList("pgms"); mPgmCount = data["pins"].size(); mPgms = 0; for (int i = 0; i < mPgmCount; i++) { uint8_t tmp = 0; if (data["pins"][i].toBool()) tmp = 1; mPgms |= (tmp << i); json["pgms"].addValue(tmp); } return true; } else if (data["type"].str() == "changed") { json.addValue("ioboardnode","node"); json.addValue("changed","subtype"); json.addValue(data["pin"].toInt(),"pin"); json.addList("pgms"); mPgmCount = data["pins"].size(); mPgms = 0; for (int i = 0; i < mPgmCount; i++) { uint8_t tmp = 0; if (data["pins"][i].toBool()) tmp = 1; mPgms |= (tmp << i); json["pgms"].addValue(tmp); } return true; } return false; } void IOBoard::registerCallBacks(ThreadSafeRestEngine* pEngine) { RESTCallBack *p; p = new RESTCallBack(this,&IOBoard::status_callback,"Get PGM status"); pEngine->addCallBack("/dwn/"+mInfo.id+"/status","GET",p); mRestCallbacks.push_back(p); p = new RESTCallBack(this,&IOBoard::setoutput_callback,"set output"); pEngine->addCallBack("/dwn/"+mInfo.id+"/set","GET",p); p->addParam("out","0-4",false); p->addParam("level","0 or 1",false); mRestCallbacks.push_back(p); } void IOBoard::status_callback(RESTContext* context) { RESTParameters* params = context->params; Dumais::JSON::JSON& json = context->returnData; json.addValue("ok","status"); json.addList("pgms"); for (int i = 0; i < mPgmCount; i++) json["pgms"].addValue(((mPgms>>i)&1)); } void IOBoard::setoutput_callback(RESTContext* context) { RESTParameters* params = context->params; Dumais::JSON::JSON& json = context->returnData; std::string out = params->getParam("out"); std::string level = params->getParam("level"); Dumais::JSON::JSON j; j.addValue("set","event"); j.addValue(out,"out"); j.addValue(level,"level"); std::string st = j.stringify(false); this->mInfo.sendQueue->sendToNode(this->mInfo.ip,st.c_str(),st.size()); } <commit_msg>Decoding paradox alarm panel messages<commit_after>#include "DHASLogging.h" #include "IOBoard.h" REGISTER_NODE_NAME(IOBoard,"EDISON IO CONTROLLER"); IOBoard::IOBoard() { mPgms = 0; mPgmCount = 0; } IOBoard::~IOBoard() { } bool IOBoard::processData(char* buf, size_t size, Dumais::JSON::JSON& json) { std::string st(buf,size); Dumais::JSON::JSON data; data.parse(st); LOG("IOBoard received " << st); if (data["type"].str() == "initial") { json.addValue("ioboardnode","node"); json.addList("pgms"); mPgmCount = data["pins"].size(); mPgms = 0; for (int i = 0; i < mPgmCount; i++) { uint8_t tmp = 0; if (data["pins"][i].toBool()) tmp = 1; mPgms |= (tmp << i); json["pgms"].addValue(tmp); } return true; } else if (data["type"].str() == "alarm") { json.addValue("ioboardnode","node"); json.addValue("alarmpanel","subtype"); int group = data["group"].toInt(); int subGroup = data["subgroup"].toInt(); std::string label = data["label"].str(); json.addValue(label,"zonelabel"); if (group == 0) // Zone OK { json.addValue("zoneoff","action"); return true; } else if (group == 1) // Zone open { json.addValue("zoneon","action"); return true; } else if (group == 2) // Partition status { if (subGroup == 14) { json.addValue("Exit delay","action"); } else if (subGroup == 12) { json.addValue("Armed","action"); } else if (subGroup == 13) { json.addValue("Entry delay","action"); } else if (subGroup == 11) { json.addValue("Disarmed","action"); } return true; } return false; } else if (data["type"].str() == "changed") { json.addValue("ioboardnode","node"); json.addValue("changed","subtype"); json.addValue(data["pin"].toInt(),"pin"); json.addList("pgms"); mPgmCount = data["pins"].size(); mPgms = 0; for (int i = 0; i < mPgmCount; i++) { uint8_t tmp = 0; if (data["pins"][i].toBool()) tmp = 1; mPgms |= (tmp << i); json["pgms"].addValue(tmp); } return true; } return false; } void IOBoard::registerCallBacks(ThreadSafeRestEngine* pEngine) { RESTCallBack *p; p = new RESTCallBack(this,&IOBoard::status_callback,"Get PGM status"); pEngine->addCallBack("/dwn/"+mInfo.id+"/status","GET",p); mRestCallbacks.push_back(p); p = new RESTCallBack(this,&IOBoard::setoutput_callback,"set output"); pEngine->addCallBack("/dwn/"+mInfo.id+"/set","GET",p); p->addParam("out","0-4",false); p->addParam("level","0 or 1",false); mRestCallbacks.push_back(p); } void IOBoard::status_callback(RESTContext* context) { RESTParameters* params = context->params; Dumais::JSON::JSON& json = context->returnData; json.addValue("ok","status"); json.addList("pgms"); for (int i = 0; i < mPgmCount; i++) json["pgms"].addValue(((mPgms>>i)&1)); } void IOBoard::setoutput_callback(RESTContext* context) { RESTParameters* params = context->params; Dumais::JSON::JSON& json = context->returnData; std::string out = params->getParam("out"); std::string level = params->getParam("level"); Dumais::JSON::JSON j; j.addValue("set","event"); j.addValue(out,"out"); j.addValue(level,"level"); std::string st = j.stringify(false); this->mInfo.sendQueue->sendToNode(this->mInfo.ip,st.c_str(),st.size()); } <|endoftext|>
<commit_before>#include "GUI_Neutron.h" #include <DM/DM_RenderTable.h> #include <GEO/GEO_PrimPolySoup.h> #include <GR/GR_DisplayOption.h> #include <GR/GR_GeoRender.h> #include <GR/GR_OptionTable.h> #include <GR/GR_UserOption.h> #include <GR/GR_Utils.h> #include <GT/GT_GEOPrimitive.h> #include <RE/RE_Geometry.h> #include <RE/RE_Render.h> //#include <UT/UT_DSOVersion.h> #include "utility_Neutron.h" using namespace HDK_Sample; // install the hook. void newRenderHook(DM_RenderTable* table) { // the priority only matters if multiple hooks are assigned to the same // primitive type. If this is the case, the hook with the highest priority // (largest priority value) is processed first. const int priority = 0; // register the actual hook table->registerGEOHook(new GUI_NeutronHook(), GA_PrimitiveTypeId(GA_PRIMPOLYSOUP), priority, GUI_HOOK_FLAG_AUGMENT_PRIM); // register custom display options for the hook } // ------------------------------------------------------------------------- // The render hook itself. It is reponsible for creating new GUI_PolySoupBox // primitives when request by the viewport. GUI_NeutronHook::GUI_NeutronHook() : GUI_PrimitiveHook("GUI_NeutronHook") { } GUI_NeutronHook::~GUI_NeutronHook() { } GR_Primitive* GUI_NeutronHook::createPrimitive(const GT_PrimitiveHandle& gt_prim, const GEO_Primitive* geo_prim, const GR_RenderInfo* info, const char* cache_name, GR_PrimAcceptResult& processed) { //only create hook if attribute is set if (geo_prim->getTypeId().get() == GA_PRIMPOLYSOUP) { // We're going to process this prim and prevent any more lower-priority // hooks from hooking on it. Alternatively, GR_PROCESSED_NON_EXCLUSIVE // could be passed back, in which case any hooks of lower priority would // also be called. processed = GR_PROCESSED; // In this case, we aren't doing anything special, like checking attribs // to see if this is a flagged native primitive we want to hook on. return new GUI_Neutron(info, cache_name, geo_prim); } return NULL; } // ------------------------------------------------------------------------- // The decoration rendering code for the primitive. GUI_Neutron::GUI_Neutron(const GR_RenderInfo* info, const char* cache_name, const GEO_Primitive* prim) : GR_Primitive(info, cache_name, GA_PrimCompat::TypeMask(0)) { myGeometry = NULL; } GUI_Neutron::~GUI_Neutron() { delete myGeometry; } GR_PrimAcceptResult GUI_Neutron::acceptPrimitive(GT_PrimitiveType t, int geo_type, const GT_PrimitiveHandle& ph, const GEO_Primitive* prim) { GU_Detail* parent = static_cast<GU_Detail*>(prim->getParent()); //see if we have a detail attrib on there GA_RWHandleS attrib(parent, GA_ATTRIB_DETAIL, "__fluid__"); GA_RWHandleI uniqueHandleID(parent, GA_ATTRIB_DETAIL, "uniqueHandleID"); if (geo_type == GA_PRIMPOLYSOUP && attrib.isValid()){ std::cout << "accepted" << std::endl; mySim& simObject = myFluid::simvec[uniqueHandleID.get(0)]; simObject.doSomething(); return GR_PROCESSED; } return GR_NOT_PROCESSED; } void GUI_Neutron::update(RE_Render* r, const GT_PrimitiveHandle& primh, const GR_UpdateParms& p) { if (p.reason & (GR_GEO_CHANGED | GR_GEO_TOPOLOGY_CHANGED | GR_INSTANCE_PARMS_CHANGED)) { } } void GUI_Neutron::renderDecoration(RE_Render* r, GR_Decoration decor, const GR_DecorationParms& p) { if (decor >= GR_USER_DECORATION) { } } void GUI_Neutron::render(RE_Render* r, GR_RenderMode render_mode, GR_RenderFlags flags, GR_DrawParms dp) { // The native Houdini primitive for polysoups will do the rendering. } int GUI_Neutron::renderPick(RE_Render* r, const GR_DisplayOption* opt, unsigned int pick_type, GR_PickStyle pick_style, bool has_pick_map) { // The native Houdini primitive for polysoups will do the rendering. return 0; }<commit_msg>quick test of getting viewport dimensions<commit_after>#include "GUI_Neutron.h" #include <DM/DM_RenderTable.h> #include <GEO/GEO_PrimPolySoup.h> #include <GR/GR_DisplayOption.h> #include <GR/GR_GeoRender.h> #include <GR/GR_OptionTable.h> #include <GR/GR_UserOption.h> #include <GR/GR_Utils.h> #include <GT/GT_GEOPrimitive.h> #include <RE/RE_Geometry.h> #include <RE/RE_Render.h> //#include <UT/UT_DSOVersion.h> #include "utility_Neutron.h" using namespace HDK_Sample; // install the hook. void newRenderHook(DM_RenderTable* table) { // the priority only matters if multiple hooks are assigned to the same // primitive type. If this is the case, the hook with the highest priority // (largest priority value) is processed first. const int priority = 0; // register the actual hook table->registerGEOHook(new GUI_NeutronHook(), GA_PrimitiveTypeId(GA_PRIMPOLYSOUP), priority, GUI_HOOK_FLAG_AUGMENT_PRIM); // register custom display options for the hook } // ------------------------------------------------------------------------- // The render hook itself. It is reponsible for creating new GUI_PolySoupBox // primitives when request by the viewport. GUI_NeutronHook::GUI_NeutronHook() : GUI_PrimitiveHook("GUI_NeutronHook") { } GUI_NeutronHook::~GUI_NeutronHook() { } GR_Primitive* GUI_NeutronHook::createPrimitive(const GT_PrimitiveHandle& gt_prim, const GEO_Primitive* geo_prim, const GR_RenderInfo* info, const char* cache_name, GR_PrimAcceptResult& processed) { //only create hook if attribute is set if (geo_prim->getTypeId().get() == GA_PRIMPOLYSOUP) { // We're going to process this prim and prevent any more lower-priority // hooks from hooking on it. Alternatively, GR_PROCESSED_NON_EXCLUSIVE // could be passed back, in which case any hooks of lower priority would // also be called. processed = GR_PROCESSED; // In this case, we aren't doing anything special, like checking attribs // to see if this is a flagged native primitive we want to hook on. return new GUI_Neutron(info, cache_name, geo_prim); } return NULL; } // ------------------------------------------------------------------------- // The decoration rendering code for the primitive. GUI_Neutron::GUI_Neutron(const GR_RenderInfo* info, const char* cache_name, const GEO_Primitive* prim) : GR_Primitive(info, cache_name, GA_PrimCompat::TypeMask(0)) { myGeometry = NULL; } GUI_Neutron::~GUI_Neutron() { delete myGeometry; } GR_PrimAcceptResult GUI_Neutron::acceptPrimitive(GT_PrimitiveType t, int geo_type, const GT_PrimitiveHandle& ph, const GEO_Primitive* prim) { GU_Detail* parent = static_cast<GU_Detail*>(prim->getParent()); //see if we have a detail attrib on there GA_RWHandleS attrib(parent, GA_ATTRIB_DETAIL, "__fluid__"); GA_RWHandleI uniqueHandleID(parent, GA_ATTRIB_DETAIL, "uniqueHandleID"); if (geo_type == GA_PRIMPOLYSOUP && attrib.isValid()){ std::cout << "accepted" << std::endl; mySim& simObject = myFluid::simvec[uniqueHandleID.get(0)]; simObject.doSomething(); return GR_PROCESSED; } return GR_NOT_PROCESSED; } void GUI_Neutron::update(RE_Render* r, const GT_PrimitiveHandle& primh, const GR_UpdateParms& p) { if (p.reason & (GR_GEO_CHANGED | GR_GEO_TOPOLOGY_CHANGED | GR_INSTANCE_PARMS_CHANGED)) { } } void GUI_Neutron::renderDecoration(RE_Render* r, GR_Decoration decor, const GR_DecorationParms& p) { if (decor >= GR_USER_DECORATION) { } UT_DimRect saved_vp = r->getViewport2DI(); std::cout << saved_vp.width() << " " << saved_vp.height() << std::endl; } void GUI_Neutron::render(RE_Render* r, GR_RenderMode render_mode, GR_RenderFlags flags, GR_DrawParms dp) { // The native Houdini primitive for polysoups will do the rendering. } int GUI_Neutron::renderPick(RE_Render* r, const GR_DisplayOption* opt, unsigned int pick_type, GR_PickStyle pick_style, bool has_pick_map) { // The native Houdini primitive for polysoups will do the rendering. return 0; }<|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsatelliteinfosource_maemo_p.h" QTM_BEGIN_NAMESPACE QGeoSatelliteInfoSourceMaemo::QGeoSatelliteInfoSourceMaemo(QObject *parent) : QGeoSatelliteInfoSource(parent) { client_id_ = -1; } int QGeoSatelliteInfoSourceMaemo::init() { int status; dbusComm = new DBusComm(); status = dbusComm->init(); QObject::connect(dbusComm, SIGNAL(npeMessage(const QByteArray &)), this, SLOT(npeMessages(const QByteArray &))); return status; } // This method receives messages from DBus. void QGeoSatelliteInfoSourceMaemo::dbusMessages(const QByteArray &msg) { Q_UNUSED(msg) return; } void QGeoSatelliteInfoSourceMaemo::startUpdates() { #if 0 int len = npe.NewStartTrackingMsg(&msg,client_id_, NpeIf::MethodAll, NpeIf::OptionNone , 1); // cout << "ISI Message len " << len << "\n"; dbusComm->sendIsiMessage(msg,len); delete [] msg; #endif #if 0 // Test ! QList<QGeoSatelliteInfo> list; QGeoSatelliteInfo tmp; tmp.setPrnNumber(33); tmp.setSignalStrength(15); tmp.setProperty(QGeoSatelliteInfo::Azimuth, 45.0); tmp.setProperty(QGeoSatelliteInfo::Elevation, 25.5); list.append(tmp); list.append(tmp); list.append(tmp); emit satellitesInViewUpdated(list); emit satellitesInUseUpdated(list); #endif } void QGeoSatelliteInfoSourceMaemo::stopUpdates() { } void QGeoSatelliteInfoSourceMaemo::requestUpdate(int timeout) { int a; a = timeout +1; } #if 0 void satellitesInViewUpdated(const QList<QGeoSatelliteInfo> &satellites); void satellitesInUseUpdated(const QList<QGeoSatelliteInfo> &satellites); void requestTimeout(); #endif #include "moc_qgeosatelliteinfosource_maemo_p.cpp" QTM_END_NAMESPACE <commit_msg>Final part of initial Maemo location backend integration.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgeosatelliteinfosource_maemo_p.h" QTM_BEGIN_NAMESPACE QGeoSatelliteInfoSourceMaemo::QGeoSatelliteInfoSourceMaemo(QObject *parent) : QGeoSatelliteInfoSource(parent) { client_id_ = -1; } int QGeoSatelliteInfoSourceMaemo::init() { int status; dbusComm = new DBusComm(); status = dbusComm->init(); QObject::connect(dbusComm, SIGNAL(npeMessage(const QByteArray &)), this, SLOT(npeMessages(const QByteArray &))); return status; } // This method receives messages from DBus. void QGeoSatelliteInfoSourceMaemo::dbusMessages(const QByteArray &msg) { Q_UNUSED(msg) return; } void QGeoSatelliteInfoSourceMaemo::startUpdates() { #if 0 int len = npe.NewStartTrackingMsg(&msg,client_id_, NpeIf::MethodAll, NpeIf::OptionNone , 1); // cout << "ISI Message len " << len << "\n"; dbusComm->sendIsiMessage(msg,len); delete [] msg; #endif #if 0 // Test ! QList<QGeoSatelliteInfo> list; QGeoSatelliteInfo tmp; tmp.setPrnNumber(33); tmp.setSignalStrength(15); tmp.setProperty(QGeoSatelliteInfo::Azimuth, 45.0); tmp.setProperty(QGeoSatelliteInfo::Elevation, 25.5); list.append(tmp); list.append(tmp); list.append(tmp); emit satellitesInViewUpdated(list); emit satellitesInUseUpdated(list); #endif } void QGeoSatelliteInfoSourceMaemo::stopUpdates() { } void QGeoSatelliteInfoSourceMaemo::requestUpdate(int timeout) { int a; a = timeout +1; } #if 0 void satellitesInViewUpdated(const QList<QGeoSatelliteInfo> &satellites); void satellitesInUseUpdated(const QList<QGeoSatelliteInfo> &satellites); void requestTimeout(); #endif #include "moc_qgeosatelliteinfosource_maemo_p.cpp" QTM_END_NAMESPACE <|endoftext|>
<commit_before>/* * Copyright (c) 2010 Eduard Burtescu * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS 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, DIRECT, 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 <processor/types.h> #include <utilities/assert.h> #include <utilities/Cache.h> #include <ServiceManager.h> #include "ScsiDisk.h" #include "ScsiCommands.h" #include "ScsiController.h" #define delay(n) do{Semaphore semWAIT(0);semWAIT.acquire(1, 0, n*1000);}while(0) ScsiDisk::ScsiDisk() : m_Cache(), m_nAlignPoints(0), m_NumBlocks(0), m_BlockSize(0) { } ScsiDisk::~ScsiDisk() { } bool ScsiDisk::initialise(ScsiController *pController, size_t nUnit) { m_pController = pController; m_pParent = pController; m_nUnit = nUnit; // Turn on the unit - go ACTIVE ScsiCommand *pCommand = new ScsiCommands::StartStop(false, 1, true, true); bool success = sendCommand(pCommand, 0, 0); if(!success) return false; // Ensure the unit is ready before we attempt to do anything more if(!unitReady()) { ERROR("ScsiDisk: disk never became ready."); return false; } // Get the capacity of the device getCapacityInternal(&m_NumBlocks, &m_BlockSize); DEBUG_LOG("ScsiDisk: Capacity: " << Dec << m_NumBlocks << " blocks, each " << m_BlockSize << " bytes - " << (m_BlockSize * m_NumBlocks) << Hex << " bytes in total."); // Chat to the partition service and let it pick up that we're around now ServiceFeatures *pFeatures = ServiceManager::instance().enumerateOperations(String("partition")); Service *pService = ServiceManager::instance().getService(String("partition")); NOTICE("Asking if the partition provider supports touch"); if(pFeatures->provides(ServiceFeatures::touch)) { NOTICE("It does, attempting to inform the partitioner of our presence..."); if(pService) { if(pService->serve(ServiceFeatures::touch, static_cast<Disk*>(this), sizeof(static_cast<Disk*>(this)))) NOTICE("Successful."); else ERROR("Failed."); } else ERROR("ScsiDisk: Couldn't tell the partition service about the new disk presence"); } else ERROR("ScsiDisk: Partition service doesn't appear to support touch"); return true; } bool ScsiDisk::readSense(Sense *sense) { memset(sense, 0xFF, sizeof(Sense)); // Maximum size of sense data is 252 bytes ScsiCommand *pCommand = new ScsiCommands::ReadSense(0, sizeof(Sense)); uint8_t *response = new uint8_t[sizeof(Sense)]; bool success = sendCommand(pCommand, reinterpret_cast<uintptr_t>(response), sizeof(Sense)); if(!success) { WARNING("ScsiDisk: SENSE command failed"); delete [] response; return false; } /// \todo get the amount of data received from the SCSI device memcpy(sense, response, sizeof(Sense)); // Dump the sense information DEBUG_LOG(" Sense information:"); for(size_t i = 0; i < sizeof(Sense); i++) DEBUG_LOG(" [" << Dec << i << Hex << "] " << response[i]); delete [] response; return ((sense->ResponseCode & 0x70) == 0x70); } bool ScsiDisk::unitReady() { Sense s; memset(&s, 0, sizeof(Sense)); ScsiCommand *pCommand = new ScsiCommands::UnitReady(); readSense(&s); bool success = false; int retry = 5; do { success = sendCommand(pCommand, 0, 0, true); if(!success) delay(100); } while((!success) && (readSense(&s)) && --retry); delete pCommand; return (((s.ResponseCode & 0x70) == 0x70) && ((s.SenseKey == 0x06) || (s.SenseKey == 0x02) || (s.SenseKey == 0x00))); } bool ScsiDisk::getCapacityInternal(size_t *blockNumber, size_t *blockSize) { if(!unitReady()) { WARNING("ScsiDisk::getCapacityInternal - returning to defaults, unit not ready"); *blockNumber = 0; *blockSize = defaultBlockSize(); return false; } struct Capacity { uint32_t LBA; uint32_t BlockSize; } __attribute__((packed)) capacity; memset(&capacity, 0, sizeof(Capacity)); ScsiCommand *pCommand = new ScsiCommands::ReadCapacity10(); bool success = sendCommand(pCommand, reinterpret_cast<uintptr_t>(&capacity), sizeof(Capacity), false); delete pCommand; if(!success) { WARNING("ScsiDisk::getCapacityInternal - READ CAPACITY command failed"); return false; } *blockNumber = BIG_TO_HOST32(capacity.LBA); uint32_t blockSz = BIG_TO_HOST32(capacity.BlockSize); *blockSize = blockSz ? blockSz : defaultBlockSize(); return true; } bool ScsiDisk::sendCommand(ScsiCommand *pCommand, uintptr_t pRespBuffer, uint16_t nRespBytes, bool bWrite) { uintptr_t pCommandBuffer = 0; size_t nCommandSize = pCommand->serialise(pCommandBuffer); return m_pController->sendCommand(m_nUnit, pCommandBuffer, nCommandSize, pRespBuffer, nRespBytes, bWrite); } uintptr_t ScsiDisk::read(uint64_t location) { if (location % 512) FATAL("Read with location % 512."); if(!unitReady()) { ERROR("ScsiDisk::read - unit not ready"); return 0; } if((location / m_BlockSize) > m_NumBlocks) { ERROR("ScsiDisk::read - location too high"); return 0; } // Look through the align points. uint64_t alignPoint = 0; for (size_t i = 0; i < m_nAlignPoints; i++) if (m_AlignPoints[i] <= location && m_AlignPoints[i] > alignPoint) alignPoint = m_AlignPoints[i]; alignPoint %= 4096; // Determine which page the read is in uint64_t pageNumber = ((location - alignPoint) & ~0xFFFUL) + alignPoint; uint64_t pageOffset = (location - alignPoint) % 4096; uintptr_t buffer = m_Cache.lookup(pageNumber); if (buffer) return buffer + pageOffset; buffer = m_Cache.insert(pageNumber); bool bOk; ScsiCommand *pCommand; Sense s; DEBUG_LOG("SCSI: trying read(10)"); pCommand = new ScsiCommands::Read10(pageNumber / m_BlockSize, 4096 / m_BlockSize); bOk = sendCommand(pCommand, buffer, 4096); delete pCommand; if(bOk) return buffer + pageOffset; DEBUG_LOG("SCSI: trying read(12)"); pCommand = new ScsiCommands::Read12(pageNumber / m_BlockSize, 4096 / m_BlockSize); bOk = sendCommand(pCommand, buffer, 4096); delete pCommand; if(bOk) return buffer + pageOffset; DEBUG_LOG("SCSI: trying read(16)"); pCommand = new ScsiCommands::Read16(pageNumber / m_BlockSize, 4096 / m_BlockSize); bOk = sendCommand(pCommand, buffer, 4096); delete pCommand; if(bOk) ERROR("SCSI: no read function worked"); return buffer + pageOffset; } void ScsiDisk::write(uint64_t location) { WARNING("ScsiDisk::write: Not implemented."); } void ScsiDisk::align(uint64_t location) { assert(m_nAlignPoints < 8); m_AlignPoints[m_nAlignPoints++] = location; } <commit_msg>Fixed ScsiDisk::read to avoid using any SCSI commands until after a cache miss occurs.<commit_after>/* * Copyright (c) 2010 Eduard Burtescu * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS 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, DIRECT, 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 <processor/types.h> #include <utilities/assert.h> #include <utilities/Cache.h> #include <ServiceManager.h> #include "ScsiDisk.h" #include "ScsiCommands.h" #include "ScsiController.h" #define delay(n) do{Semaphore semWAIT(0);semWAIT.acquire(1, 0, n*1000);}while(0) ScsiDisk::ScsiDisk() : m_Cache(), m_nAlignPoints(0), m_NumBlocks(0), m_BlockSize(0) { } ScsiDisk::~ScsiDisk() { } bool ScsiDisk::initialise(ScsiController *pController, size_t nUnit) { m_pController = pController; m_pParent = pController; m_nUnit = nUnit; // Turn on the unit - go ACTIVE ScsiCommand *pCommand = new ScsiCommands::StartStop(false, 1, true, true); bool success = sendCommand(pCommand, 0, 0); if(!success) return false; // Ensure the unit is ready before we attempt to do anything more if(!unitReady()) { ERROR("ScsiDisk: disk never became ready."); return false; } // Get the capacity of the device getCapacityInternal(&m_NumBlocks, &m_BlockSize); DEBUG_LOG("ScsiDisk: Capacity: " << Dec << m_NumBlocks << " blocks, each " << m_BlockSize << " bytes - " << (m_BlockSize * m_NumBlocks) << Hex << " bytes in total."); // Chat to the partition service and let it pick up that we're around now ServiceFeatures *pFeatures = ServiceManager::instance().enumerateOperations(String("partition")); Service *pService = ServiceManager::instance().getService(String("partition")); NOTICE("Asking if the partition provider supports touch"); if(pFeatures->provides(ServiceFeatures::touch)) { NOTICE("It does, attempting to inform the partitioner of our presence..."); if(pService) { if(pService->serve(ServiceFeatures::touch, static_cast<Disk*>(this), sizeof(static_cast<Disk*>(this)))) NOTICE("Successful."); else ERROR("Failed."); } else ERROR("ScsiDisk: Couldn't tell the partition service about the new disk presence"); } else ERROR("ScsiDisk: Partition service doesn't appear to support touch"); return true; } bool ScsiDisk::readSense(Sense *sense) { memset(sense, 0xFF, sizeof(Sense)); // Maximum size of sense data is 252 bytes ScsiCommand *pCommand = new ScsiCommands::ReadSense(0, sizeof(Sense)); uint8_t *response = new uint8_t[sizeof(Sense)]; bool success = sendCommand(pCommand, reinterpret_cast<uintptr_t>(response), sizeof(Sense)); if(!success) { WARNING("ScsiDisk: SENSE command failed"); delete [] response; return false; } /// \todo get the amount of data received from the SCSI device memcpy(sense, response, sizeof(Sense)); // Dump the sense information DEBUG_LOG(" Sense information:"); for(size_t i = 0; i < sizeof(Sense); i++) DEBUG_LOG(" [" << Dec << i << Hex << "] " << response[i]); delete [] response; return ((sense->ResponseCode & 0x70) == 0x70); } bool ScsiDisk::unitReady() { Sense s; memset(&s, 0, sizeof(Sense)); ScsiCommand *pCommand = new ScsiCommands::UnitReady(); readSense(&s); bool success = false; int retry = 5; do { success = sendCommand(pCommand, 0, 0, true); if(!success) delay(100); } while((!success) && (readSense(&s)) && --retry); delete pCommand; return (((s.ResponseCode & 0x70) == 0x70) && ((s.SenseKey == 0x06) || (s.SenseKey == 0x02) || (s.SenseKey == 0x00))); } bool ScsiDisk::getCapacityInternal(size_t *blockNumber, size_t *blockSize) { if(!unitReady()) { WARNING("ScsiDisk::getCapacityInternal - returning to defaults, unit not ready"); *blockNumber = 0; *blockSize = defaultBlockSize(); return false; } struct Capacity { uint32_t LBA; uint32_t BlockSize; } __attribute__((packed)) capacity; memset(&capacity, 0, sizeof(Capacity)); ScsiCommand *pCommand = new ScsiCommands::ReadCapacity10(); bool success = sendCommand(pCommand, reinterpret_cast<uintptr_t>(&capacity), sizeof(Capacity), false); delete pCommand; if(!success) { WARNING("ScsiDisk::getCapacityInternal - READ CAPACITY command failed"); return false; } *blockNumber = BIG_TO_HOST32(capacity.LBA); uint32_t blockSz = BIG_TO_HOST32(capacity.BlockSize); *blockSize = blockSz ? blockSz : defaultBlockSize(); return true; } bool ScsiDisk::sendCommand(ScsiCommand *pCommand, uintptr_t pRespBuffer, uint16_t nRespBytes, bool bWrite) { uintptr_t pCommandBuffer = 0; size_t nCommandSize = pCommand->serialise(pCommandBuffer); return m_pController->sendCommand(m_nUnit, pCommandBuffer, nCommandSize, pRespBuffer, nRespBytes, bWrite); } uintptr_t ScsiDisk::read(uint64_t location) { if (location % 512) FATAL("Read with location % 512."); if((location / m_BlockSize) > m_NumBlocks) { ERROR("ScsiDisk::read - location too high"); return 0; } // Look through the align points. uint64_t alignPoint = 0; for (size_t i = 0; i < m_nAlignPoints; i++) if (m_AlignPoints[i] <= location && m_AlignPoints[i] > alignPoint) alignPoint = m_AlignPoints[i]; alignPoint %= 4096; // Determine which page the read is in uint64_t pageNumber = ((location - alignPoint) & ~0xFFFUL) + alignPoint; uint64_t pageOffset = (location - alignPoint) % 4096; uintptr_t buffer = m_Cache.lookup(pageNumber); if (buffer) return buffer + pageOffset; buffer = m_Cache.insert(pageNumber); bool bOk; ScsiCommand *pCommand; Sense s; // Wait for the unit to be ready before reading if(!unitReady()) { ERROR("ScsiDisk::read - unit not ready"); return 0; } DEBUG_LOG("SCSI: trying read(10)"); pCommand = new ScsiCommands::Read10(pageNumber / m_BlockSize, 4096 / m_BlockSize); bOk = sendCommand(pCommand, buffer, 4096); delete pCommand; if(bOk) return buffer + pageOffset; DEBUG_LOG("SCSI: trying read(12)"); pCommand = new ScsiCommands::Read12(pageNumber / m_BlockSize, 4096 / m_BlockSize); bOk = sendCommand(pCommand, buffer, 4096); delete pCommand; if(bOk) return buffer + pageOffset; DEBUG_LOG("SCSI: trying read(16)"); pCommand = new ScsiCommands::Read16(pageNumber / m_BlockSize, 4096 / m_BlockSize); bOk = sendCommand(pCommand, buffer, 4096); delete pCommand; if(bOk) ERROR("SCSI: no read function worked"); return buffer + pageOffset; } void ScsiDisk::write(uint64_t location) { WARNING("ScsiDisk::write: Not implemented."); } void ScsiDisk::align(uint64_t location) { assert(m_nAlignPoints < 8); m_AlignPoints[m_nAlignPoints++] = location; } <|endoftext|>
<commit_before>#include <cstring> #include <cassert> #include <boost/lexical_cast.hpp> #include <boost/regex.hpp> #include <string> #include <atomic> #include "HTTPProxy.h" #include "util.h" #include "Identity.h" #include "Streaming.h" #include "Destination.h" #include "ClientContext.h" #include "I2PEndian.h" #include "I2PTunnel.h" #include "Config.h" namespace i2p { namespace proxy { static const size_t http_buffer_size = 8192; class HTTPProxyHandler: public i2p::client::I2PServiceHandler, public std::enable_shared_from_this<HTTPProxyHandler> { private: enum state { GET_METHOD, GET_HOSTNAME, GET_HTTPV, GET_HTTPVNL, //TODO: fallback to finding HOst: header if needed DONE }; void EnterState(state nstate); bool HandleData(uint8_t *http_buff, std::size_t len); void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered); void Terminate(); void AsyncSockRead(); void HTTPRequestFailed(/*std::string message*/); void RedirectToJumpService(); void ExtractRequest(); bool IsI2PAddress(); bool ValidateHTTPRequest(); void HandleJumpServices(); bool CreateHTTPRequest(uint8_t *http_buff, std::size_t len); void SentHTTPFailed(const boost::system::error_code & ecode); void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream); uint8_t m_http_buff[http_buffer_size]; std::shared_ptr<boost::asio::ip::tcp::socket> m_sock; std::string m_request; //Data left to be sent std::string m_url; //URL std::string m_method; //Method std::string m_version; //HTTP version std::string m_address; //Address std::string m_path; //Path int m_port; //Port state m_state;//Parsing state public: HTTPProxyHandler(HTTPProxyServer * parent, std::shared_ptr<boost::asio::ip::tcp::socket> sock) : I2PServiceHandler(parent), m_sock(sock) { EnterState(GET_METHOD); } ~HTTPProxyHandler() { Terminate(); } void Handle () { AsyncSockRead(); } }; void HTTPProxyHandler::AsyncSockRead() { LogPrint(eLogDebug, "HTTPProxy: async sock read"); if(m_sock) { m_sock->async_receive(boost::asio::buffer(m_http_buff, http_buffer_size), std::bind(&HTTPProxyHandler::HandleSockRecv, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { LogPrint(eLogError, "HTTPProxy: no socket for read"); } } void HTTPProxyHandler::Terminate() { if (Kill()) return; if (m_sock) { LogPrint(eLogDebug, "HTTPProxy: close sock"); m_sock->close(); m_sock = nullptr; } Done(shared_from_this()); } /* All hope is lost beyond this point */ //TODO: handle this apropriately void HTTPProxyHandler::HTTPRequestFailed(/*HTTPProxyHandler::errTypes error*/) { static std::string response = "HTTP/1.0 500 Internal Server Error\r\nContent-type: text/html\r\nContent-length: 0\r\n"; boost::asio::async_write(*m_sock, boost::asio::buffer(response,response.size()), std::bind(&HTTPProxyHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1)); } void HTTPProxyHandler::RedirectToJumpService(/*HTTPProxyHandler::errTypes error*/) { std::stringstream response; std::string httpAddr; i2p::config::GetOption("http.address", httpAddr); uint16_t httpPort; i2p::config::GetOption("http.port", httpPort); response << "HTTP/1.1 302 Found\r\nLocation: http://" << httpAddr << ":" << httpPort << "/?jumpservices=&address=" << m_address << "\r\n\r\n"; boost::asio::async_write(*m_sock, boost::asio::buffer(response.str (),response.str ().length ()), std::bind(&HTTPProxyHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1)); } void HTTPProxyHandler::EnterState(HTTPProxyHandler::state nstate) { m_state = nstate; } void HTTPProxyHandler::ExtractRequest() { LogPrint(eLogDebug, "HTTPProxy: request: ", m_method, " ", m_url); std::string server=""; std::string port="80"; boost::regex rHTTP("http://(.*?)(:(\\d+))?(/.*)"); boost::smatch m; std::string path; if(boost::regex_search(m_url, m, rHTTP, boost::match_extra)) { server=m[1].str(); if (m[2].str() != "") port=m[3].str(); path=m[4].str(); } LogPrint(eLogDebug, "HTTPProxy: server: ", server, ", port: ", port, ", path: ", path); m_address = server; m_port = boost::lexical_cast<int>(port); m_path = path; } bool HTTPProxyHandler::ValidateHTTPRequest() { if ( m_version != "HTTP/1.0" && m_version != "HTTP/1.1" ) { LogPrint(eLogError, "HTTPProxy: unsupported version: ", m_version); HTTPRequestFailed(); //TODO: send right stuff return false; } return true; } void HTTPProxyHandler::HandleJumpServices() { static const char * helpermark1 = "?i2paddresshelper="; static const char * helpermark2 = "&i2paddresshelper="; size_t addressHelperPos1 = m_path.rfind (helpermark1); size_t addressHelperPos2 = m_path.rfind (helpermark2); size_t addressHelperPos; if (addressHelperPos1 == std::string::npos) { if (addressHelperPos2 == std::string::npos) return; //Not a jump service else addressHelperPos = addressHelperPos2; } else { if (addressHelperPos2 == std::string::npos) addressHelperPos = addressHelperPos1; else if ( addressHelperPos1 > addressHelperPos2 ) addressHelperPos = addressHelperPos1; else addressHelperPos = addressHelperPos2; } auto base64 = m_path.substr (addressHelperPos + strlen(helpermark1)); base64 = i2p::util::http::urlDecode(base64); //Some of the symbols may be urlencoded LogPrint (eLogInfo, "HTTPProxy: jump service for ", m_address, ", inserting to address book"); //TODO: this is very dangerous and broken. We should ask the user before doing anything see http://pastethis.i2p/raw/pn5fL4YNJL7OSWj3Sc6N/ //TODO: we could redirect the user again to avoid dirtiness in the browser i2p::client::context.GetAddressBook ().InsertAddress (m_address, base64); m_path.erase(addressHelperPos); } bool HTTPProxyHandler::IsI2PAddress() { auto pos = m_address.rfind (".i2p"); if (pos != std::string::npos && (pos+4) == m_address.length ()) { return true; } return false; } bool HTTPProxyHandler::CreateHTTPRequest(uint8_t *http_buff, std::size_t len) { ExtractRequest(); //TODO: parse earlier if (!ValidateHTTPRequest()) return false; HandleJumpServices(); i2p::data::IdentHash identHash; if (IsI2PAddress ()) { if (!i2p::client::context.GetAddressBook ().GetIdentHash (m_address, identHash)){ RedirectToJumpService(); return false; } } m_request = m_method; m_request.push_back(' '); m_request += m_path; m_request.push_back(' '); m_request += m_version; m_request.push_back('\r'); m_request.push_back('\n'); m_request.append("Connection: close\r\n"); // TODO: temporary shortcut. Must be implemented properly uint8_t * eol = nullptr; bool isEndOfHeader = false; while (!isEndOfHeader && len && (eol = (uint8_t *)memchr (http_buff, '\r', len))) { if (eol) { *eol = 0; eol++; if (strncmp ((const char *)http_buff, "Referer", 7) && strncmp ((const char *)http_buff, "Connection", 10)) // strip out referer and connection { if (!strncmp ((const char *)http_buff, "User-Agent", 10)) // replace UserAgent m_request.append("User-Agent: MYOB/6.66 (AN/ON)"); else m_request.append ((const char *)http_buff); m_request.append ("\r\n"); } isEndOfHeader = !http_buff[0]; auto l = eol - http_buff; http_buff = eol; len -= l; if (len > 0) // \r { http_buff++; len--; } } } m_request.append(reinterpret_cast<const char *>(http_buff),len); return true; } bool HTTPProxyHandler::HandleData(uint8_t *http_buff, std::size_t len) { while (len > 0) { //TODO: fallback to finding HOst: header if needed switch (m_state) { case GET_METHOD: switch (*http_buff) { case ' ': EnterState(GET_HOSTNAME); break; default: m_method.push_back(*http_buff); break; } break; case GET_HOSTNAME: switch (*http_buff) { case ' ': EnterState(GET_HTTPV); break; default: m_url.push_back(*http_buff); break; } break; case GET_HTTPV: switch (*http_buff) { case '\r': EnterState(GET_HTTPVNL); break; default: m_version.push_back(*http_buff); break; } break; case GET_HTTPVNL: switch (*http_buff) { case '\n': EnterState(DONE); break; default: LogPrint(eLogError, "HTTPProxy: rejected invalid request ending with: ", ((int)*http_buff)); HTTPRequestFailed(); //TODO: add correct code return false; } break; default: LogPrint(eLogError, "HTTPProxy: invalid state: ", m_state); HTTPRequestFailed(); //TODO: add correct code 500 return false; } http_buff++; len--; if (m_state == DONE) return CreateHTTPRequest(http_buff,len); } return true; } void HTTPProxyHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len) { LogPrint(eLogDebug, "HTTPProxy: sock recv: ", len, " bytes"); if(ecode) { LogPrint(eLogWarning, "HTTPProxy: sock recv got error: ", ecode); Terminate(); return; } if (HandleData(m_http_buff, len)) { if (m_state == DONE) { LogPrint(eLogDebug, "HTTPProxy: requested: ", m_url); GetOwner()->CreateStream (std::bind (&HTTPProxyHandler::HandleStreamRequestComplete, shared_from_this(), std::placeholders::_1), m_address, m_port); } else AsyncSockRead(); } } void HTTPProxyHandler::SentHTTPFailed(const boost::system::error_code & ecode) { if (ecode) LogPrint (eLogError, "HTTPProxy: Closing socket after sending failure because: ", ecode.message ()); Terminate(); } void HTTPProxyHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream) { if (stream) { if (Kill()) return; LogPrint (eLogInfo, "HTTPProxy: New I2PTunnel connection"); auto connection = std::make_shared<i2p::client::I2PTunnelConnection>(GetOwner(), m_sock, stream); GetOwner()->AddHandler (connection); connection->I2PConnect (reinterpret_cast<const uint8_t*>(m_request.data()), m_request.size()); Done(shared_from_this()); } else { LogPrint (eLogError, "HTTPProxy: error when creating the stream, check the previous warnings for more info"); HTTPRequestFailed(); // TODO: Send correct error message host unreachable } } HTTPProxyServer::HTTPProxyServer(const std::string& address, int port, std::shared_ptr<i2p::client::ClientDestination> localDestination): TCPIPAcceptor(address, port, localDestination ? localDestination : i2p::client::context.GetSharedLocalDestination ()) { } std::shared_ptr<i2p::client::I2PServiceHandler> HTTPProxyServer::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket) { return std::make_shared<HTTPProxyHandler> (this, socket); } } } <commit_msg>fix jumpservices<commit_after>#include <cstring> #include <cassert> #include <boost/lexical_cast.hpp> #include <boost/regex.hpp> #include <string> #include <atomic> #include "HTTPProxy.h" #include "util.h" #include "Identity.h" #include "Streaming.h" #include "Destination.h" #include "ClientContext.h" #include "I2PEndian.h" #include "I2PTunnel.h" #include "Config.h" namespace i2p { namespace proxy { static const size_t http_buffer_size = 8192; class HTTPProxyHandler: public i2p::client::I2PServiceHandler, public std::enable_shared_from_this<HTTPProxyHandler> { private: enum state { GET_METHOD, GET_HOSTNAME, GET_HTTPV, GET_HTTPVNL, //TODO: fallback to finding HOst: header if needed DONE }; void EnterState(state nstate); bool HandleData(uint8_t *http_buff, std::size_t len); void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered); void Terminate(); void AsyncSockRead(); void HTTPRequestFailed(/*std::string message*/); void RedirectToJumpService(); void ExtractRequest(); bool IsI2PAddress(); bool ValidateHTTPRequest(); void HandleJumpServices(); bool CreateHTTPRequest(uint8_t *http_buff, std::size_t len); void SentHTTPFailed(const boost::system::error_code & ecode); void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream); uint8_t m_http_buff[http_buffer_size]; std::shared_ptr<boost::asio::ip::tcp::socket> m_sock; std::string m_request; //Data left to be sent std::string m_url; //URL std::string m_method; //Method std::string m_version; //HTTP version std::string m_address; //Address std::string m_path; //Path int m_port; //Port state m_state;//Parsing state public: HTTPProxyHandler(HTTPProxyServer * parent, std::shared_ptr<boost::asio::ip::tcp::socket> sock) : I2PServiceHandler(parent), m_sock(sock) { EnterState(GET_METHOD); } ~HTTPProxyHandler() { Terminate(); } void Handle () { AsyncSockRead(); } }; void HTTPProxyHandler::AsyncSockRead() { LogPrint(eLogDebug, "HTTPProxy: async sock read"); if(m_sock) { m_sock->async_receive(boost::asio::buffer(m_http_buff, http_buffer_size), std::bind(&HTTPProxyHandler::HandleSockRecv, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { LogPrint(eLogError, "HTTPProxy: no socket for read"); } } void HTTPProxyHandler::Terminate() { if (Kill()) return; if (m_sock) { LogPrint(eLogDebug, "HTTPProxy: close sock"); m_sock->close(); m_sock = nullptr; } Done(shared_from_this()); } /* All hope is lost beyond this point */ //TODO: handle this apropriately void HTTPProxyHandler::HTTPRequestFailed(/*HTTPProxyHandler::errTypes error*/) { static std::string response = "HTTP/1.0 500 Internal Server Error\r\nContent-type: text/html\r\nContent-length: 0\r\n"; boost::asio::async_write(*m_sock, boost::asio::buffer(response,response.size()), std::bind(&HTTPProxyHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1)); } void HTTPProxyHandler::RedirectToJumpService(/*HTTPProxyHandler::errTypes error*/) { std::stringstream response; std::string httpAddr; i2p::config::GetOption("http.address", httpAddr); uint16_t httpPort; i2p::config::GetOption("http.port", httpPort); response << "HTTP/1.1 302 Found\r\nLocation: http://" << httpAddr << ":" << httpPort << "/?page=jumpservices&address=" << m_address << "\r\n\r\n"; boost::asio::async_write(*m_sock, boost::asio::buffer(response.str (),response.str ().length ()), std::bind(&HTTPProxyHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1)); } void HTTPProxyHandler::EnterState(HTTPProxyHandler::state nstate) { m_state = nstate; } void HTTPProxyHandler::ExtractRequest() { LogPrint(eLogDebug, "HTTPProxy: request: ", m_method, " ", m_url); std::string server=""; std::string port="80"; boost::regex rHTTP("http://(.*?)(:(\\d+))?(/.*)"); boost::smatch m; std::string path; if(boost::regex_search(m_url, m, rHTTP, boost::match_extra)) { server=m[1].str(); if (m[2].str() != "") port=m[3].str(); path=m[4].str(); } LogPrint(eLogDebug, "HTTPProxy: server: ", server, ", port: ", port, ", path: ", path); m_address = server; m_port = boost::lexical_cast<int>(port); m_path = path; } bool HTTPProxyHandler::ValidateHTTPRequest() { if ( m_version != "HTTP/1.0" && m_version != "HTTP/1.1" ) { LogPrint(eLogError, "HTTPProxy: unsupported version: ", m_version); HTTPRequestFailed(); //TODO: send right stuff return false; } return true; } void HTTPProxyHandler::HandleJumpServices() { static const char * helpermark1 = "?i2paddresshelper="; static const char * helpermark2 = "&i2paddresshelper="; size_t addressHelperPos1 = m_path.rfind (helpermark1); size_t addressHelperPos2 = m_path.rfind (helpermark2); size_t addressHelperPos; if (addressHelperPos1 == std::string::npos) { if (addressHelperPos2 == std::string::npos) return; //Not a jump service else addressHelperPos = addressHelperPos2; } else { if (addressHelperPos2 == std::string::npos) addressHelperPos = addressHelperPos1; else if ( addressHelperPos1 > addressHelperPos2 ) addressHelperPos = addressHelperPos1; else addressHelperPos = addressHelperPos2; } auto base64 = m_path.substr (addressHelperPos + strlen(helpermark1)); base64 = i2p::util::http::urlDecode(base64); //Some of the symbols may be urlencoded LogPrint (eLogInfo, "HTTPProxy: jump service for ", m_address, ", inserting to address book"); //TODO: this is very dangerous and broken. We should ask the user before doing anything see http://pastethis.i2p/raw/pn5fL4YNJL7OSWj3Sc6N/ //TODO: we could redirect the user again to avoid dirtiness in the browser i2p::client::context.GetAddressBook ().InsertAddress (m_address, base64); m_path.erase(addressHelperPos); } bool HTTPProxyHandler::IsI2PAddress() { auto pos = m_address.rfind (".i2p"); if (pos != std::string::npos && (pos+4) == m_address.length ()) { return true; } return false; } bool HTTPProxyHandler::CreateHTTPRequest(uint8_t *http_buff, std::size_t len) { ExtractRequest(); //TODO: parse earlier if (!ValidateHTTPRequest()) return false; HandleJumpServices(); i2p::data::IdentHash identHash; if (IsI2PAddress ()) { if (!i2p::client::context.GetAddressBook ().GetIdentHash (m_address, identHash)){ RedirectToJumpService(); return false; } } m_request = m_method; m_request.push_back(' '); m_request += m_path; m_request.push_back(' '); m_request += m_version; m_request.push_back('\r'); m_request.push_back('\n'); m_request.append("Connection: close\r\n"); // TODO: temporary shortcut. Must be implemented properly uint8_t * eol = nullptr; bool isEndOfHeader = false; while (!isEndOfHeader && len && (eol = (uint8_t *)memchr (http_buff, '\r', len))) { if (eol) { *eol = 0; eol++; if (strncmp ((const char *)http_buff, "Referer", 7) && strncmp ((const char *)http_buff, "Connection", 10)) // strip out referer and connection { if (!strncmp ((const char *)http_buff, "User-Agent", 10)) // replace UserAgent m_request.append("User-Agent: MYOB/6.66 (AN/ON)"); else m_request.append ((const char *)http_buff); m_request.append ("\r\n"); } isEndOfHeader = !http_buff[0]; auto l = eol - http_buff; http_buff = eol; len -= l; if (len > 0) // \r { http_buff++; len--; } } } m_request.append(reinterpret_cast<const char *>(http_buff),len); return true; } bool HTTPProxyHandler::HandleData(uint8_t *http_buff, std::size_t len) { while (len > 0) { //TODO: fallback to finding HOst: header if needed switch (m_state) { case GET_METHOD: switch (*http_buff) { case ' ': EnterState(GET_HOSTNAME); break; default: m_method.push_back(*http_buff); break; } break; case GET_HOSTNAME: switch (*http_buff) { case ' ': EnterState(GET_HTTPV); break; default: m_url.push_back(*http_buff); break; } break; case GET_HTTPV: switch (*http_buff) { case '\r': EnterState(GET_HTTPVNL); break; default: m_version.push_back(*http_buff); break; } break; case GET_HTTPVNL: switch (*http_buff) { case '\n': EnterState(DONE); break; default: LogPrint(eLogError, "HTTPProxy: rejected invalid request ending with: ", ((int)*http_buff)); HTTPRequestFailed(); //TODO: add correct code return false; } break; default: LogPrint(eLogError, "HTTPProxy: invalid state: ", m_state); HTTPRequestFailed(); //TODO: add correct code 500 return false; } http_buff++; len--; if (m_state == DONE) return CreateHTTPRequest(http_buff,len); } return true; } void HTTPProxyHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len) { LogPrint(eLogDebug, "HTTPProxy: sock recv: ", len, " bytes"); if(ecode) { LogPrint(eLogWarning, "HTTPProxy: sock recv got error: ", ecode); Terminate(); return; } if (HandleData(m_http_buff, len)) { if (m_state == DONE) { LogPrint(eLogDebug, "HTTPProxy: requested: ", m_url); GetOwner()->CreateStream (std::bind (&HTTPProxyHandler::HandleStreamRequestComplete, shared_from_this(), std::placeholders::_1), m_address, m_port); } else AsyncSockRead(); } } void HTTPProxyHandler::SentHTTPFailed(const boost::system::error_code & ecode) { if (ecode) LogPrint (eLogError, "HTTPProxy: Closing socket after sending failure because: ", ecode.message ()); Terminate(); } void HTTPProxyHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream) { if (stream) { if (Kill()) return; LogPrint (eLogInfo, "HTTPProxy: New I2PTunnel connection"); auto connection = std::make_shared<i2p::client::I2PTunnelConnection>(GetOwner(), m_sock, stream); GetOwner()->AddHandler (connection); connection->I2PConnect (reinterpret_cast<const uint8_t*>(m_request.data()), m_request.size()); Done(shared_from_this()); } else { LogPrint (eLogError, "HTTPProxy: error when creating the stream, check the previous warnings for more info"); HTTPRequestFailed(); // TODO: Send correct error message host unreachable } } HTTPProxyServer::HTTPProxyServer(const std::string& address, int port, std::shared_ptr<i2p::client::ClientDestination> localDestination): TCPIPAcceptor(address, port, localDestination ? localDestination : i2p::client::context.GetSharedLocalDestination ()) { } std::shared_ptr<i2p::client::I2PServiceHandler> HTTPProxyServer::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket) { return std::make_shared<HTTPProxyHandler> (this, socket); } } } <|endoftext|>
<commit_before>#include "StorageLogSegment.h" #include "System/FileSystem.h" #include "System/IO/IOProcessor.h" #include "System/Stopwatch.h" #include "StorageEnvironment.h" #include "StorageFileDeleter.h" StorageLogSegment::StorageLogSegment() { prev = next = this; trackID = 0; logSegmentID = 0; fd = INVALID_FD; logCommandID = 1; commitedLogCommandID = 0; syncGranularity = 0; offset = 0; lastSyncOffset = 0; prevContextID = 0; prevShardID = 0; writeShardID = true; asyncCommit = false; isCommitting = false; commitStatus = false; } #define Log_DebugLong(sw, ...) \ if (sw.Elapsed() > 1000) \ do { \ Log_Debug(__VA_ARGS__); \ sw.Reset(); \ } while (0) void StorageLogSegment::Open(Buffer& logPath, uint64_t trackID_, uint64_t logSegmentID_, uint64_t syncGranularity_) { unsigned length; Stopwatch sw; char humanBuf[5]; trackID = trackID_; logSegmentID = logSegmentID_; syncGranularity = syncGranularity_; offset = 0; lastSyncOffset = 0; filename.Write(logPath); filename.Appendf("log.%020U.%020U", trackID, logSegmentID); filename.NullTerminate(); sw.Start(); fd = FS_Open(filename.GetBuffer(), FS_CREATE | FS_WRITEONLY | FS_APPEND); sw.Stop(); if (fd == INVALID_FD) { Log_Message("Unable to open log segment file %U.", logSegmentID); Log_Message("Free disk space: %s", HumanBytes(FS_FreeDiskSpace(filename.GetBuffer()), humanBuf)); Log_Message("This should not happen."); Log_Message("Possible causes: not enough disk space, software bug..."); STOP_FAIL(1); } Log_DebugLong(sw, "log segment Open() took %U msec", (uint64_t) sw.Elapsed()); sw.Start(); writeBuffer.AppendLittle32(STORAGE_LOGSEGMENT_VERSION); writeBuffer.AppendLittle64(logSegmentID); length = writeBuffer.GetLength(); if (FS_FileWrite(fd, writeBuffer.GetBuffer(), length) != (ssize_t) length) { Log_Message("Unable to open log segment file %U.", logSegmentID); Log_Message("Free disk space: %s", HumanBytes(FS_FreeDiskSpace(filename.GetBuffer()), humanBuf)); Log_Message("This should not happen."); Log_Message("Possible causes: not enough disk space, software bug..."); STOP_FAIL(1); } offset += length; sw.Stop(); Log_DebugLong(sw, "log segment Open() took %U msec, length = %u", (uint64_t) sw.Elapsed(), length); sw.Start(); StorageEnvironment::Sync(fd); sw.Stop(); Log_DebugLong(sw, "log segment Open() took %U msec", (uint64_t) sw.Elapsed()); NewRound(); Log_Debug("Opening log segment %U", logSegmentID); } void StorageLogSegment::Close() { FS_FileClose(fd); fd = INVALID_FD; writeBuffer.Reset(); } void StorageLogSegment::DeleteFile() { StorageFileDeleter::Delete(filename.GetBuffer()); } uint64_t StorageLogSegment::GetTrackID() { return trackID; } uint64_t StorageLogSegment::GetLogSegmentID() { return logSegmentID; } uint32_t StorageLogSegment::GetLogCommandID() { return logCommandID; } void StorageLogSegment::SetOnCommit(Callable* onCommit_) { onCommit = onCommit_; asyncCommit = true; } int32_t StorageLogSegment::AppendSet(uint16_t contextID, uint64_t shardID, ReadBuffer& key, ReadBuffer& value) { ASSERT(fd != INVALID_FD); ASSERT(key.GetLength() > 0); prevLength = writeBuffer.GetLength(); writeBuffer.Appendf("%c", STORAGE_LOGSEGMENT_COMMAND_SET); if (!writeShardID && contextID == prevContextID && shardID == prevShardID) { writeBuffer.Appendf("%b", true); // use previous shardID } else { writeBuffer.Appendf("%b", false); writeBuffer.AppendLittle16(contextID); writeBuffer.AppendLittle64(shardID); } writeBuffer.AppendLittle16(key.GetLength()); writeBuffer.Append(key); writeBuffer.AppendLittle32(value.GetLength()); writeBuffer.Append(value); writeShardID = false; prevContextID = contextID; prevShardID = shardID; return logCommandID++; } int32_t StorageLogSegment::AppendDelete(uint16_t contextID, uint64_t shardID, ReadBuffer& key) { ASSERT(fd != INVALID_FD); ASSERT(key.GetLength() > 0); prevLength = writeBuffer.GetLength(); writeBuffer.Appendf("%c", STORAGE_LOGSEGMENT_COMMAND_DELETE); if (!writeShardID && contextID == prevContextID && shardID == prevShardID) { writeBuffer.Appendf("%b", true); // use previous shardID } else { writeBuffer.Appendf("%b", false); writeBuffer.AppendLittle16(contextID); writeBuffer.AppendLittle64(shardID); } writeBuffer.AppendLittle16(key.GetLength()); writeBuffer.Append(key); writeShardID = false; prevContextID = contextID; prevShardID = shardID; return logCommandID++; } void StorageLogSegment::Undo() { writeBuffer.SetLength(prevLength); logCommandID--; writeShardID = true; } void StorageLogSegment::Commit() { uint32_t checksum; uint64_t length; uint64_t writeSize; uint64_t writeOffset; ssize_t ret; Stopwatch sw; char humanBuf[5]; char humanBuf2[5]; commitStatus = true; ASSERT(fd != INVALID_FD); length = writeBuffer.GetLength(); ASSERT(length >= STORAGE_LOGSEGMENT_BLOCK_HEAD_SIZE); if (length == STORAGE_LOGSEGMENT_BLOCK_HEAD_SIZE) return; // empty round checksum = 0; writeBuffer.SetLength(0); writeBuffer.AppendLittle64(length); writeBuffer.AppendLittle64(length - STORAGE_LOGSEGMENT_BLOCK_HEAD_SIZE); writeBuffer.AppendLittle32(checksum); writeBuffer.SetLength(length); sw.Start(); for (writeOffset = 0; writeOffset < length; writeOffset += writeSize) { writeSize = MIN(STORAGE_WRITE_GRANULARITY, length - writeOffset); ret = FS_FileWrite(fd, writeBuffer.GetBuffer() + writeOffset, writeSize); if (ret < 0 || (uint64_t) ret != writeSize) { Log_Message("Unable to write log segment file %U to disk.", logSegmentID); Log_Message("Free disk space: %s", HumanBytes(FS_FreeDiskSpace(filename.GetBuffer()), humanBuf)); Log_Message("This should not happen."); Log_Message("Possible causes: not enough disk space, software bug..."); STOP_FAIL(1); } if (syncGranularity > 0 && writeOffset - lastSyncOffset > syncGranularity) { StorageEnvironment::Sync(fd); lastSyncOffset = writeOffset; } } offset += length; StorageEnvironment::Sync(fd); sw.Stop(); Log_Message("Committed track %U, elapsed: %U, size: %s, bps: %sB/s", trackID, (uint64_t) sw.Elapsed(), HumanBytes(length, humanBuf), HumanBytes(BYTE_PER_SEC(length, sw.Elapsed()), humanBuf2)); NewRound(); commitedLogCommandID = logCommandID - 1; if (asyncCommit) IOProcessor::Complete(onCommit); } bool StorageLogSegment::HasUncommitted() { return (writeBuffer.GetLength() > STORAGE_LOGSEGMENT_BLOCK_HEAD_SIZE); } uint32_t StorageLogSegment::GetCommitedLogCommandID() { return commitedLogCommandID; } uint64_t StorageLogSegment::GetOffset() { return offset; } uint64_t StorageLogSegment::GetWriteBufferSize() { return writeBuffer.GetSize(); } void StorageLogSegment::SetOffset(uint64_t offset_) { ASSERT(fd == INVALID_FD); offset = offset_; } void StorageLogSegment::NewRound() { // reserve: // 4 bytes for size // 4 bytes for uncompressedLength // 4 bytes for CRC writeBuffer.Allocate(STORAGE_LOGSEGMENT_BLOCK_HEAD_SIZE); writeBuffer.Zero(); writeBuffer.SetLength(STORAGE_LOGSEGMENT_BLOCK_HEAD_SIZE); prevLength = writeBuffer.GetLength(); } <commit_msg>Changed loglevel.<commit_after>#include "StorageLogSegment.h" #include "System/FileSystem.h" #include "System/IO/IOProcessor.h" #include "System/Stopwatch.h" #include "StorageEnvironment.h" #include "StorageFileDeleter.h" StorageLogSegment::StorageLogSegment() { prev = next = this; trackID = 0; logSegmentID = 0; fd = INVALID_FD; logCommandID = 1; commitedLogCommandID = 0; syncGranularity = 0; offset = 0; lastSyncOffset = 0; prevContextID = 0; prevShardID = 0; writeShardID = true; asyncCommit = false; isCommitting = false; commitStatus = false; } #define Log_DebugLong(sw, ...) \ if (sw.Elapsed() > 1000) \ do { \ Log_Debug(__VA_ARGS__); \ sw.Reset(); \ } while (0) void StorageLogSegment::Open(Buffer& logPath, uint64_t trackID_, uint64_t logSegmentID_, uint64_t syncGranularity_) { unsigned length; Stopwatch sw; char humanBuf[5]; trackID = trackID_; logSegmentID = logSegmentID_; syncGranularity = syncGranularity_; offset = 0; lastSyncOffset = 0; filename.Write(logPath); filename.Appendf("log.%020U.%020U", trackID, logSegmentID); filename.NullTerminate(); sw.Start(); fd = FS_Open(filename.GetBuffer(), FS_CREATE | FS_WRITEONLY | FS_APPEND); sw.Stop(); if (fd == INVALID_FD) { Log_Message("Unable to open log segment file %U.", logSegmentID); Log_Message("Free disk space: %s", HumanBytes(FS_FreeDiskSpace(filename.GetBuffer()), humanBuf)); Log_Message("This should not happen."); Log_Message("Possible causes: not enough disk space, software bug..."); STOP_FAIL(1); } Log_DebugLong(sw, "log segment Open() took %U msec", (uint64_t) sw.Elapsed()); sw.Start(); writeBuffer.AppendLittle32(STORAGE_LOGSEGMENT_VERSION); writeBuffer.AppendLittle64(logSegmentID); length = writeBuffer.GetLength(); if (FS_FileWrite(fd, writeBuffer.GetBuffer(), length) != (ssize_t) length) { Log_Message("Unable to open log segment file %U.", logSegmentID); Log_Message("Free disk space: %s", HumanBytes(FS_FreeDiskSpace(filename.GetBuffer()), humanBuf)); Log_Message("This should not happen."); Log_Message("Possible causes: not enough disk space, software bug..."); STOP_FAIL(1); } offset += length; sw.Stop(); Log_DebugLong(sw, "log segment Open() took %U msec, length = %u", (uint64_t) sw.Elapsed(), length); sw.Start(); StorageEnvironment::Sync(fd); sw.Stop(); Log_DebugLong(sw, "log segment Open() took %U msec", (uint64_t) sw.Elapsed()); NewRound(); Log_Debug("Opening log segment %U", logSegmentID); } void StorageLogSegment::Close() { FS_FileClose(fd); fd = INVALID_FD; writeBuffer.Reset(); } void StorageLogSegment::DeleteFile() { StorageFileDeleter::Delete(filename.GetBuffer()); } uint64_t StorageLogSegment::GetTrackID() { return trackID; } uint64_t StorageLogSegment::GetLogSegmentID() { return logSegmentID; } uint32_t StorageLogSegment::GetLogCommandID() { return logCommandID; } void StorageLogSegment::SetOnCommit(Callable* onCommit_) { onCommit = onCommit_; asyncCommit = true; } int32_t StorageLogSegment::AppendSet(uint16_t contextID, uint64_t shardID, ReadBuffer& key, ReadBuffer& value) { ASSERT(fd != INVALID_FD); ASSERT(key.GetLength() > 0); prevLength = writeBuffer.GetLength(); writeBuffer.Appendf("%c", STORAGE_LOGSEGMENT_COMMAND_SET); if (!writeShardID && contextID == prevContextID && shardID == prevShardID) { writeBuffer.Appendf("%b", true); // use previous shardID } else { writeBuffer.Appendf("%b", false); writeBuffer.AppendLittle16(contextID); writeBuffer.AppendLittle64(shardID); } writeBuffer.AppendLittle16(key.GetLength()); writeBuffer.Append(key); writeBuffer.AppendLittle32(value.GetLength()); writeBuffer.Append(value); writeShardID = false; prevContextID = contextID; prevShardID = shardID; return logCommandID++; } int32_t StorageLogSegment::AppendDelete(uint16_t contextID, uint64_t shardID, ReadBuffer& key) { ASSERT(fd != INVALID_FD); ASSERT(key.GetLength() > 0); prevLength = writeBuffer.GetLength(); writeBuffer.Appendf("%c", STORAGE_LOGSEGMENT_COMMAND_DELETE); if (!writeShardID && contextID == prevContextID && shardID == prevShardID) { writeBuffer.Appendf("%b", true); // use previous shardID } else { writeBuffer.Appendf("%b", false); writeBuffer.AppendLittle16(contextID); writeBuffer.AppendLittle64(shardID); } writeBuffer.AppendLittle16(key.GetLength()); writeBuffer.Append(key); writeShardID = false; prevContextID = contextID; prevShardID = shardID; return logCommandID++; } void StorageLogSegment::Undo() { writeBuffer.SetLength(prevLength); logCommandID--; writeShardID = true; } void StorageLogSegment::Commit() { uint32_t checksum; uint64_t length; uint64_t writeSize; uint64_t writeOffset; ssize_t ret; Stopwatch sw; char humanBuf[5]; char humanBuf2[5]; commitStatus = true; ASSERT(fd != INVALID_FD); length = writeBuffer.GetLength(); ASSERT(length >= STORAGE_LOGSEGMENT_BLOCK_HEAD_SIZE); if (length == STORAGE_LOGSEGMENT_BLOCK_HEAD_SIZE) return; // empty round checksum = 0; writeBuffer.SetLength(0); writeBuffer.AppendLittle64(length); writeBuffer.AppendLittle64(length - STORAGE_LOGSEGMENT_BLOCK_HEAD_SIZE); writeBuffer.AppendLittle32(checksum); writeBuffer.SetLength(length); sw.Start(); for (writeOffset = 0; writeOffset < length; writeOffset += writeSize) { writeSize = MIN(STORAGE_WRITE_GRANULARITY, length - writeOffset); ret = FS_FileWrite(fd, writeBuffer.GetBuffer() + writeOffset, writeSize); if (ret < 0 || (uint64_t) ret != writeSize) { Log_Message("Unable to write log segment file %U to disk.", logSegmentID); Log_Message("Free disk space: %s", HumanBytes(FS_FreeDiskSpace(filename.GetBuffer()), humanBuf)); Log_Message("This should not happen."); Log_Message("Possible causes: not enough disk space, software bug..."); STOP_FAIL(1); } if (syncGranularity > 0 && writeOffset - lastSyncOffset > syncGranularity) { StorageEnvironment::Sync(fd); lastSyncOffset = writeOffset; } } offset += length; StorageEnvironment::Sync(fd); sw.Stop(); Log_Debug("Committed track %U, elapsed: %U, size: %s, bps: %sB/s", trackID, (uint64_t) sw.Elapsed(), HumanBytes(length, humanBuf), HumanBytes(BYTE_PER_SEC(length, sw.Elapsed()), humanBuf2)); NewRound(); commitedLogCommandID = logCommandID - 1; if (asyncCommit) IOProcessor::Complete(onCommit); } bool StorageLogSegment::HasUncommitted() { return (writeBuffer.GetLength() > STORAGE_LOGSEGMENT_BLOCK_HEAD_SIZE); } uint32_t StorageLogSegment::GetCommitedLogCommandID() { return commitedLogCommandID; } uint64_t StorageLogSegment::GetOffset() { return offset; } uint64_t StorageLogSegment::GetWriteBufferSize() { return writeBuffer.GetSize(); } void StorageLogSegment::SetOffset(uint64_t offset_) { ASSERT(fd == INVALID_FD); offset = offset_; } void StorageLogSegment::NewRound() { // reserve: // 4 bytes for size // 4 bytes for uncompressedLength // 4 bytes for CRC writeBuffer.Allocate(STORAGE_LOGSEGMENT_BLOCK_HEAD_SIZE); writeBuffer.Zero(); writeBuffer.SetLength(STORAGE_LOGSEGMENT_BLOCK_HEAD_SIZE); prevLength = writeBuffer.GetLength(); } <|endoftext|>
<commit_before>/// /// anax /// An open source C++ entity system. /// /// Copyright (C) 2013 Miguel Martin (miguel.martin7.5@hotmail.com) /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. /// #include <anax/detail/EntityIdPool.hpp> namespace anax { namespace detail { EntityIdPool::EntityIdPool(std::size_t poolSize) : m_defaultPoolSize(poolSize), m_entities(poolSize), m_nextId(0) { } Entity::Id EntityIdPool::create() { Entity::Id id; // if we need to add more entities to the pool if(!m_freeList.empty()) { id = m_freeList.back(); m_freeList.pop_back(); // Update the ID counter before issuing //id.counter = m_entities[id.index]; } else { id.index = m_nextId++; // an ID given out cannot have a counter of 0. // 0 is an "invalid" counter, thus we must update // the counter within the pool for the corresponding // entity m_entities[id.index] = id.counter = 1; } return id; } void EntityIdPool::remove(Entity::Id id) { ++m_entities[id.index]; // increment the counter in the cache m_freeList.emplace_back(id.index, m_entities[id.index]); // add the ID to the freeList } Entity::Id EntityIdPool::get(std::size_t index) const { assert(!(m_entities[index] == 0) && "Entity ID does not exist"); return Entity::Id{index, m_entities[index]}; } bool EntityIdPool::isValid(Entity::Id id) const { return id.counter == m_entities[id.index]; } void EntityIdPool::resize(std::size_t amount) { m_entities.resize(amount); } void EntityIdPool::clear() { m_entities.clear(); m_freeList.clear(); m_nextId = 0; m_entities.resize(m_defaultPoolSize); } } } <commit_msg>Fix #40<commit_after>/// /// anax /// An open source C++ entity system. /// /// Copyright (C) 2013 Miguel Martin (miguel.martin7.5@hotmail.com) /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. /// #include <anax/detail/EntityIdPool.hpp> namespace anax { namespace detail { EntityIdPool::EntityIdPool(std::size_t poolSize) : m_defaultPoolSize(poolSize), m_entities(poolSize), m_nextId(0) { } Entity::Id EntityIdPool::create() { Entity::Id id; // if we need to add more entities to the pool if(!m_freeList.empty()) { id = m_freeList.back(); m_freeList.pop_back(); // Update the ID counter before issuing //id.counter = m_entities[id.index]; } else { id.index = m_nextId++; // an ID given out cannot have a counter of 0. // 0 is an "invalid" counter, thus we must update // the counter within the pool for the corresponding // entity m_entities[id.index] = id.counter = 1; } return id; } void EntityIdPool::remove(Entity::Id id) { auto& counter = m_entities[id.index]; ++counter; // increment the counter in the cache m_freeList.emplace_back(static_cast<Entity::Id::int_type>(id.index), counter); // add the ID to the freeList } Entity::Id EntityIdPool::get(std::size_t index) const { assert(!(m_entities[index] == 0) && "Entity ID does not exist"); return Entity::Id{index, m_entities[index]}; } bool EntityIdPool::isValid(Entity::Id id) const { return id.counter == m_entities[id.index]; } void EntityIdPool::resize(std::size_t amount) { m_entities.resize(amount); } void EntityIdPool::clear() { m_entities.clear(); m_freeList.clear(); m_nextId = 0; m_entities.resize(m_defaultPoolSize); } } } <|endoftext|>
<commit_before>#include "InfoLayer.h" USING_NS_CC; USING_NS_CC_DEN; cocos2d::Scene * Info::createScene() { auto scene = Scene::create(); auto layer = Info::create(); scene->addChild(layer); return scene; } bool Info::init() { if (!Layer::init()) { return false; } auto rootNode = CSLoader::createNode("Csbs/Info.csb"); rootNode->setPosition(Vec2::ZERO); this->addChild(rootNode); auto mainMenuButton = dynamic_cast<ui::Button *>(rootNode->getChildByName("MainMenuButton")); mainMenuButton->addTouchEventListener([&](Ref* pSender, ui::Widget::TouchEventType type) { if (type == ui::Widget::TouchEventType::ENDED) { Director::getInstance()->popToRootScene(); if (UserDefault::getInstance()->getBoolForKey(SOUND_KEY)) { SimpleAudioEngine::getInstance()->playEffect(FILE_SOUND_1); } } }); return true; } void Info::onEnterTransitionDidFinish() { Layer::onEnterTransitionDidFinish(); if (UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) { SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); } } <commit_msg>Delete InfoLayer.cpp<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include <stdio.h> #include <dlfcn.h> #include <cxxabi.h> #include <hash_map> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <com/sun/star/uno/genfunc.hxx> #include "com/sun/star/uno/RuntimeException.hpp" #include <typelib/typedescription.hxx> #include <uno/any2.h> #include "share.hxx" #ifdef TEST #include "test/TestBridgeException.hpp" #endif using namespace ::std; using namespace ::osl; using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::__cxxabiv1; //================================================================================================== //YD static handle to this dll, to allow rtti symbol lookup static void* hmod; //================================================================================================== //YD required to run test programs, because exe cannot export symbols! #ifdef TEST using namespace ::test; void dymmy_TestBridgeException() throw( ::test::TestBridgeException) { throw TestBridgeException(); } #endif //================================================================================================== namespace CPPU_CURRENT_NAMESPACE { void dummy_can_throw_anything( char const * ) { } //================================================================================================== static OUString toUNOname( char const * p ) SAL_THROW( () ) { #if OSL_DEBUG_LEVEL > 1 char const * start = p; #endif // example: N3com3sun4star4lang24IllegalArgumentExceptionE OUStringBuffer buf( 64 ); OSL_ASSERT( 'N' == *p ); ++p; // skip N while ('E' != *p) { // read chars count long n = (*p++ - '0'); while ('0' <= *p && '9' >= *p) { n *= 10; n += (*p++ - '0'); } buf.appendAscii( p, n ); p += n; if ('E' != *p) buf.append( (sal_Unicode)'.' ); } #if OSL_DEBUG_LEVEL > 1 OUString ret( buf.makeStringAndClear() ); OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() ); return ret; #else return buf.makeStringAndClear(); #endif } //================================================================================================== class RTTI { typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map; Mutex m_mutex; t_rtti_map m_rttis; t_rtti_map m_generatedRttis; //void * m_hApp; public: RTTI() SAL_THROW( () ); ~RTTI() SAL_THROW( () ); type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () ); }; //__________________________________________________________________________________________________ RTTI::RTTI() SAL_THROW( () ) // : m_hApp( dlopen( 0, RTLD_LAZY ) ) { } //__________________________________________________________________________________________________ RTTI::~RTTI() SAL_THROW( () ) { // dlclose( m_hApp ); } //__________________________________________________________________________________________________ type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () ) { type_info * rtti; OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName; MutexGuard guard( m_mutex ); t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) ); if (iFind == m_rttis.end()) { // RTTI symbol OStringBuffer buf( 64 ); buf.append( RTL_CONSTASCII_STRINGPARAM("__ZTIN") ); sal_Int32 index = 0; do { OUString token( unoName.getToken( 0, '.', index ) ); buf.append( token.getLength() ); OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) ); buf.append( c_token ); } while (index >= 0); buf.append( 'E' ); OString symName( buf.makeStringAndClear() ); //rtti = (type_info *)dlsym( m_hApp, symName.getStr() ); if (hmod == NULL) hmod = dlopen( "gcc3_uno.dll", 0); if (hmod) rtti = (type_info *)dlsym( hmod, symName.getStr() ); if (rtti) { pair< t_rtti_map::iterator, bool > insertion( m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" ); } else { // try to lookup the symbol in the generated rtti map t_rtti_map::const_iterator iFind( m_generatedRttis.find( unoName ) ); if (iFind == m_generatedRttis.end()) { // we must generate it ! // symbol and rtti-name is nearly identical, // the symbol is prefixed with __ZTI char const * rttiName = symName.getStr() +5; #if OSL_DEBUG_LEVEL > 1 fprintf( stderr,"generated rtti for %s\n", rttiName ); #endif if (pTypeDescr->pBaseTypeDescription) { // ensure availability of base type_info * base_rtti = getRTTI( (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription ); rtti = new __si_class_type_info( strdup( rttiName ), (__class_type_info *)base_rtti ); } else { // this class has no base class rtti = new __class_type_info( strdup( rttiName ) ); } pair< t_rtti_map::iterator, bool > insertion( m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" ); } else // taking already generated rtti { rtti = iFind->second; } } } else { rtti = iFind->second; } return rtti; } //-------------------------------------------------------------------------------------------------- static void deleteException( void * pExc ) { __cxa_exception const * header = ((__cxa_exception const *)pExc - 1); typelib_TypeDescription * pTD = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pTD, unoName.pData ); OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" ); if (pTD) { ::uno_destructData( pExc, pTD, cpp_release ); ::typelib_typedescription_release( pTD ); } } //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { #if OSL_DEBUG_LEVEL > 1 OString cstr( OUStringToOString( *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> uno exception occured: %s\n", cstr.getStr() ); #endif void * pCppExc; type_info * rtti; { // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); OSL_ASSERT( pTypeDescr ); if (! pTypeDescr) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("cannot get typedescription for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } pCppExc = __cxa_allocate_exception( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); // avoiding locked counts static RTTI * s_rtti = 0; if (! s_rtti) { MutexGuard guard( Mutex::getGlobalMutex() ); if (! s_rtti) { #ifdef LEAK_STATIC_DATA s_rtti = new RTTI(); #else static RTTI rtti_data; s_rtti = &rtti_data; #endif } } rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr ); TYPELIB_DANGER_RELEASE( pTypeDescr ); OSL_ENSURE( rtti, "### no rtti for throwing exception!" ); if (! rtti) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("no rtti for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } } __cxa_throw( pCppExc, rtti, deleteException ); } //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno ) { if (! header) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("no exception header!") ), Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_ENSURE( 0, cstr.getStr() ); #endif return; } typelib_TypeDescription * pExcTypeDescr = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); #if OSL_DEBUG_LEVEL > 1 OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> c++ exception occured: %s\n", cstr_unoName.getStr() ); #endif typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData ); if (0 == pExcTypeDescr) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("exception type not found: ") ) + unoName, Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_ENSURE( 0, cstr.getStr() ); #endif } else { // construct uno exception any uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno ); typelib_typedescription_release( pExcTypeDescr ); } } } <commit_msg>cmcfixes74: #i109877 init rtti on os2<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include <stdio.h> #include <dlfcn.h> #include <cxxabi.h> #include <hash_map> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <com/sun/star/uno/genfunc.hxx> #include "com/sun/star/uno/RuntimeException.hpp" #include <typelib/typedescription.hxx> #include <uno/any2.h> #include "share.hxx" #ifdef TEST #include "test/TestBridgeException.hpp" #endif using namespace ::std; using namespace ::osl; using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::__cxxabiv1; //================================================================================================== //YD static handle to this dll, to allow rtti symbol lookup static void* hmod; //================================================================================================== //YD required to run test programs, because exe cannot export symbols! #ifdef TEST using namespace ::test; void dymmy_TestBridgeException() throw( ::test::TestBridgeException) { throw TestBridgeException(); } #endif //================================================================================================== namespace CPPU_CURRENT_NAMESPACE { void dummy_can_throw_anything( char const * ) { } //================================================================================================== static OUString toUNOname( char const * p ) SAL_THROW( () ) { #if OSL_DEBUG_LEVEL > 1 char const * start = p; #endif // example: N3com3sun4star4lang24IllegalArgumentExceptionE OUStringBuffer buf( 64 ); OSL_ASSERT( 'N' == *p ); ++p; // skip N while ('E' != *p) { // read chars count long n = (*p++ - '0'); while ('0' <= *p && '9' >= *p) { n *= 10; n += (*p++ - '0'); } buf.appendAscii( p, n ); p += n; if ('E' != *p) buf.append( (sal_Unicode)'.' ); } #if OSL_DEBUG_LEVEL > 1 OUString ret( buf.makeStringAndClear() ); OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() ); return ret; #else return buf.makeStringAndClear(); #endif } //================================================================================================== class RTTI { typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map; Mutex m_mutex; t_rtti_map m_rttis; t_rtti_map m_generatedRttis; //void * m_hApp; public: RTTI() SAL_THROW( () ); ~RTTI() SAL_THROW( () ); type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () ); }; //__________________________________________________________________________________________________ RTTI::RTTI() SAL_THROW( () ) // : m_hApp( dlopen( 0, RTLD_LAZY ) ) { } //__________________________________________________________________________________________________ RTTI::~RTTI() SAL_THROW( () ) { // dlclose( m_hApp ); } //__________________________________________________________________________________________________ type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () ) { type_info * rtti = NULL; OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName; MutexGuard guard( m_mutex ); t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) ); if (iFind == m_rttis.end()) { // RTTI symbol OStringBuffer buf( 64 ); buf.append( RTL_CONSTASCII_STRINGPARAM("__ZTIN") ); sal_Int32 index = 0; do { OUString token( unoName.getToken( 0, '.', index ) ); buf.append( token.getLength() ); OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) ); buf.append( c_token ); } while (index >= 0); buf.append( 'E' ); OString symName( buf.makeStringAndClear() ); //rtti = (type_info *)dlsym( m_hApp, symName.getStr() ); if (hmod == NULL) hmod = dlopen( "gcc3_uno.dll", 0); if (hmod) rtti = (type_info *)dlsym( hmod, symName.getStr() ); if (rtti) { pair< t_rtti_map::iterator, bool > insertion( m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" ); } else { // try to lookup the symbol in the generated rtti map t_rtti_map::const_iterator iFind( m_generatedRttis.find( unoName ) ); if (iFind == m_generatedRttis.end()) { // we must generate it ! // symbol and rtti-name is nearly identical, // the symbol is prefixed with __ZTI char const * rttiName = symName.getStr() +5; #if OSL_DEBUG_LEVEL > 1 fprintf( stderr,"generated rtti for %s\n", rttiName ); #endif if (pTypeDescr->pBaseTypeDescription) { // ensure availability of base type_info * base_rtti = getRTTI( (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription ); rtti = new __si_class_type_info( strdup( rttiName ), (__class_type_info *)base_rtti ); } else { // this class has no base class rtti = new __class_type_info( strdup( rttiName ) ); } pair< t_rtti_map::iterator, bool > insertion( m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" ); } else // taking already generated rtti { rtti = iFind->second; } } } else { rtti = iFind->second; } return rtti; } //-------------------------------------------------------------------------------------------------- static void deleteException( void * pExc ) { __cxa_exception const * header = ((__cxa_exception const *)pExc - 1); typelib_TypeDescription * pTD = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pTD, unoName.pData ); OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" ); if (pTD) { ::uno_destructData( pExc, pTD, cpp_release ); ::typelib_typedescription_release( pTD ); } } //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { #if OSL_DEBUG_LEVEL > 1 OString cstr( OUStringToOString( *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> uno exception occured: %s\n", cstr.getStr() ); #endif void * pCppExc; type_info * rtti; { // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); OSL_ASSERT( pTypeDescr ); if (! pTypeDescr) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("cannot get typedescription for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } pCppExc = __cxa_allocate_exception( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); // avoiding locked counts static RTTI * s_rtti = 0; if (! s_rtti) { MutexGuard guard( Mutex::getGlobalMutex() ); if (! s_rtti) { #ifdef LEAK_STATIC_DATA s_rtti = new RTTI(); #else static RTTI rtti_data; s_rtti = &rtti_data; #endif } } rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr ); TYPELIB_DANGER_RELEASE( pTypeDescr ); OSL_ENSURE( rtti, "### no rtti for throwing exception!" ); if (! rtti) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("no rtti for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } } __cxa_throw( pCppExc, rtti, deleteException ); } //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno ) { if (! header) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("no exception header!") ), Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_ENSURE( 0, cstr.getStr() ); #endif return; } typelib_TypeDescription * pExcTypeDescr = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); #if OSL_DEBUG_LEVEL > 1 OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> c++ exception occured: %s\n", cstr_unoName.getStr() ); #endif typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData ); if (0 == pExcTypeDescr) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("exception type not found: ") ) + unoName, Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_ENSURE( 0, cstr.getStr() ); #endif } else { // construct uno exception any uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno ); typelib_typedescription_release( pExcTypeDescr ); } } } <|endoftext|>
<commit_before>/// /// @file S2_hard_mpi_msg.cpp /// @brief MPI utility functions and classes. /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <S2_hard_mpi_msg.hpp> #include <cstddef> #include <mpi.h> #include <int128.hpp> #ifndef MPI_INT64_T #define MPI_INT64_T MPI_LONG_LONG #endif namespace primecount { S2_hard_mpi_msg::S2_hard_mpi_msg() { init_MPI_struct(); reset(); } S2_hard_mpi_msg::S2_hard_mpi_msg(int64_t proc_id, int64_t low, int64_t high, int64_t segment_size, int64_t segments_per_thread) { init_MPI_struct(); set(proc_id, low, high, segment_size, segments_per_thread); } void S2_hard_mpi_msg::set(int64_t proc_id, int64_t low, int64_t high, int64_t segment_size, int64_t segments_per_thread) { reset(); msgData_.proc_id = proc_id; msgData_.low = low; msgData_.high = high; msgData_.segment_size = segment_size; msgData_.segments_per_thread = segments_per_thread; } void S2_hard_mpi_msg::reset() { msgData_.proc_id = 0; msgData_.low = 0; msgData_.high = 0; msgData_.segment_size = 0; msgData_.segments_per_thread = 0; msgData_.s2_hard[0] = 0; msgData_.s2_hard[1] = 0; msgData_.init_seconds = 0; msgData_.seconds = 0; msgData_.rsd = 0; msgData_.finished = false; } S2_hard_mpi_msg::~S2_hard_mpi_msg() { MPI_Type_free(&mpi_type_); } void S2_hard_mpi_msg::init_MPI_struct() { int items = 10; int block_lengths[10] = { 1, 1, 1, 1, 1, 2, 1, 1, 1, 1 }; MPI_Datatype types[10] = { MPI_INT, // proc_id MPI_INT64_T, // low MPI_INT64_T, // high MPI_INT64_T, // segment_size MPI_INT64_T, // segments_per_thread MPI_INT64_T, // s2_hard MPI_DOUBLE, // init_seconds MPI_DOUBLE, // seconds MPI_DOUBLE, // rsd MPI_INT }; // finished MPI_Aint offsets[10]; offsets[0] = offsetof(MsgData, proc_id); offsets[1] = offsetof(MsgData, low); offsets[2] = offsetof(MsgData, high); offsets[3] = offsetof(MsgData, segment_size); offsets[4] = offsetof(MsgData, segments_per_thread); offsets[5] = offsetof(MsgData, s2_hard); offsets[6] = offsetof(MsgData, init_seconds); offsets[7] = offsetof(MsgData, seconds); offsets[8] = offsetof(MsgData, rsd); offsets[9] = offsetof(MsgData, finished); MPI_Type_create_struct(items, block_lengths, offsets, types, &mpi_type_); MPI_Type_commit(&mpi_type_); } void S2_hard_mpi_msg::send(int proc_id) { MPI_Send(&msgData_, 1, mpi_type_, proc_id, proc_id, MPI_COMM_WORLD); } void S2_hard_mpi_msg::send_finish() { msgData_.finished = true; int proc_id = msgData_.proc_id; MPI_Send(&msgData_, 1, mpi_type_, proc_id, proc_id, MPI_COMM_WORLD); } void S2_hard_mpi_msg::recv(int proc_id) { MPI_Status status; MPI_Recv(&msgData_, 1, mpi_type_, mpi_master_proc_id(), proc_id, MPI_COMM_WORLD, &status); } void S2_hard_mpi_msg::recv_any() { MPI_Status status; MPI_Recv(&msgData_, 1, mpi_type_, MPI_ANY_SOURCE, mpi_master_proc_id(), MPI_COMM_WORLD, &status); } int S2_hard_mpi_msg::proc_id() const { return msgData_.proc_id; } int64_t S2_hard_mpi_msg::low() const { return msgData_.low; } int64_t S2_hard_mpi_msg::high() const { return msgData_.high; } int64_t S2_hard_mpi_msg::segment_size() const { return msgData_.segment_size; } int64_t S2_hard_mpi_msg::segments_per_thread() const { return msgData_.segments_per_thread; } double S2_hard_mpi_msg::init_seconds() const { return msgData_.init_seconds; } double S2_hard_mpi_msg::seconds() const { return msgData_.seconds; } double S2_hard_mpi_msg::rsd() const { return msgData_.rsd; } bool S2_hard_mpi_msg::finished() const { return ((bool) msgData_.finished) == true; } } // namespace <commit_msg>Add rsd<commit_after>/// /// @file S2_hard_mpi_msg.cpp /// @brief MPI utility functions and classes. /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <S2_hard_mpi_msg.hpp> #include <cstddef> #include <mpi.h> #include <int128.hpp> #ifndef MPI_INT64_T #define MPI_INT64_T MPI_LONG_LONG #endif namespace primecount { S2_hard_mpi_msg::S2_hard_mpi_msg() { init_MPI_struct(); reset(); } S2_hard_mpi_msg::S2_hard_mpi_msg(int64_t proc_id, int64_t low, int64_t high, int64_t segment_size, int64_t segments_per_thread) { init_MPI_struct(); double rsd = 40; set(proc_id, low, high, segment_size, segments_per_thread, rsd); } void S2_hard_mpi_msg::set(int64_t proc_id, int64_t low, int64_t high, int64_t segment_size, int64_t segments_per_thread, double rsd) { reset(); msgData_.proc_id = proc_id; msgData_.low = low; msgData_.high = high; msgData_.segment_size = segment_size; msgData_.segments_per_thread = segments_per_thread; msgData_.rsd = rsd; } void S2_hard_mpi_msg::reset() { msgData_.proc_id = 0; msgData_.low = 0; msgData_.high = 0; msgData_.segment_size = 0; msgData_.segments_per_thread = 0; msgData_.s2_hard[0] = 0; msgData_.s2_hard[1] = 0; msgData_.init_seconds = 0; msgData_.seconds = 0; msgData_.rsd = 0; msgData_.finished = false; } S2_hard_mpi_msg::~S2_hard_mpi_msg() { MPI_Type_free(&mpi_type_); } void S2_hard_mpi_msg::init_MPI_struct() { int items = 10; int block_lengths[10] = { 1, 1, 1, 1, 1, 2, 1, 1, 1, 1 }; MPI_Datatype types[10] = { MPI_INT, // proc_id MPI_INT64_T, // low MPI_INT64_T, // high MPI_INT64_T, // segment_size MPI_INT64_T, // segments_per_thread MPI_INT64_T, // s2_hard MPI_DOUBLE, // init_seconds MPI_DOUBLE, // seconds MPI_DOUBLE, // rsd MPI_INT }; // finished MPI_Aint offsets[10]; offsets[0] = offsetof(MsgData, proc_id); offsets[1] = offsetof(MsgData, low); offsets[2] = offsetof(MsgData, high); offsets[3] = offsetof(MsgData, segment_size); offsets[4] = offsetof(MsgData, segments_per_thread); offsets[5] = offsetof(MsgData, s2_hard); offsets[6] = offsetof(MsgData, init_seconds); offsets[7] = offsetof(MsgData, seconds); offsets[8] = offsetof(MsgData, rsd); offsets[9] = offsetof(MsgData, finished); MPI_Type_create_struct(items, block_lengths, offsets, types, &mpi_type_); MPI_Type_commit(&mpi_type_); } void S2_hard_mpi_msg::send(int proc_id) { MPI_Send(&msgData_, 1, mpi_type_, proc_id, proc_id, MPI_COMM_WORLD); } void S2_hard_mpi_msg::send_finish() { msgData_.finished = true; int proc_id = msgData_.proc_id; MPI_Send(&msgData_, 1, mpi_type_, proc_id, proc_id, MPI_COMM_WORLD); } void S2_hard_mpi_msg::recv(int proc_id) { MPI_Status status; MPI_Recv(&msgData_, 1, mpi_type_, mpi_master_proc_id(), proc_id, MPI_COMM_WORLD, &status); } void S2_hard_mpi_msg::recv_any() { MPI_Status status; MPI_Recv(&msgData_, 1, mpi_type_, MPI_ANY_SOURCE, mpi_master_proc_id(), MPI_COMM_WORLD, &status); } int S2_hard_mpi_msg::proc_id() const { return msgData_.proc_id; } int64_t S2_hard_mpi_msg::low() const { return msgData_.low; } int64_t S2_hard_mpi_msg::high() const { return msgData_.high; } int64_t S2_hard_mpi_msg::segment_size() const { return msgData_.segment_size; } int64_t S2_hard_mpi_msg::segments_per_thread() const { return msgData_.segments_per_thread; } double S2_hard_mpi_msg::init_seconds() const { return msgData_.init_seconds; } double S2_hard_mpi_msg::seconds() const { return msgData_.seconds; } double S2_hard_mpi_msg::rsd() const { return msgData_.rsd; } bool S2_hard_mpi_msg::finished() const { return ((bool) msgData_.finished) == true; } } // namespace <|endoftext|>
<commit_before><commit_msg>Disable BookmarkBarViewTest15.MenuStaysVisibleAfterDelete on Chromium OS.<commit_after><|endoftext|>
<commit_before>//***************************************************************************** // Copyright 2017-2019 Intel 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 <memory> #include "gemm.hpp" #include "ngraph/op/fused/gemm.hpp" namespace ngraph { namespace onnx_import { namespace op { namespace set_1 { NodeVector gemm(const Node& node) { NodeVector inputs{node.get_ng_inputs()}; auto input_a = inputs.at(0); auto input_b = inputs.at(1); auto input_c = inputs.at(2); double alpha = node.get_attribute_value<double>("alpha", 1); double beta = node.get_attribute_value<double>("beta", 1); bool trans_a = node.get_attribute_value<int64_t>("transA", 0); bool trans_b = node.get_attribute_value<int64_t>("transB", 0); return NodeVector{std::make_shared<ngraph::op::Gemm>( input_a, input_b, input_c, alpha, beta, trans_a, trans_b)}; } } // namespace set_1 } // namespace op } // namespace onnx_import } // namespace ngraph <commit_msg>[ONNX] Add support for optional C input in Gemm op (#3821)<commit_after>//***************************************************************************** // Copyright 2017-2019 Intel 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 <memory> #include "gemm.hpp" #include "ngraph/op/constant.hpp" #include "ngraph/op/fused/gemm.hpp" namespace ngraph { namespace onnx_import { namespace op { namespace set_1 { NodeVector gemm(const Node& node) { NodeVector inputs{node.get_ng_inputs()}; std::shared_ptr<ngraph::Node> input_a = inputs.at(0); std::shared_ptr<ngraph::Node> input_b = inputs.at(1); std::shared_ptr<ngraph::Node> input_c; if (inputs.size() == 3) { input_c = inputs.at(2); } else { input_c = ngraph::op::Constant::create( input_b->get_element_type(), ngraph::Shape{}, {0}); } double alpha = node.get_attribute_value<double>("alpha", 1); double beta = node.get_attribute_value<double>("beta", 1); bool trans_a = node.get_attribute_value<int64_t>("transA", 0); bool trans_b = node.get_attribute_value<int64_t>("transB", 0); return NodeVector{std::make_shared<ngraph::op::Gemm>( input_a, input_b, input_c, alpha, beta, trans_a, trans_b)}; } } // namespace set_1 } // namespace op } // namespace onnx_import } // namespace ngraph <|endoftext|>
<commit_before>/* ** Copyright 2009-2011,2014-2015 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <cstring> #include "com/centreon/broker/neb/log_entry.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/neb/internal.hh" #include "com/centreon/broker/neb/set_log_data.hh" using namespace com::centreon::broker; /** * Extract the first element of a log string. */ static char* log_extract_first(char* str, char** lasts) { char* data(strtok_r(str, ";", lasts)); if (!data) throw (exceptions::msg() << "log: data extraction failed"); return (data); } /** * Extract following elements of a log string. */ static char* log_extract(char** lasts) { char* data(strtok_r(NULL, ";", lasts)); if (!data) throw (exceptions::msg() << "log: data extraction failed"); return (data); } /** * Get the id of a log status. */ static int status_id(char const* status) { int id; if (!strcmp(status, "DOWN") || !strcmp(status, "WARNING")) id = 1; else if (!strcmp(status, "UNREACHABLE") || !strcmp(status, "CRITICAL")) id = 2; else if (!strcmp(status, "UNKNOWN")) id = 3; else if (!strcmp(status, "PENDING")) id = 4; else id = 0; return (id); } /** * Get the id of a log type. */ static int type_id(char const* type) { int id; if (!strcmp(type, "HARD")) id = 1; else id = 0; return (id); } /** * Extract Nagios-formated log data to the C++ object. */ void neb::set_log_data(neb::log_entry& le, char const* log_data) { // Duplicate string so that we can split it with strtok_r. char* datadup(strdup(log_data)); if (!datadup) throw (exceptions::msg() << "log: data extraction failed"); try { char* lasts; // First part is the log description. lasts = datadup + strcspn(datadup, ":"); if (*lasts) { *lasts = '\0'; lasts = lasts + 1 + strspn(lasts + 1, " "); } if (!strcmp(datadup, "SERVICE ALERT")) { le.msg_type = 0; le.host_name = log_extract_first(lasts, &lasts); le.service_description = log_extract(&lasts); le.status = status_id(log_extract(&lasts)); le.log_type = type_id(log_extract(&lasts)); le.retry = strtol(log_extract(&lasts), NULL, 10); le.output = log_extract(&lasts); } else if (!strcmp(datadup, "HOST ALERT")) { le.msg_type = 1; le.host_name = log_extract_first(lasts, &lasts); le.status = status_id(log_extract(&lasts)); le.log_type = type_id(log_extract(&lasts)); le.retry = strtol(log_extract(&lasts), NULL, 10); le.output = log_extract(&lasts); } else if (!strcmp(datadup, "CURRENT SERVICE STATE")) { le.msg_type = 6; le.host_name = log_extract_first(lasts, &lasts); le.service_description = log_extract(&lasts); le.status = status_id(log_extract(&lasts)); le.log_type = type_id(log_extract(&lasts)); le.retry = strtol(log_extract(&lasts), NULL, 10); le.output = log_extract(&lasts); } else if (!strcmp(datadup, "CURRENT HOST STATE")) { le.msg_type = 7; le.host_name = log_extract_first(lasts, &lasts); le.status = status_id(log_extract(&lasts)); le.log_type = type_id(log_extract(&lasts)); le.retry = strtol(log_extract(&lasts), NULL, 10); le.output = log_extract(&lasts); } else if (!strcmp(datadup, "INITIAL HOST STATE")) { le.msg_type = 9; le.host_name = log_extract_first(lasts, &lasts); le.status = status_id(log_extract(&lasts)); le.log_type = type_id(log_extract(&lasts)); le.retry = strtol(log_extract(&lasts), NULL, 10); le.output = log_extract(&lasts); } else if (!strcmp(datadup, "INITIAL SERVICE STATE")) { le.msg_type = 8; le.host_name = log_extract_first(lasts, &lasts); le.service_description = log_extract(&lasts); le.status = status_id(log_extract(&lasts)); le.log_type = type_id(log_extract(&lasts)); le.retry = strtol(log_extract(&lasts), NULL, 10); le.output = log_extract(&lasts); } else if (!strcmp(datadup, "EXTERNAL COMMAND")) { log_extract_first(lasts, &lasts); le.msg_type = 5; le.output = "EXTERNAL COMMAND: "; le.output.append(lasts); } else if (!strcmp(datadup, "Warning")) { le.msg_type = 4; le.output = lasts; } else { le.msg_type = 5; le.output = log_data; } } catch (...) {} free(datadup); // Set host and service IDs. umap<std::string, int>::const_iterator host_it; std::map<std::pair<std::string, std::string>, std::pair<int, int> >::const_iterator service_it; host_it = neb::gl_hosts.find(le.host_name.toStdString()); if (host_it != neb::gl_hosts.end()) le.host_id = host_it->second; service_it = neb::gl_services.find(std::make_pair(le.host_name.toStdString(), le.service_description.toStdString())); if (service_it != neb::gl_services.end()) { le.host_id = service_it->second.first; le.service_id = service_it->second.second; } return ; } <commit_msg>NEB: fix external command logging.<commit_after>/* ** Copyright 2009-2011,2014-2015 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <cstring> #include "com/centreon/broker/neb/log_entry.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/neb/internal.hh" #include "com/centreon/broker/neb/set_log_data.hh" using namespace com::centreon::broker; /** * Extract the first element of a log string. */ static char* log_extract_first(char* str, char** lasts) { char* data(strtok_r(str, ";", lasts)); if (!data) throw (exceptions::msg() << "log: data extraction failed"); return (data); } /** * Extract following elements of a log string. */ static char* log_extract(char** lasts) { char* data(strtok_r(NULL, ";", lasts)); if (!data) throw (exceptions::msg() << "log: data extraction failed"); return (data); } /** * Get the id of a log status. */ static int status_id(char const* status) { int id; if (!strcmp(status, "DOWN") || !strcmp(status, "WARNING")) id = 1; else if (!strcmp(status, "UNREACHABLE") || !strcmp(status, "CRITICAL")) id = 2; else if (!strcmp(status, "UNKNOWN")) id = 3; else if (!strcmp(status, "PENDING")) id = 4; else id = 0; return (id); } /** * Get the id of a log type. */ static int type_id(char const* type) { int id; if (!strcmp(type, "HARD")) id = 1; else id = 0; return (id); } /** * Extract Nagios-formated log data to the C++ object. */ void neb::set_log_data(neb::log_entry& le, char const* log_data) { // Duplicate string so that we can split it with strtok_r. char* datadup(strdup(log_data)); if (!datadup) throw (exceptions::msg() << "log: data extraction failed"); try { char* lasts; // First part is the log description. lasts = datadup + strcspn(datadup, ":"); if (*lasts) { *lasts = '\0'; lasts = lasts + 1 + strspn(lasts + 1, " "); } if (!strcmp(datadup, "SERVICE ALERT")) { le.msg_type = 0; le.host_name = log_extract_first(lasts, &lasts); le.service_description = log_extract(&lasts); le.status = status_id(log_extract(&lasts)); le.log_type = type_id(log_extract(&lasts)); le.retry = strtol(log_extract(&lasts), NULL, 10); le.output = log_extract(&lasts); } else if (!strcmp(datadup, "HOST ALERT")) { le.msg_type = 1; le.host_name = log_extract_first(lasts, &lasts); le.status = status_id(log_extract(&lasts)); le.log_type = type_id(log_extract(&lasts)); le.retry = strtol(log_extract(&lasts), NULL, 10); le.output = log_extract(&lasts); } else if (!strcmp(datadup, "CURRENT SERVICE STATE")) { le.msg_type = 6; le.host_name = log_extract_first(lasts, &lasts); le.service_description = log_extract(&lasts); le.status = status_id(log_extract(&lasts)); le.log_type = type_id(log_extract(&lasts)); le.retry = strtol(log_extract(&lasts), NULL, 10); le.output = log_extract(&lasts); } else if (!strcmp(datadup, "CURRENT HOST STATE")) { le.msg_type = 7; le.host_name = log_extract_first(lasts, &lasts); le.status = status_id(log_extract(&lasts)); le.log_type = type_id(log_extract(&lasts)); le.retry = strtol(log_extract(&lasts), NULL, 10); le.output = log_extract(&lasts); } else if (!strcmp(datadup, "INITIAL HOST STATE")) { le.msg_type = 9; le.host_name = log_extract_first(lasts, &lasts); le.status = status_id(log_extract(&lasts)); le.log_type = type_id(log_extract(&lasts)); le.retry = strtol(log_extract(&lasts), NULL, 10); le.output = log_extract(&lasts); } else if (!strcmp(datadup, "INITIAL SERVICE STATE")) { le.msg_type = 8; le.host_name = log_extract_first(lasts, &lasts); le.service_description = log_extract(&lasts); le.status = status_id(log_extract(&lasts)); le.log_type = type_id(log_extract(&lasts)); le.retry = strtol(log_extract(&lasts), NULL, 10); le.output = log_extract(&lasts); } else if (!strcmp(datadup, "EXTERNAL COMMAND")) { le.msg_type = 5; le.output = "EXTERNAL COMMAND: "; le.output.append(lasts); } else if (!strcmp(datadup, "Warning")) { le.msg_type = 4; le.output = lasts; } else { le.msg_type = 5; le.output = log_data; } } catch (...) {} free(datadup); // Set host and service IDs. umap<std::string, int>::const_iterator host_it; std::map<std::pair<std::string, std::string>, std::pair<int, int> >::const_iterator service_it; host_it = neb::gl_hosts.find(le.host_name.toStdString()); if (host_it != neb::gl_hosts.end()) le.host_id = host_it->second; service_it = neb::gl_services.find(std::make_pair(le.host_name.toStdString(), le.service_description.toStdString())); if (service_it != neb::gl_services.end()) { le.host_id = service_it->second.first; le.service_id = service_it->second.second; } return ; } <|endoftext|>
<commit_before>#include "pubsub_man.h" #include "event_loop.h" #include "log_macros.h" #include "WampTypes.h" #include "SessionMan.h" #include "kernel.h" #include "wamp_utils.h" #include <list> #include <iostream> namespace XXX { /* TODO: what locking is needed around this? - as subs are added, they will READ. need to sync the addition of the subscriber, with the series of images and updates it sees. - as PUBLISH events arrive, they will write */ struct managed_topic { std::vector< std::weak_ptr<wamp_session> > m_subscribers; // current upto date image of the value jalson::json_value image; // Note, we are tieing the subscription ID direct to the topic. WAMP does // allow this, and it has the benefit that we can perform a single message // serialisation for all subscribers. Might have to change later if more // complex subscription features are supported. size_t subscription_id; managed_topic(size_t __subscription_id) : subscription_id(__subscription_id) { } uint64_t next_publication_id() { return m_id_gen.next(); } private: global_scope_id_generator m_id_gen; }; /* Constructor */ pubsub_man::pubsub_man(kernel& k) : __logger(k.get_logger()), m_next_subscription_id(1) /* zero used for initial snapshot */ { } pubsub_man::~pubsub_man() { // destructor needed here so that unique_ptr can see the definition of // managed_topic } /* static bool compare_session(const session_handle& p1, const session_handle& p2) { return ( !p1.owner_before(p2) && !p2.owner_before(p1) ); } */ managed_topic* pubsub_man::find_topic(const std::string& topic, const std::string& realm, bool allow_create) { auto realm_iter = m_topics.find( realm ); if (realm_iter == m_topics.end()) { if (allow_create) { auto result = m_topics.insert(std::make_pair(realm, topic_registry())); realm_iter = result.first; } else return nullptr; } auto topic_iter = realm_iter->second.find( topic ); if (topic_iter == realm_iter->second.end()) { if (allow_create) { std::unique_ptr<managed_topic> ptr(new managed_topic(m_next_subscription_id++)); auto result = realm_iter->second.insert(std::make_pair(topic, std::move( ptr ))); topic_iter = result.first; } else return nullptr; } return topic_iter->second.get(); } void pubsub_man::update_topic(const std::string& topic, const std::string& realm, jalson::json_object options, wamp_args args) { /* EVENT thread */ // resolve topic managed_topic* mt = find_topic(topic, realm, true); // TODO: do we want to reply to the originating client, if we reject the // publish? Also, we can have other exceptions (below), e.g., patch // exceptions. Also, dont want to throw, if it is an internal update if (!mt) return; if (options.find("_p") != options.end() && args.args_list.is_array()) { // apply the patch std::cout << "@" << topic << ", patch\n"; std::cout << "BEFORE: " << mt->image << "\n"; std::cout << "PATCH : " << args.args_list << "\n"; jalson::json_array & change = args.args_list.as_array(); mt->image.patch(change[0].as_array()); std::cout << "AFTER : " << mt->image << "\n"; std::cout << "-------\n"; } // broadcast event to subscribers jalson::json_array msg; msg.reserve(6); msg.push_back( EVENT ); msg.push_back( mt->subscription_id ); msg.push_back( mt->next_publication_id() ); msg.push_back( std::move(options) ); if (!args.args_list.is_null()) { msg.push_back( args.args_list ); if (!args.args_dict.is_null()) msg.push_back( args.args_dict ); } size_t num_active = 0; for (auto & item : mt->m_subscribers) { if (auto sp = item.lock()) { sp->send_msg(msg); num_active++; } } // remove any expired sessions if (num_active != mt->m_subscribers.size()) { std::vector< std::weak_ptr<wamp_session> > temp; temp.resize(num_active); for (auto item : mt->m_subscribers) { if (!item.expired()) temp.push_back( std::move(item) ); } mt->m_subscribers.swap( temp ); } } /* Handle arrival of the a PUBLISH event, targeted at a topic. */ void pubsub_man::inbound_publish(std::string realm, std::string topic, jalson::json_object options, wamp_args args) { /* EV thread */ update_topic(topic, realm, std::move(options), args); } uint64_t pubsub_man::subscribe(wamp_session* sptr, t_request_id request_id, std::string uri, jalson::json_object & options) { /* EV thread */ /* We have received an external request to subscribe to a top */ // validate the URI // TODO: implement Strict URIs if (uri.empty()) throw wamp_error(WAMP_ERROR_INVALID_URI, "URI zero length"); // find or create a topic managed_topic* mt = find_topic(uri, sptr->realm(), true); if (!mt) throw wamp_error(WAMP_ERROR_INVALID_URI); LOG_INFO("session " << sptr->unique_id() << " subscribing to '"<< uri<< "'"); /* SUBSCRIBED acknowledgement */ jalson::json_array subscribed_msg; subscribed_msg.reserve(3); subscribed_msg.push_back(SUBSCRIBED); subscribed_msg.push_back(request_id); subscribed_msg.push_back(mt->subscription_id); sptr->send_msg(subscribed_msg); /* for stateful topic must send initial snapshot */ if (options.find("_p") != options.end()) { XXX::wamp_args pub_args; pub_args.args_list = jalson::json_array(); jalson::json_array patch; jalson::json_object& operation = jalson::append_object(patch); operation["op"] = "replace"; operation["path"] = ""; /* replace whole document */ operation["value"] = mt->image; pub_args.args_list.as_array().push_back(std::move(patch)); pub_args.args_list.as_array().push_back(jalson::json_array()); // empty event jalson::json_object event_options; event_options["_p"] = options["_p"]; event_options["_snap"] = 1; jalson::json_array snapshot_msg; snapshot_msg.reserve(5); snapshot_msg.push_back( EVENT ); snapshot_msg.push_back( mt->subscription_id ); snapshot_msg.push_back( 0 ); // publication id snapshot_msg.push_back( std::move(event_options) ); snapshot_msg.push_back( pub_args.args_list ); sptr->send_msg(snapshot_msg); } mt->m_subscribers.push_back(sptr->handle()); return mt->subscription_id; } void pubsub_man::session_closed(session_handle /*sh*/) { /* EV loop */ // // design of this can be improved, ie, we should track what topics a session // // has subscribed too, rather than searching every topic. // for (auto & realm_iter : m_topics) // for (auto & item : realm_iter.second) // { // for (auto it = item.second->m_subscribers.begin(); // it != item.second->m_subscribers.end(); it++) // { // if (compare_session( *it, sh)) // { // item.second->m_subscribers.erase( it ); // break; // } // } // } } } // namespace XXX <commit_msg>updated comment<commit_after>#include "pubsub_man.h" #include "event_loop.h" #include "log_macros.h" #include "WampTypes.h" #include "SessionMan.h" #include "kernel.h" #include "wamp_utils.h" #include <list> #include <iostream> namespace XXX { /* Thread safety for pubsub. Currently the public methods: - inbound_publish - subscribe ... are both called on the event loop thead, so presently no need for any synchronization around the managed topics. Additionally for the addition of a new subscriber, the synchronization of the initially snapshot followed by updates is also acheived through the single threaded approach. */ struct managed_topic { std::vector< std::weak_ptr<wamp_session> > m_subscribers; // current upto date image of the value jalson::json_value image; // Note, we are tieing the subscription ID direct to the topic. WAMP does // allow this, and it has the benefit that we can perform a single message // serialisation for all subscribers. Might have to change later if more // complex subscription features are supported. size_t subscription_id; managed_topic(size_t __subscription_id) : subscription_id(__subscription_id) { } uint64_t next_publication_id() { return m_id_gen.next(); } private: global_scope_id_generator m_id_gen; }; /* Constructor */ pubsub_man::pubsub_man(kernel& k) : __logger(k.get_logger()), m_next_subscription_id(1) /* zero used for initial snapshot */ { } pubsub_man::~pubsub_man() { // destructor needed here so that unique_ptr can see the definition of // managed_topic } /* static bool compare_session(const session_handle& p1, const session_handle& p2) { return ( !p1.owner_before(p2) && !p2.owner_before(p1) ); } */ managed_topic* pubsub_man::find_topic(const std::string& topic, const std::string& realm, bool allow_create) { auto realm_iter = m_topics.find( realm ); if (realm_iter == m_topics.end()) { if (allow_create) { auto result = m_topics.insert(std::make_pair(realm, topic_registry())); realm_iter = result.first; } else return nullptr; } auto topic_iter = realm_iter->second.find( topic ); if (topic_iter == realm_iter->second.end()) { if (allow_create) { std::unique_ptr<managed_topic> ptr(new managed_topic(m_next_subscription_id++)); auto result = realm_iter->second.insert(std::make_pair(topic, std::move( ptr ))); topic_iter = result.first; } else return nullptr; } return topic_iter->second.get(); } void pubsub_man::update_topic(const std::string& topic, const std::string& realm, jalson::json_object options, wamp_args args) { /* EVENT thread */ // resolve topic managed_topic* mt = find_topic(topic, realm, true); // TODO: do we want to reply to the originating client, if we reject the // publish? Also, we can have other exceptions (below), e.g., patch // exceptions. Also, dont want to throw, if it is an internal update if (!mt) return; if (options.find("_p") != options.end() && args.args_list.is_array()) { // apply the patch std::cout << "@" << topic << ", patch\n"; std::cout << "BEFORE: " << mt->image << "\n"; std::cout << "PATCH : " << args.args_list << "\n"; jalson::json_array & change = args.args_list.as_array(); mt->image.patch(change[0].as_array()); std::cout << "AFTER : " << mt->image << "\n"; std::cout << "-------\n"; } // broadcast event to subscribers jalson::json_array msg; msg.reserve(6); msg.push_back( EVENT ); msg.push_back( mt->subscription_id ); msg.push_back( mt->next_publication_id() ); msg.push_back( std::move(options) ); if (!args.args_list.is_null()) { msg.push_back( args.args_list ); if (!args.args_dict.is_null()) msg.push_back( args.args_dict ); } size_t num_active = 0; for (auto & item : mt->m_subscribers) { if (auto sp = item.lock()) { sp->send_msg(msg); num_active++; } } // remove any expired sessions if (num_active != mt->m_subscribers.size()) { std::vector< std::weak_ptr<wamp_session> > temp; temp.resize(num_active); for (auto item : mt->m_subscribers) { if (!item.expired()) temp.push_back( std::move(item) ); } mt->m_subscribers.swap( temp ); } } /* Handle arrival of the a PUBLISH event, targeted at a topic. This will write * to a managed topic. */ void pubsub_man::inbound_publish(std::string realm, std::string topic, jalson::json_object options, wamp_args args) { /* EV thread */ update_topic(topic, realm, std::move(options), args); } /* Add a subscription to a managed topic. Need to sync the addition of the subscriber, with the series of images and updates it sees. This is done via single threaded access to this class. */ uint64_t pubsub_man::subscribe(wamp_session* sptr, t_request_id request_id, std::string uri, jalson::json_object & options) { /* EV thread */ /* We have received an external request to subscribe to a top */ // validate the URI // TODO: implement Strict URIs if (uri.empty()) throw wamp_error(WAMP_ERROR_INVALID_URI, "URI zero length"); // find or create a topic managed_topic* mt = find_topic(uri, sptr->realm(), true); if (!mt) throw wamp_error(WAMP_ERROR_INVALID_URI); LOG_INFO("session " << sptr->unique_id() << " subscribing to '"<< uri<< "'"); /* SUBSCRIBED acknowledgement */ jalson::json_array subscribed_msg; subscribed_msg.reserve(3); subscribed_msg.push_back(SUBSCRIBED); subscribed_msg.push_back(request_id); subscribed_msg.push_back(mt->subscription_id); sptr->send_msg(subscribed_msg); /* for stateful topic must send initial snapshot */ if (options.find("_p") != options.end()) { XXX::wamp_args pub_args; pub_args.args_list = jalson::json_array(); jalson::json_array patch; jalson::json_object& operation = jalson::append_object(patch); operation["op"] = "replace"; operation["path"] = ""; /* replace whole document */ operation["value"] = mt->image; pub_args.args_list.as_array().push_back(std::move(patch)); pub_args.args_list.as_array().push_back(jalson::json_array()); // empty event jalson::json_object event_options; event_options["_p"] = options["_p"]; event_options["_snap"] = 1; jalson::json_array snapshot_msg; snapshot_msg.reserve(5); snapshot_msg.push_back( EVENT ); snapshot_msg.push_back( mt->subscription_id ); snapshot_msg.push_back( 0 ); // publication id snapshot_msg.push_back( std::move(event_options) ); snapshot_msg.push_back( pub_args.args_list ); sptr->send_msg(snapshot_msg); } mt->m_subscribers.push_back(sptr->handle()); return mt->subscription_id; } void pubsub_man::session_closed(session_handle /*sh*/) { /* EV loop */ // // design of this can be improved, ie, we should track what topics a session // // has subscribed too, rather than searching every topic. // for (auto & realm_iter : m_topics) // for (auto & item : realm_iter.second) // { // for (auto it = item.second->m_subscribers.begin(); // it != item.second->m_subscribers.end(); it++) // { // if (compare_session( *it, sh)) // { // item.second->m_subscribers.erase( it ); // break; // } // } // } } } // namespace XXX <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) 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. ===================================================================*/ // Blueberry #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // Qmitk #include "PAUSMotionCompensation.h" // Qt #include <QMessageBox> // mitk image #include <mitkImage.h> const std::string PAUSMotionCompensation::VIEW_ID = "org.mitk.views.pausmotioncompensation"; void PAUSMotionCompensation::SetFocus() { m_Controls.buttonPerformImageProcessing->setFocus(); } void PAUSMotionCompensation::CreateQtPartControl(QWidget *parent) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); connect( m_Controls.buttonPerformImageProcessing, &QPushButton::clicked, this, &PAUSMotionCompensation::DoImageProcessing); } void PAUSMotionCompensation::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*source*/, const QList<mitk::DataNode::Pointer> &nodes) { // Make sure that there are exactle 2 nodes selected if (nodes.size() == 2) { // iterate all selected objects, adjust warning visibility foreach (mitk::DataNode::Pointer node, nodes) { if (node.IsNotNull() && dynamic_cast<mitk::Image *>(node->GetData())) { m_Controls.labelWarning->setVisible(false); m_Controls.buttonPerformImageProcessing->setEnabled(true); return; } } } m_Controls.labelWarning->setVisible(true); m_Controls.buttonPerformImageProcessing->setEnabled(false); } void PAUSMotionCompensation::DoImageProcessing() { QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection(); // Make sure that there are two images selected if (nodes.empty() || nodes.size() != 2) { QMessageBox::information(nullptr, "Warning", "Please select two images before starting image processing."); return; } //TODO: I need to process two nodes and get the BaseData. mitk::DataNode *node = nodes.front(); if (!node) { // Nothing selected. Inform the user and return QMessageBox::information(nullptr, "Template", "Please load and select 2 images before starting image processing."); return; } // here we have a valid mitk::DataNode // a node itself is not very useful, we need its data item (the image) mitk::BaseData *data = node->GetData(); if (data) { // test if this data item is an image or not (could also be a surface or something totally different) mitk::Image *image = dynamic_cast<mitk::Image *>(data); if (image) { std::stringstream message; std::string name; message << "Performing image processing for image "; if (node->GetName(name)) { // a property called "name" was found for this DataNode message << "'" << name << "'"; } message << "."; MITK_INFO << message.str(); // actually do something here... m_Filter->SetInput(0, image); m_Filter->SetInput(1, image); m_Filter->Update(); node->SetData(m_Filter->GetOutput(0)); } } } <commit_msg>Debug messages were added<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) 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. ===================================================================*/ // Blueberry #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // Qmitk #include "PAUSMotionCompensation.h" // Qt #include <QMessageBox> // mitk image #include <mitkImage.h> const std::string PAUSMotionCompensation::VIEW_ID = "org.mitk.views.pausmotioncompensation"; void PAUSMotionCompensation::SetFocus() { m_Controls.buttonPerformImageProcessing->setFocus(); } void PAUSMotionCompensation::CreateQtPartControl(QWidget *parent) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi(parent); connect( m_Controls.buttonPerformImageProcessing, &QPushButton::clicked, this, &PAUSMotionCompensation::DoImageProcessing); } void PAUSMotionCompensation::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*source*/, const QList<mitk::DataNode::Pointer> &nodes) { // Make sure that there are exactle 2 nodes selected if (nodes.size() == 2) { // iterate all selected objects, adjust warning visibility foreach (mitk::DataNode::Pointer node, nodes) { if (node.IsNotNull() && dynamic_cast<mitk::Image *>(node->GetData())) { m_Controls.labelWarning->setVisible(false); m_Controls.buttonPerformImageProcessing->setEnabled(true); return; } } } m_Controls.labelWarning->setVisible(true); m_Controls.buttonPerformImageProcessing->setEnabled(false); } void PAUSMotionCompensation::DoImageProcessing() { QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection(); // Make sure that there are two images selected if (nodes.empty() || nodes.size() != 2) { QMessageBox::information(nullptr, "Warning", "Please select two images before starting image processing."); return; } //TODO: I need to process two nodes and get the BaseData. mitk::DataNode *node = nodes.front(); if (!node) { // Nothing selected. Inform the user and return QMessageBox::information(nullptr, "Template", "Please load and select 2 images before starting image processing."); return; } // here we have a valid mitk::DataNode // a node itself is not very useful, we need its data item (the image) mitk::BaseData *data = node->GetData(); if (data) { // test if this data item is an image or not (could also be a surface or something totally different) mitk::Image *image = dynamic_cast<mitk::Image *>(data); if (image) { std::stringstream message; std::string name; message << "Performing image processing for image "; if (node->GetName(name)) { // a property called "name" was found for this DataNode message << "'" << name << "'"; } message << "."; MITK_INFO << message.str(); // actually do something here... m_Filter->SetInput(0, image); m_Filter->SetInput(1, image); m_Filter->Update(); // node->SetData(m_Filter->GetOutput(0)); // mitk::Image *test = m_Filter->GetOutput(0); m_Filter->GetOutput(0); m_Filter->GetOutput(1); // node->SetData(test); MITK_INFO << "We are back in the plugin."; auto newNode = mitk::DataNode::New(); // newNode->SetData(test); newNode->SetName("Test"); this->GetDataStorage()->Add(newNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } <|endoftext|>
<commit_before>// ------------------------------------------------------------------------ // Pion is a development platform for building Reactors that process Events // ------------------------------------------------------------------------ // Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com) // // Pion 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. // // Pion is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for // more details. // // You should have received a copy of the GNU Affero General Public License // along with Pion. If not, see <http://www.gnu.org/licenses/>. // #include <boost/filesystem/operations.hpp> #include <pion/platform/ConfigManager.hpp> #include <pion/platform/DatabaseManager.hpp> #include "SQLiteDatabase.hpp" using namespace pion::platform; namespace pion { // begin namespace pion namespace plugins { // begin namespace plugins // static members of SQLiteDatabase const std::string SQLiteDatabase::BACKUP_FILE_EXTENSION = ".bak"; const std::string SQLiteDatabase::FILENAME_ELEMENT_NAME = "Filename"; // SQLiteDatabase member functions void SQLiteDatabase::setConfig(const Vocabulary& v, const xmlNodePtr config_ptr) { Database::setConfig(v, config_ptr); readConfig(config_ptr, "SQLite"); // get the Filename of the database if (! ConfigManager::getConfigOption(FILENAME_ELEMENT_NAME, m_database_name, config_ptr)) throw EmptyFilenameException(getId()); // resolve paths relative to the platform DataDirectory boost::filesystem::path path_to_file(boost::filesystem::system_complete(getDatabaseManager().getDataDirectory())); path_to_file /= m_database_name; path_to_file.normalize(); m_database_name = path_to_file.file_string(); } DatabasePtr SQLiteDatabase::clone(void) const { SQLiteDatabase *db_ptr(new SQLiteDatabase()); db_ptr->copyDatabase(*this); db_ptr->m_database_name = m_database_name; return DatabasePtr(db_ptr); } void SQLiteDatabase::open(bool create_backup) { // create a backup copy of the database before opening it const bool is_new_database = ! boost::filesystem::exists(m_database_name); if (! is_new_database && create_backup) { const std::string backup_filename(m_database_name + BACKUP_FILE_EXTENSION); if (boost::filesystem::exists(backup_filename)) boost::filesystem::remove(backup_filename); boost::filesystem::copy_file(m_database_name, backup_filename); } // open up the database if (sqlite3_open_v2(m_database_name.c_str(), &m_sqlite_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK) { // prevent memory leak (sqlite3 assigns handle even if error) if (m_sqlite_db != NULL) { sqlite3_close(m_sqlite_db); m_sqlite_db = NULL; } throw OpenDatabaseException(m_database_name); } // set a 2s busy timeout to deal with db locking sqlite3_busy_timeout(m_sqlite_db, 2000); // execute all PreSQL (if any) for (unsigned i = 0; i < m_pre_sql.size(); i++) sqlite3_exec(m_sqlite_db, m_pre_sql[i].c_str(), NULL, NULL, &m_error_ptr); } void SQLiteDatabase::close(void) { if (m_sqlite_db != NULL) sqlite3_close(m_sqlite_db); m_sqlite_db = NULL; } void SQLiteDatabase::runQuery(const std::string& sql_query) { // sanity checks PION_ASSERT(is_open()); PION_ASSERT(! sql_query.empty()); // execute the query if (sqlite3_exec(m_sqlite_db, sql_query.c_str(), NULL, NULL, &m_error_ptr) != SQLITE_OK) throw SQLiteAPIException(getSQLiteError()); } QueryPtr SQLiteDatabase::addQuery(QueryID query_id, const std::string& sql_query) { // sanity checks PION_ASSERT(is_open()); PION_ASSERT(! query_id.empty()); PION_ASSERT(! sql_query.empty()); // generate a new database query object QueryPtr query_ptr(new SQLiteQuery(sql_query, m_sqlite_db)); // add the query to our query map m_query_map.insert(std::make_pair(query_id, query_ptr)); // return the new database query object return query_ptr; } void SQLiteDatabase::createTable(const Query::FieldMap& field_map, const std::string& table_name) { PION_ASSERT(is_open()); // build a SQL query to create the output table if it doesn't yet exist std::string create_table_sql = m_create_log; stringSubstitutes(create_table_sql, field_map, table_name); // run the SQL query to create the table runQuery(create_table_sql); } QueryPtr SQLiteDatabase::prepareInsertQuery(const Query::FieldMap& field_map, const std::string& table_name) { PION_ASSERT(is_open()); // exit early if it already exists QueryMap::const_iterator query_it = m_query_map.find(INSERT_QUERY_ID); if (query_it != m_query_map.end()) return query_it->second; // build a SQL query that can be used to insert a new record std::string insert_sql = m_insert_log; stringSubstitutes(insert_sql, field_map, table_name); // compile the SQL query into a prepared statement return addQuery(Database::INSERT_QUERY_ID, insert_sql); } QueryPtr SQLiteDatabase::getBeginTransactionQuery(void) { PION_ASSERT(is_open()); QueryMap::const_iterator i = m_query_map.find(BEGIN_QUERY_ID); if (i == m_query_map.end()) return addQuery(BEGIN_QUERY_ID, m_begin_insert); return i->second; } QueryPtr SQLiteDatabase::getCommitTransactionQuery(void) { PION_ASSERT(is_open()); QueryMap::const_iterator i = m_query_map.find(COMMIT_QUERY_ID); if (i == m_query_map.end()) return addQuery(COMMIT_QUERY_ID, m_commit_insert); return i->second; } QueryPtr SQLiteDatabase::prepareFullQuery(const std::string& query) { PION_ASSERT(is_open()); QueryPtr query_ptr(new SQLiteQuery(query, m_sqlite_db)); return query_ptr; } bool SQLiteDatabase::SQLiteQuery::runFullQuery(const pion::platform::Query::FieldMap& ins, const pion::platform::EventPtr& src, const pion::platform::Query::FieldMap& outs, pion::platform::EventPtr& dest, unsigned int limit) { bool changes = false; sqlite3_reset(m_sqlite_stmt); bindEvent(ins, *src); while (sqlite3_step(m_sqlite_stmt) == SQLITE_ROW) { fetchEvent(outs, dest); changes = true; if (!--limit) return changes; } return changes; } bool SQLiteDatabase::SQLiteQuery::runFullGetMore(const pion::platform::Query::FieldMap& outs, pion::platform::EventPtr& dest, unsigned int limit) { bool changes = false; while (sqlite3_step(m_sqlite_stmt) == SQLITE_ROW) { fetchEvent(outs, dest); changes = true; if (!--limit) return changes; } return changes; } // SQLiteDatabase::SQLiteQuery member functions SQLiteDatabase::SQLiteQuery::SQLiteQuery(const std::string& sql_query, sqlite3 *db_ptr) : Query(sql_query), m_sqlite_db(db_ptr), m_sqlite_stmt(NULL) { PION_ASSERT(db_ptr != NULL); if (sqlite3_prepare_v2(m_sqlite_db, sql_query.c_str(), sql_query.size(), &m_sqlite_stmt, NULL) != SQLITE_OK) SQLiteDatabase::throwAPIException(m_sqlite_db); PION_ASSERT(m_sqlite_stmt != NULL); } bool SQLiteDatabase::SQLiteQuery::run(void) { // step forward to the next row in the query (if there are any) bool row_available = false; switch (sqlite3_step(m_sqlite_stmt)) { case SQLITE_BUSY: throw SQLiteDatabase::DatabaseBusyException(); break; case SQLITE_ROW: // a new result row is available row_available = true; break; case SQLITE_DONE: // query is finished; no more rows to return row_available = false; break; default: SQLiteDatabase::throwAPIException(m_sqlite_db); break; } return row_available; } bool SQLiteDatabase::SQLiteQuery::fetchRow(const FieldMap& field_map, EventPtr e) { bool row_available = false; switch (sqlite3_step(m_sqlite_stmt)) { case SQLITE_BUSY: throw SQLiteDatabase::DatabaseBusyException(); break; case SQLITE_ROW: // a new result row is available fetchEvent(field_map, e); row_available = true; break; case SQLITE_DONE: // query is finished; no more rows to return // row_available = false; break; default: SQLiteDatabase::throwAPIException(m_sqlite_db); break; } return row_available; } } // end namespace plugins } // end namespace pion /// creates new SQLiteDatabase objects extern "C" PION_PLUGIN_API pion::platform::Database *pion_create_SQLiteDatabase(void) { return new pion::plugins::SQLiteDatabase(); } /// destroys SQLiteDatabase objects extern "C" PION_PLUGIN_API void pion_destroy_SQLiteDatabase(pion::plugins::SQLiteDatabase *database_ptr) { delete database_ptr; } <commit_msg>SQLiteDatabase<commit_after>// ------------------------------------------------------------------------ // Pion is a development platform for building Reactors that process Events // ------------------------------------------------------------------------ // Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com) // // Pion 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. // // Pion is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for // more details. // // You should have received a copy of the GNU Affero General Public License // along with Pion. If not, see <http://www.gnu.org/licenses/>. // #include <boost/filesystem/operations.hpp> #include <pion/platform/ConfigManager.hpp> #include <pion/platform/DatabaseManager.hpp> #include "SQLiteDatabase.hpp" using namespace pion::platform; namespace pion { // begin namespace pion namespace plugins { // begin namespace plugins // static members of SQLiteDatabase const std::string SQLiteDatabase::BACKUP_FILE_EXTENSION = ".bak"; const std::string SQLiteDatabase::FILENAME_ELEMENT_NAME = "Filename"; // SQLiteDatabase member functions void SQLiteDatabase::setConfig(const Vocabulary& v, const xmlNodePtr config_ptr) { Database::setConfig(v, config_ptr); readConfig(config_ptr, "SQLite"); // get the Filename of the database if (! ConfigManager::getConfigOption(FILENAME_ELEMENT_NAME, m_database_name, config_ptr)) throw EmptyFilenameException(getId()); // resolve paths relative to the platform DataDirectory boost::filesystem::path path_to_file(boost::filesystem::system_complete(getDatabaseManager().getDataDirectory())); path_to_file /= m_database_name; path_to_file.normalize(); m_database_name = path_to_file.file_string(); } DatabasePtr SQLiteDatabase::clone(void) const { SQLiteDatabase *db_ptr(new SQLiteDatabase()); db_ptr->copyDatabase(*this); db_ptr->m_database_name = m_database_name; return DatabasePtr(db_ptr); } void SQLiteDatabase::open(bool create_backup) { // create a backup copy of the database before opening it const bool is_new_database = ! boost::filesystem::exists(m_database_name); if (! is_new_database && create_backup) { const std::string backup_filename(m_database_name + BACKUP_FILE_EXTENSION); if (boost::filesystem::exists(backup_filename)) boost::filesystem::remove(backup_filename); boost::filesystem::copy_file(m_database_name, backup_filename); } // open up the database if (sqlite3_open_v2(m_database_name.c_str(), &m_sqlite_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK) { // prevent memory leak (sqlite3 assigns handle even if error) if (m_sqlite_db != NULL) { sqlite3_close(m_sqlite_db); m_sqlite_db = NULL; } throw OpenDatabaseException(m_database_name); } // set a 2s busy timeout to deal with db locking sqlite3_busy_timeout(m_sqlite_db, 2000); // execute all PreSQL (if any) for (unsigned i = 0; i < m_pre_sql.size(); i++) if (sqlite3_exec(m_sqlite_db, m_pre_sql[i].c_str(), NULL, NULL, &m_error_ptr) != SQLITE_OK) throw SQLiteAPIException(getSQLiteError()); } void SQLiteDatabase::close(void) { if (m_sqlite_db != NULL) sqlite3_close(m_sqlite_db); m_sqlite_db = NULL; } void SQLiteDatabase::runQuery(const std::string& sql_query) { // sanity checks PION_ASSERT(is_open()); PION_ASSERT(! sql_query.empty()); // execute the query if (sqlite3_exec(m_sqlite_db, sql_query.c_str(), NULL, NULL, &m_error_ptr) != SQLITE_OK) throw SQLiteAPIException(getSQLiteError()); } QueryPtr SQLiteDatabase::addQuery(QueryID query_id, const std::string& sql_query) { // sanity checks PION_ASSERT(is_open()); PION_ASSERT(! query_id.empty()); PION_ASSERT(! sql_query.empty()); // generate a new database query object QueryPtr query_ptr(new SQLiteQuery(sql_query, m_sqlite_db)); // add the query to our query map m_query_map.insert(std::make_pair(query_id, query_ptr)); // return the new database query object return query_ptr; } void SQLiteDatabase::createTable(const Query::FieldMap& field_map, const std::string& table_name) { PION_ASSERT(is_open()); // build a SQL query to create the output table if it doesn't yet exist std::string create_table_sql = m_create_log; stringSubstitutes(create_table_sql, field_map, table_name); // run the SQL query to create the table runQuery(create_table_sql); } QueryPtr SQLiteDatabase::prepareInsertQuery(const Query::FieldMap& field_map, const std::string& table_name) { PION_ASSERT(is_open()); // exit early if it already exists QueryMap::const_iterator query_it = m_query_map.find(INSERT_QUERY_ID); if (query_it != m_query_map.end()) return query_it->second; // build a SQL query that can be used to insert a new record std::string insert_sql = m_insert_log; stringSubstitutes(insert_sql, field_map, table_name); // compile the SQL query into a prepared statement return addQuery(Database::INSERT_QUERY_ID, insert_sql); } QueryPtr SQLiteDatabase::getBeginTransactionQuery(void) { PION_ASSERT(is_open()); QueryMap::const_iterator i = m_query_map.find(BEGIN_QUERY_ID); if (i == m_query_map.end()) return addQuery(BEGIN_QUERY_ID, m_begin_insert); return i->second; } QueryPtr SQLiteDatabase::getCommitTransactionQuery(void) { PION_ASSERT(is_open()); QueryMap::const_iterator i = m_query_map.find(COMMIT_QUERY_ID); if (i == m_query_map.end()) return addQuery(COMMIT_QUERY_ID, m_commit_insert); return i->second; } QueryPtr SQLiteDatabase::prepareFullQuery(const std::string& query) { PION_ASSERT(is_open()); QueryPtr query_ptr(new SQLiteQuery(query, m_sqlite_db)); return query_ptr; } bool SQLiteDatabase::SQLiteQuery::runFullQuery(const pion::platform::Query::FieldMap& ins, const pion::platform::EventPtr& src, const pion::platform::Query::FieldMap& outs, pion::platform::EventPtr& dest, unsigned int limit) { bool changes = false; sqlite3_reset(m_sqlite_stmt); bindEvent(ins, *src); while (sqlite3_step(m_sqlite_stmt) == SQLITE_ROW) { fetchEvent(outs, dest); changes = true; if (!--limit) return changes; } return changes; } bool SQLiteDatabase::SQLiteQuery::runFullGetMore(const pion::platform::Query::FieldMap& outs, pion::platform::EventPtr& dest, unsigned int limit) { bool changes = false; while (sqlite3_step(m_sqlite_stmt) == SQLITE_ROW) { fetchEvent(outs, dest); changes = true; if (!--limit) return changes; } return changes; } // SQLiteDatabase::SQLiteQuery member functions SQLiteDatabase::SQLiteQuery::SQLiteQuery(const std::string& sql_query, sqlite3 *db_ptr) : Query(sql_query), m_sqlite_db(db_ptr), m_sqlite_stmt(NULL) { PION_ASSERT(db_ptr != NULL); if (sqlite3_prepare_v2(m_sqlite_db, sql_query.c_str(), sql_query.size(), &m_sqlite_stmt, NULL) != SQLITE_OK) SQLiteDatabase::throwAPIException(m_sqlite_db); PION_ASSERT(m_sqlite_stmt != NULL); } bool SQLiteDatabase::SQLiteQuery::run(void) { // step forward to the next row in the query (if there are any) bool row_available = false; switch (sqlite3_step(m_sqlite_stmt)) { case SQLITE_BUSY: throw SQLiteDatabase::DatabaseBusyException(); break; case SQLITE_ROW: // a new result row is available row_available = true; break; case SQLITE_DONE: // query is finished; no more rows to return row_available = false; break; default: SQLiteDatabase::throwAPIException(m_sqlite_db); break; } return row_available; } bool SQLiteDatabase::SQLiteQuery::fetchRow(const FieldMap& field_map, EventPtr e) { bool row_available = false; switch (sqlite3_step(m_sqlite_stmt)) { case SQLITE_BUSY: throw SQLiteDatabase::DatabaseBusyException(); break; case SQLITE_ROW: // a new result row is available fetchEvent(field_map, e); row_available = true; break; case SQLITE_DONE: // query is finished; no more rows to return // row_available = false; break; default: SQLiteDatabase::throwAPIException(m_sqlite_db); break; } return row_available; } } // end namespace plugins } // end namespace pion /// creates new SQLiteDatabase objects extern "C" PION_PLUGIN_API pion::platform::Database *pion_create_SQLiteDatabase(void) { return new pion::plugins::SQLiteDatabase(); } /// destroys SQLiteDatabase objects extern "C" PION_PLUGIN_API void pion_destroy_SQLiteDatabase(pion::plugins::SQLiteDatabase *database_ptr) { delete database_ptr; } <|endoftext|>
<commit_before>/* * http://github.com/dusty-nv/jetson-inference */ // #include "gstCamera.h" #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <jetson-inference/cudaMappedMemory.h> #include <jetson-inference/cudaNormalize.h> #include <jetson-inference/cudaFont.h> #include <jetson-inference/detectNet.h> #define DEFAULT_CAMERA -1 // -1 for onboard camera, or change to index of /dev/video V4L2 camera (>=0) using namespace std; bool signal_recieved = false; //void sig_handler(int signo) //{ //if( signo == SIGINT ) //{ //printf("received SIGINT\n"); //signal_recieved = true; //} //} static const std::string OPENCV_WINDOW = "Image window"; class ImageConverter { ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; float confidence = 0.0f; float* bbCPU = NULL; float* bbCUDA = NULL; float* confCPU = NULL; float* confCUDA = NULL; detectNet* net = NULL; uint32_t maxBoxes = 0; uint32_t classes = 0; float4* gpu_data = NULL; uint32_t imgWidth; uint32_t imgHeight; size_t imgSize; public: ImageConverter(int argc, char** argv ) : it_(nh_) { cout << "start constructor" << endl; // Subscrive to input video feed and publish output video feed image_sub_ = it_.subscribe("/left/image_rect_color", 1, &ImageConverter::imageCb, this); cv::namedWindow(OPENCV_WINDOW); cout << "Named a window" << endl; /* * create detectNet */ net = detectNet::Create(argc, argv); cout << "Created DetectNet" << endl; if( !net ) { printf("obj_detect: failed to initialize imageNet\n"); } /* * allocate memory for output bounding boxes and class confidence */ if( !cudaAllocMapped((void**)&bbCPU, (void**)&bbCUDA, maxBoxes * sizeof(float4)) || !cudaAllocMapped((void**)&confCPU, (void**)&confCUDA, maxBoxes * classes * sizeof(float)) ) { printf("detectnet-console: failed to alloc output memory\n"); } cout << "Allocated CUDA mem" << endl; maxBoxes = net->GetMaxBoundingBoxes(); printf("maximum bounding boxes: %u\n", maxBoxes); classes = net->GetNumClasses(); cout << "Constructor operations complete" << endl; } ~ImageConverter() { cv::destroyWindow(OPENCV_WINDOW); } void imageCb(const sensor_msgs::ImageConstPtr& msg) { cv::Mat cv_im; try { cv_im = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8)->image; cv_im.convertTo(cv_im,CV_32FC3); // convert color cv::cvtColor(cv_im,cv_im,CV_BGR2RGBA); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } imgHeight = cv_im.rows; imgWidth = cv_im.cols; imgSize = cv_im.rows*cv_im.cols * sizeof(float4); float4* cpu_data = (float4*)(cv_im.data); // copy to device CUDA(cudaMemcpy(gpu_data, cpu_data, imgSize, cudaMemcpyHostToDevice)); //void* imgCPU = NULL; void* imgCUDA = NULL; // classify image with detectNet int numBoundingBoxes = maxBoxes; if( net->Detect((float*)gpu_data, imgWidth, imgHeight, bbCPU, &numBoundingBoxes, confCPU)) { printf("%i bounding boxes detected\n", numBoundingBoxes); int lastClass = 0; int lastStart = 0; for( int n=0; n < numBoundingBoxes; n++ ) { const int nc = confCPU[n*2+1]; float* bb = bbCPU + (n * 4); printf("bounding box %i (%f, %f) (%f, %f) w=%f h=%f\n", n, bb[0], bb[1], bb[2], bb[3], bb[2] - bb[0], bb[3] - bb[1]); //cv::rectangle(cv_im, Rect rec, Scalar( rand()&255, rand()&255, rand()&255 ),1, LINE_8, 0 ) //if( nc != lastClass || n == (numBoundingBoxes - 1) ) //{ //if( !net->DrawBoxes((float*)gpu_data, (float*)gpu_data, imgWidth, imgHeight, //bbCUDA + (lastStart * 4), (n - lastStart) + 1, lastClass) ) //printf("detectnet-console: failed to draw boxes\n"); //lastClass = nc; //lastStart = n; ////CUDA(cudaDeviceSynchronize()); //} } /*if( font != NULL ) { char str[256]; sprintf(str, "%05.2f%% %s", confidence * 100.0f, net->GetClassDesc(img_class)); font->RenderOverlay((float4*)imgRGBA, (float4*)imgRGBA, camera->GetWidth(), camera->GetHeight(), str, 10, 10, make_float4(255.0f, 255.0f, 255.0f, 255.0f)); }*/ char str[256]; sprintf(str, "TensorRT build %x | %s | %04.1f FPS", NV_GIE_VERSION, net->HasFP16() ? "FP16" : "FP32", -1.0); //sprintf(str, "GIE build %x | %s | %04.1f FPS | %05.2f%% %s", NV_GIE_VERSION, net->GetNetworkName(), display->GetFPS(), confidence * 100.0f, net->GetClassDesc(img_class)); cv::setWindowTitle(OPENCV_WINDOW, str); } // update display // Draw an example circle on the video stream if (cv_im.rows > 60 && cv_im.cols > 60) cv::circle(cv_im, cv::Point(50, 50), 10, CV_RGB(255,0,0)); // Update GUI Window cv::imshow(OPENCV_WINDOW, cv_im); cv::waitKey(3); } }; int main( int argc, char** argv ) { cout << "starting node" << endl; printf("obj_detect\n args (%i): ", argc); ros::init(argc, argv, "obj_detector"); ros::NodeHandle nh; for( int i=0; i < argc; i++ ) printf("%i [%s] ", i, argv[i]); printf("\n\n"); ImageConverter ic(argc, argv); /* * parse network type from CLI arguments */ /*detectNet::NetworkType networkType = detectNet::PEDNET_MULTI; if( argc > 1 ) { if( strcmp(argv[1], "multiped") == 0 || strcmp(argv[1], "pednet") == 0 || strcmp(argv[1], "multiped-500") == 0 ) networkType = detectNet::PEDNET_MULTI; else if( strcmp(argv[1], "ped-100") == 0 ) networkType = detectNet::PEDNET; else if( strcmp(argv[1], "facenet") == 0 || strcmp(argv[1], "facenet-120") == 0 || strcmp(argv[1], "face-120") == 0 ) networkType = detectNet::FACENET; }*/ //if( signal(SIGINT, sig_handler) == SIG_ERR ) //printf("\ncan't catch SIGINT\n"); /* * create the camera device */ //gstCamera* camera = gstCamera::Create(DEFAULT_CAMERA); //if( !camera ) //{ //printf("\ndetectnet-camera: failed to initialize video device\n"); //return 0; //} //printf("\ndetectnet-camera: successfully initialized video device\n"); //printf(" width: %u\n", camera->GetWidth()); //printf(" height: %u\n", camera->GetHeight()); //printf(" depth: %u (bpp)\n\n", camera->GetPixelDepth()); ros::spin(); return 0; } <commit_msg>obj_detector now takes a face trained detectNet model and prints the bounding box coordinates based on the image sent over ROS and processed through the cv_bridge<commit_after>/* * http://github.com/dusty-nv/jetson-inference */ // #include "gstCamera.h" #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <jetson-inference/cudaMappedMemory.h> #include <jetson-inference/cudaNormalize.h> #include <jetson-inference/cudaFont.h> #include <jetson-inference/detectNet.h> #define DEFAULT_CAMERA -1 // -1 for onboard camera, or change to index of /dev/video V4L2 camera (>=0) using namespace std; bool signal_recieved = false; //void sig_handler(int signo) //{ //if( signo == SIGINT ) //{ //printf("received SIGINT\n"); //signal_recieved = true; //} //} static const std::string OPENCV_WINDOW = "Image post bridge conversion"; static const std::string OPENCV_WINDOW2 = "Image post bit depth conversion"; static const std::string OPENCV_WINDOW3 = "Image post color conversion"; static const std::string OPENCV_WINDOW4 = "Image window"; class ImageConverter { ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; cv::Mat cv_im; cv_bridge::CvImagePtr cv_ptr; float confidence = 0.0f; float* bbCPU = NULL; float* bbCUDA = NULL; float* confCPU = NULL; float* confCUDA = NULL; detectNet* net = NULL; uint32_t maxBoxes = 0; uint32_t classes = 0; float4* gpu_data = NULL; uint32_t imgWidth; uint32_t imgHeight; size_t imgSize; public: ImageConverter(int argc, char** argv ) : it_(nh_) { cout << "start constructor" << endl; // Subscrive to input video feed and publish output video feed image_sub_ = it_.subscribe("/left/image_rect_color", 1, &ImageConverter::imageCb, this); cv::namedWindow(OPENCV_WINDOW); cv::namedWindow(OPENCV_WINDOW2); cv::namedWindow(OPENCV_WINDOW3); cv::namedWindow(OPENCV_WINDOW4); cout << "Named a window" << endl; /* * create detectNet */ net = detectNet::Create(argc, argv); cout << "Created DetectNet" << endl; if( !net ) { printf("obj_detect: failed to initialize imageNet\n"); } maxBoxes = net->GetMaxBoundingBoxes(); printf("maximum bounding boxes: %u\n", maxBoxes); classes = net->GetNumClasses(); /* * allocate memory for output bounding boxes and class confidence */ if( !cudaAllocMapped((void**)&bbCPU, (void**)&bbCUDA, maxBoxes * sizeof(float4)) || !cudaAllocMapped((void**)&confCPU, (void**)&confCUDA, maxBoxes * classes * sizeof(float)) ) { printf("detectnet-console: failed to alloc output memory\n"); } cout << "Allocated CUDA mem" << endl; maxBoxes = net->GetMaxBoundingBoxes(); printf("maximum bounding boxes: %u\n", maxBoxes); classes = net->GetNumClasses(); cout << "Constructor operations complete" << endl; } ~ImageConverter() { cv::destroyWindow(OPENCV_WINDOW); } void imageCb(const sensor_msgs::ImageConstPtr& msg) { try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); cv_im = cv_ptr->image; cv::imshow(OPENCV_WINDOW, cv_im); cv_im.convertTo(cv_im,CV_32FC3); //ROS_INFO("Image width %d height %d", cv_im.cols, cv_im.rows); cv::imshow(OPENCV_WINDOW2, cv_im); // convert color cv::cvtColor(cv_im,cv_im,CV_BGR2RGBA); cv::imshow(OPENCV_WINDOW3, cv_im); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // allocate GPU data if necessary if(!gpu_data){ ROS_INFO("first allocation"); CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4))); }else if(imgHeight != cv_im.rows || imgWidth != cv_im.cols){ ROS_INFO("re allocation"); // reallocate for a new image size if necessary CUDA(cudaFree(gpu_data)); CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4))); } //ROS_INFO("allocation done"); imgHeight = cv_im.rows; imgWidth = cv_im.cols; imgSize = cv_im.rows*cv_im.cols * sizeof(float4); float4* cpu_data = (float4*)(cv_im.data); //ROS_INFO("cuda memcpy begin"); // copy to device CUDA(cudaMemcpy(gpu_data, cpu_data, imgSize, cudaMemcpyHostToDevice)); //ROS_INFO("cuda memcpy end"); //void* imgCPU = NULL; void* imgCUDA = NULL; // classify image with detectNet int numBoundingBoxes = maxBoxes; //ROS_INFO("parameters gpu_data: %p imgWidth: %d imgHeight: %d bbCPU: %p numBB pointer: %p numBB: %d",gpu_data, imgWidth, imgHeight,bbCPU, &numBoundingBoxes, numBoundingBoxes); if( net->Detect((float*)gpu_data, imgWidth, imgHeight, bbCPU, &numBoundingBoxes, confCPU)) { printf("%i bounding boxes detected\n", numBoundingBoxes); int lastClass = 0; int lastStart = 0; for( int n=0; n < numBoundingBoxes; n++ ) { const int nc = confCPU[n*2+1]; float* bb = bbCPU + (n * 4); printf("bounding box %i (%f, %f) (%f, %f) w=%f h=%f\n", n, bb[0], bb[1], bb[2], bb[3], bb[2] - bb[0], bb[3] - bb[1]); //cv::rectangle(cv_im, Rect rec, Scalar( rand()&255, rand()&255, rand()&255 ),1, LINE_8, 0 ) //if( nc != lastClass || n == (numBoundingBoxes - 1) ) //{ //if( !net->DrawBoxes((float*)gpu_data, (float*)gpu_data, imgWidth, imgHeight, //bbCUDA + (lastStart * 4), (n - lastStart) + 1, lastClass) ) //printf("detectnet-console: failed to draw boxes\n"); //lastClass = nc; //lastStart = n; ////CUDA(cudaDeviceSynchronize()); //} } /*if( font != NULL ) { char str[256]; sprintf(str, "%05.2f%% %s", confidence * 100.0f, net->GetClassDesc(img_class)); font->RenderOverlay((float4*)imgRGBA, (float4*)imgRGBA, camera->GetWidth(), camera->GetHeight(), str, 10, 10, make_float4(255.0f, 255.0f, 255.0f, 255.0f)); }*/ char str[256]; sprintf(str, "TensorRT build %x | %s | %04.1f FPS", NV_GIE_VERSION, net->HasFP16() ? "FP16" : "FP32", -1.0); //sprintf(str, "GIE build %x | %s | %04.1f FPS | %05.2f%% %s", NV_GIE_VERSION, net->GetNetworkName(), display->GetFPS(), confidence * 100.0f, net->GetClassDesc(img_class)); cv::setWindowTitle(OPENCV_WINDOW, str); } // update image back to original cv_im.convertTo(cv_im,CV_8UC3); cv::cvtColor(cv_im,cv_im,CV_RGBA2BGR); // Draw an example circle on the video stream if (cv_im.rows > 60 && cv_im.cols > 60) cv::circle(cv_im, cv::Point(50, 50), 10, CV_RGB(255,0,0)); // test image cv::String filepath = "/home/ubuntu/Desktop/dog.jpg"; cv::Mat testpic = cv::imread(filepath); // Update GUI Window cv::imshow(OPENCV_WINDOW4, cv_im); //cv::imshow(OPENCV_WINDOW, cv_im); //cv::imshow(OPENCV_WINDOW, testpic); cv::waitKey(3); } }; int main( int argc, char** argv ) { cout << "starting node" << endl; printf("obj_detect\n args (%i): ", argc); ros::init(argc, argv, "obj_detector"); ros::NodeHandle nh; for( int i=0; i < argc; i++ ) printf("%i [%s] ", i, argv[i]); printf("\n\n"); ImageConverter ic(argc, argv); /* * parse network type from CLI arguments */ /*detectNet::NetworkType networkType = detectNet::PEDNET_MULTI; if( argc > 1 ) { if( strcmp(argv[1], "multiped") == 0 || strcmp(argv[1], "pednet") == 0 || strcmp(argv[1], "multiped-500") == 0 ) networkType = detectNet::PEDNET_MULTI; else if( strcmp(argv[1], "ped-100") == 0 ) networkType = detectNet::PEDNET; else if( strcmp(argv[1], "facenet") == 0 || strcmp(argv[1], "facenet-120") == 0 || strcmp(argv[1], "face-120") == 0 ) networkType = detectNet::FACENET; }*/ //if( signal(SIGINT, sig_handler) == SIG_ERR ) //printf("\ncan't catch SIGINT\n"); /* * create the camera device */ //gstCamera* camera = gstCamera::Create(DEFAULT_CAMERA); //if( !camera ) //{ //printf("\ndetectnet-camera: failed to initialize video device\n"); //return 0; //} //printf("\ndetectnet-camera: successfully initialized video device\n"); //printf(" width: %u\n", camera->GetWidth()); //printf(" height: %u\n", camera->GetHeight()); //printf(" depth: %u (bpp)\n\n", camera->GetPixelDepth()); ros::spin(); return 0; } <|endoftext|>
<commit_before>/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ #include <fstream> #include <iostream> #include <boost/filesystem/operations.hpp> #include <boost/program_options.hpp> #include <boost/exception/all.hpp> #include "configuration.hpp" namespace bpo = boost::program_options; namespace AssimpWorker { Configuration* Configuration::singletonInstance = nullptr; const char* Configuration::defaultConfigFilename = "assimpworker.conf"; Configuration& Configuration::getInstance() { if (singletonInstance == nullptr) { singletonInstance = new Configuration(); } return *singletonInstance; } Configuration::Configuration() { setupOptions(); parseConfigFile(); } void Configuration::init(int argc, char **argv) { try { bpo::command_line_parser parser(argc, argv); parser.options(description); bpo::store(parser.run(),parsedVariables); // in case the default file didn't exist // and we now know a non-default name: parseConfigFile(); if (parsedVariables.count("help") || parsedVariables.count("version")) { // if these are defined, skip checks, should exit from main anyway. return; } // now that we have parsed commandline // as well as default and possibly other configfile // check for missing stuff: bpo::notify(parsedVariables); } catch (std::exception const& e) { std::cerr << "Parsing options: " << e.what() << std::endl; exit(1); } } void Configuration::parseConfigFile() { const char* configFileName = nullptr; if (parsedVariables.count("config")) { // config file specified std::string configFile = parsedVariables["config"].as<std::string>(); configFileName = configFile.c_str(); } else if (defaultConfigExists()) { configFileName = defaultConfigFilename; } if (!configFileName){ return; } std::ifstream configFile(configFileName); if (configFile.good()) { bpo::parsed_options parsedConfig = bpo::parse_config_file(configFile,description); bpo::store(parsedConfig, parsedVariables); } // don't notify here, as we may not have parsed commandline yet. } bool Configuration::defaultConfigExists() { return boost::filesystem::exists(defaultConfigFilename); } void Configuration::setupOptions() { bpo::options_description basic("Basic options"); basic.add_options() ("help,h,?", "show this message") ("version,v","show version number") ("config,c", bpo::value<std::string>(), "read configuration from file, overrides options given on command line") ("decompression-path", bpo::value<std::string>()->default_value("./tmp"), "Path to temporary space for decompressed zip contents") ; bpo::options_description import("Import options"); import.add_options() ("mesh-split", "Split meshes larger than a certain number of vertices.") ("mesh-split-threshold", bpo::value<int>()->default_value(65535), "Number of vertices at which to split.") ; bpo::options_description stomp("Stomp options"); stomp.add_options() ("stomp-heartbeat-interval-ms", bpo::value<int>()->default_value(10000), "Heartbeat interval in ms") ("stomp-port", bpo::value<int>() ->default_value(61613), "Server port (STOMP protocol)") ("stomp-host", bpo::value<std::string>()->default_value("localhost"), "Server address") ("stomp-user", bpo::value<std::string>()->required(), "Username") ("stomp-pass", bpo::value<std::string>()->required(), "Password") ("work-queue",bpo::value<std::string>()->default_value("atlas.work.import"),"Work queue name") ("feedback-queue",bpo::value<std::string>()->default_value("atlas.work.feedback"),"Feedback queue name") ; bpo::options_description jcr("Repository options"); jcr.add_options() ("jcr-url", bpo::value<std::string>()->default_value("http://localhost:8080/modeshape-rest/atlas/default/"), "Root URL") ("jcr-user", bpo::value<std::string>()->default_value("admin"), "Username") ("jcr-pass", bpo::value<std::string>()->default_value("admin"), "Password") ; description.add(basic); description.add(import); description.add(stomp); description.add(jcr); } const bpo::variable_value& Configuration::get(const std::string &entry) const { return parsedVariables[entry]; } const bool Configuration::enabled(const std::string& entry) const { return parsedVariables.count(entry); } void Configuration::printDescription() const { std::cout << description << std::endl; } } <commit_msg>indentation changes<commit_after>/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ #include <fstream> #include <iostream> #include <boost/filesystem/operations.hpp> #include <boost/program_options.hpp> #include <boost/exception/all.hpp> #include "configuration.hpp" namespace bpo = boost::program_options; namespace AssimpWorker { Configuration* Configuration::singletonInstance = nullptr; const char* Configuration::defaultConfigFilename = "assimpworker.conf"; Configuration& Configuration::getInstance() { if (singletonInstance == nullptr) { singletonInstance = new Configuration(); } return *singletonInstance; } Configuration::Configuration() { setupOptions(); parseConfigFile(); } void Configuration::init(int argc, char **argv) { try { bpo::command_line_parser parser(argc, argv); parser.options(description); bpo::store(parser.run(),parsedVariables); // in case the default file didn't exist // and we now know a non-default name: parseConfigFile(); if (parsedVariables.count("help") || parsedVariables.count("version")) { // if these are defined, skip checks, should exit from main anyway. return; } // now that we have parsed commandline // as well as default and possibly other configfile // check for missing stuff: bpo::notify(parsedVariables); } catch (std::exception const& e) { std::cerr << "Parsing options: " << e.what() << std::endl; exit(1); } } void Configuration::parseConfigFile() { const char* configFileName = nullptr; if (parsedVariables.count("config")) { // config file specified std::string configFile = parsedVariables["config"].as<std::string>(); configFileName = configFile.c_str(); } else if (defaultConfigExists()) { configFileName = defaultConfigFilename; } if (!configFileName){ return; } std::ifstream configFile(configFileName); if (configFile.good()) { bpo::parsed_options parsedConfig = bpo::parse_config_file(configFile,description); bpo::store(parsedConfig, parsedVariables); } // don't notify here, as we may not have parsed commandline yet. } bool Configuration::defaultConfigExists() { return boost::filesystem::exists(defaultConfigFilename); } void Configuration::setupOptions() { bpo::options_description basic("Basic options"); basic.add_options() ("help,h,?", "show this message") ("version,v","show version number") ("config,c", bpo::value<std::string>(), "read configuration from file, overrides options given on command line") ("decompression-path", bpo::value<std::string>()->default_value("./tmp"), "Path to temporary space for decompressed zip contents") ; bpo::options_description import("Import options"); import.add_options() ("mesh-split", "Split meshes larger than a certain number of vertices.") ("mesh-split-threshold", bpo::value<int>()->default_value(65535), "Number of vertices at which to split.") ; bpo::options_description stomp("Stomp options"); stomp.add_options() ("stomp-heartbeat-interval-ms", bpo::value<int>()->default_value(10000), "Heartbeat interval in ms") ("stomp-port", bpo::value<int>() ->default_value(61613), "Server port (STOMP protocol)") ("stomp-host", bpo::value<std::string>()->default_value("localhost"), "Server address") ("stomp-user", bpo::value<std::string>()->required(), "Username") ("stomp-pass", bpo::value<std::string>()->required(), "Password") ("work-queue",bpo::value<std::string>()->default_value("atlas.work.import"),"Work queue name") ("feedback-queue",bpo::value<std::string>()->default_value("atlas.work.feedback"),"Feedback queue name") ; bpo::options_description jcr("Repository options"); jcr.add_options() ("jcr-url", bpo::value<std::string>()->default_value("http://localhost:8080/modeshape-rest/atlas/default/"), "Root URL") ("jcr-user", bpo::value<std::string>()->default_value("admin"), "Username") ("jcr-pass", bpo::value<std::string>()->default_value("admin"), "Password") ; description.add(basic); description.add(import); description.add(stomp); description.add(jcr); } const bpo::variable_value& Configuration::get(const std::string &entry) const { return parsedVariables[entry]; } const bool Configuration::enabled(const std::string& entry) const { return parsedVariables.count(entry); } void Configuration::printDescription() const { std::cout << description << std::endl; } } <|endoftext|>
<commit_before>// Copyright GHI Electronics, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <TinyCLR.h> #include <Device.h> #define TARGET(a) CONCAT(DEVICE_TARGET, a) const TinyCLR_Api_Manager* apiManager = nullptr; void OnSoftReset(const TinyCLR_Api_Manager* apiManager) { ::apiManager = apiManager; #ifdef INCLUDE_ADC TARGET(_Adc_AddApi)(apiManager); //apiManager->SetDefaultName(apiManager, TinyCLR_Api_Type::AdcController, TARGET(_Adc_GetApi)()->Name); #endif #ifdef INCLUDE_CAN TARGET(_Can_AddApi)(apiManager); //apiManager->SetDefaultName(apiManager, TinyCLR_Api_Type::CanController, TARGET(_Can_GetApi)()->Name); #endif #ifdef INCLUDE_DAC TARGET(_Dac_AddApi)(apiManager); //apiManager->SetDefaultName(apiManager, TinyCLR_Api_Type::DacController, TARGET(_Dac_GetApi)()->Name); #endif #ifdef INCLUDE_DISPLAY TARGET(_Display_AddApi)(apiManager); //apiManager->SetDefaultName(apiManager, TinyCLR_Api_Type::DisplayController, TARGET(_Display_GetApi)()->Name); #endif #ifdef INCLUDE_GPIO TARGET(_Gpio_AddApi)(apiManager); //apiManager->SetDefaultName(apiManager, TinyCLR_Api_Type::GpioController, TARGET(_Gpio_GetApi)()->Name); #endif #ifdef INCLUDE_I2C TARGET(_I2c_AddApi)(apiManager); #endif #ifdef INCLUDE_PWM TARGET(_Pwm_AddApi)(apiManager); #endif #ifdef INCLUDE_RTC TARGET(_Rtc_AddApi)(apiManager); //apiManager->SetDefaultName(apiManager, TinyCLR_Api_Type::RtcController, TARGET(_Rtc_GetApi)()->Name); #endif #ifdef INCLUDE_SD TARGET(_SdCard_AddApi)(apiManager); //apiManager->SetDefaultName(apiManager, TinyCLR_Api_Type::StorageController, TARGET(_SdCard_GetApi)()->Name); #endif #ifdef INCLUDE_SPI TARGET(_Spi_AddApi)(apiManager); #endif #ifdef INCLUDE_UART TARGET(_Uart_AddApi)(apiManager); #endif #ifdef INCLUDE_USBCLIENT TARGET(_UsbDevice_AddApi)(apiManager); #endif auto interopManager = reinterpret_cast<const TinyCLR_Interop_Manager*>(apiManager->FindDefault(apiManager, TinyCLR_Api_Type::InteropManager)); TARGET(_Startup_OnSoftReset)(apiManager, interopManager); TARGET(_Startup_OnSoftResetDevice)(apiManager, interopManager); } int main() { apiManager = nullptr; TARGET(_Startup_Initialize)(); uint8_t* heapStart; size_t heapLength; TARGET(_Startup_GetHeap)(heapStart, heapLength); TinyCLR_Startup_AddHeapRegion(heapStart, heapLength); const TinyCLR_Api_Info *debuggerApi, *deploymentApi; const void* debuggerConfiguration; const TinyCLR_Startup_DeploymentConfiguration* deploymentConfiguration; TARGET(_Startup_GetDebuggerTransportApi)(debuggerApi, debuggerConfiguration); TinyCLR_Startup_SetDebuggerTransportApi(debuggerApi, debuggerConfiguration); TARGET(_Startup_GetDeploymentApi)(deploymentApi, deploymentConfiguration); TinyCLR_Startup_SetDeploymentApi(deploymentApi, deploymentConfiguration); TinyCLR_Startup_SetDeviceInformation(DEVICE_NAME, DEVICE_MANUFACTURER, DEVICE_VERSION); TinyCLR_Startup_SetRequiredApis(TARGET(_Interrupt_GetRequiredApi)(), TARGET(_Power_GetRequiredApi)(), TARGET(_Time_GetRequiredApi())); auto runApp = true; TARGET(_Startup_GetRunApp)(runApp); TinyCLR_Startup_Start(&OnSoftReset, runApp); return 0; } <commit_msg>Remove unused comments<commit_after>// Copyright GHI Electronics, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <TinyCLR.h> #include <Device.h> #define TARGET(a) CONCAT(DEVICE_TARGET, a) const TinyCLR_Api_Manager* apiManager = nullptr; void OnSoftReset(const TinyCLR_Api_Manager* apiManager) { ::apiManager = apiManager; #ifdef INCLUDE_ADC TARGET(_Adc_AddApi)(apiManager); #endif #ifdef INCLUDE_CAN TARGET(_Can_AddApi)(apiManager); #endif #ifdef INCLUDE_DAC TARGET(_Dac_AddApi)(apiManager); #endif #ifdef INCLUDE_DISPLAY TARGET(_Display_AddApi)(apiManager); #endif #ifdef INCLUDE_GPIO TARGET(_Gpio_AddApi)(apiManager); #endif #ifdef INCLUDE_I2C TARGET(_I2c_AddApi)(apiManager); #endif #ifdef INCLUDE_PWM TARGET(_Pwm_AddApi)(apiManager); #endif #ifdef INCLUDE_RTC TARGET(_Rtc_AddApi)(apiManager); #endif #ifdef INCLUDE_SD TARGET(_SdCard_AddApi)(apiManager); #endif #ifdef INCLUDE_SPI TARGET(_Spi_AddApi)(apiManager); #endif #ifdef INCLUDE_UART TARGET(_Uart_AddApi)(apiManager); #endif #ifdef INCLUDE_USBCLIENT TARGET(_UsbDevice_AddApi)(apiManager); #endif auto interopManager = reinterpret_cast<const TinyCLR_Interop_Manager*>(apiManager->FindDefault(apiManager, TinyCLR_Api_Type::InteropManager)); TARGET(_Startup_OnSoftReset)(apiManager, interopManager); TARGET(_Startup_OnSoftResetDevice)(apiManager, interopManager); } int main() { apiManager = nullptr; TARGET(_Startup_Initialize)(); uint8_t* heapStart; size_t heapLength; TARGET(_Startup_GetHeap)(heapStart, heapLength); TinyCLR_Startup_AddHeapRegion(heapStart, heapLength); const TinyCLR_Api_Info *debuggerApi, *deploymentApi; const void* debuggerConfiguration; const TinyCLR_Startup_DeploymentConfiguration* deploymentConfiguration; TARGET(_Startup_GetDebuggerTransportApi)(debuggerApi, debuggerConfiguration); TinyCLR_Startup_SetDebuggerTransportApi(debuggerApi, debuggerConfiguration); TARGET(_Startup_GetDeploymentApi)(deploymentApi, deploymentConfiguration); TinyCLR_Startup_SetDeploymentApi(deploymentApi, deploymentConfiguration); TinyCLR_Startup_SetDeviceInformation(DEVICE_NAME, DEVICE_MANUFACTURER, DEVICE_VERSION); TinyCLR_Startup_SetRequiredApis(TARGET(_Interrupt_GetRequiredApi)(), TARGET(_Power_GetRequiredApi)(), TARGET(_Time_GetRequiredApi())); auto runApp = true; TARGET(_Startup_GetRunApp)(runApp); TinyCLR_Startup_Start(&OnSoftReset, runApp); return 0; } <|endoftext|>
<commit_before>#include "IEntryEnumerator.h" #include <string> #include <cstring> #ifdef FS_OS_Linux #include <glob.h> #include <sys/stat.h> #elif defined FS_OS_Windows #include <windows.h> #else #endif #include <iostream> using namespace std; using namespace FS; // * 2006-08-30 YRD - Portability note : using namespace FS confuses // windows platform SDK because it defines itself // a 'boolean' type. Thus the following define to // force the use of FS::boolean ! #define boolean FS::boolean // ________________________________________________________________________________________________________________ // namespace FS { class CEntry : public IEntryEnumerator::IEntry { public: CEntry(const string& sName); virtual const char* getName(void); public: string m_sName; }; }; // ________________________________________________________________________________________________________________ // IEntryEnumerator::IEntry::~IEntry(void) { } CEntry::CEntry(const string& sName) :m_sName(sName) { } const char* CEntry::getName(void) { return m_sName.c_str(); } // ________________________________________________________________________________________________________________ // namespace FS { class CAttributes : public IEntryEnumerator::IAttributes { public: CAttributes(void); virtual ~CAttributes(void); virtual boolean isFile(void); virtual boolean isDirectory(void); virtual boolean isSymbolicLink(void); virtual boolean isArchive(void); virtual boolean isReadOnly(void); virtual boolean isHidden(void); virtual boolean isSystem(void); virtual boolean isExecutable(void); virtual uint64 getSize(void); public: boolean m_bIsFile; boolean m_bIsDirectory; boolean m_bIsSymbolicLink; boolean m_bIsArchive; boolean m_bIsReadOnly; boolean m_bIsHidden; boolean m_bIsSystem; boolean m_bIsExecutable; uint64 m_ui64Size; }; }; // ________________________________________________________________________________________________________________ // IEntryEnumerator::IAttributes::~IAttributes(void) { } CAttributes::CAttributes(void) :m_bIsFile(false) ,m_bIsDirectory(false) ,m_bIsSymbolicLink(false) ,m_bIsArchive(false) ,m_bIsReadOnly(false) ,m_bIsHidden(false) ,m_bIsSystem(false) ,m_bIsExecutable(false) ,m_ui64Size(0) { } CAttributes::~CAttributes(void) { } // ________________________________________________________________________________________________________________ // boolean CAttributes::isFile(void) { return m_bIsFile; } boolean CAttributes::isDirectory(void) { return m_bIsDirectory; } boolean CAttributes::isSymbolicLink(void) { return m_bIsSymbolicLink; } boolean CAttributes::isArchive(void) { return m_bIsArchive; } boolean CAttributes::isReadOnly(void) { return m_bIsReadOnly; } boolean CAttributes::isHidden(void) { return m_bIsHidden; } boolean CAttributes::isSystem(void) { return m_bIsSystem; } boolean CAttributes::isExecutable(void) { return m_bIsExecutable; } // ________________________________________________________________________________________________________________ // uint64 CAttributes::getSize(void) { return m_ui64Size; } // ________________________________________________________________________________________________________________ // IEntryEnumerator::~IEntryEnumerator(void) { } // ________________________________________________________________________________________________________________ // namespace FS { class CEntryEnumerator : public IEntryEnumerator { public: CEntryEnumerator(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack); virtual void release(void); protected: IEntryEnumeratorCallBack& m_rEntryEnumeratorCallBack; }; }; // ________________________________________________________________________________________________________________ // CEntryEnumerator::CEntryEnumerator(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) :m_rEntryEnumeratorCallBack(rEntryEnumeratorCallBack) { } void CEntryEnumerator::release(void) { delete this; } // ________________________________________________________________________________________________________________ // #ifdef FS_OS_Linux namespace FS { class CEntryEnumeratorLinux : public CEntryEnumerator { public: CEntryEnumeratorLinux(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack); virtual boolean enumerate(const char* sWildCard); }; }; #elif defined FS_OS_Windows namespace FS { class CEntryEnumeratorWindows : public CEntryEnumerator { public: CEntryEnumeratorWindows(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack); virtual boolean enumerate(const char* sWildCard); }; }; #else namespace FS { class CEntryEnumeratorDummy : public CEntryEnumerator { public: CEntryEnumeratorDummy(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack); virtual boolean enumerate(const char* sWildCard); }; }; #endif // ________________________________________________________________________________________________________________ // #ifdef FS_OS_Linux CEntryEnumeratorLinux::CEntryEnumeratorLinux(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) :CEntryEnumerator(rEntryEnumeratorCallBack) { } boolean CEntryEnumeratorLinux::enumerate(const char* sWildCard) { glob_t l_oGlobStruc; memset(&l_oGlobStruc, GLOB_NOSORT, sizeof(l_oGlobStruc)); if(glob(sWildCard, 0, NULL, &l_oGlobStruc)) { return false; } size_t i=0; boolean l_bFinished=false; while(!l_bFinished) { if(i<l_oGlobStruc.gl_pathc) { char* l_sName=l_oGlobStruc.gl_pathv[i]; CEntry l_oEntry(l_sName); CAttributes l_oAttributes; struct stat l_oLStat; struct stat l_oStat; if(!lstat(l_sName, &l_oLStat) && !stat(l_sName, &l_oStat)) { l_oAttributes.m_bIsDirectory=S_ISDIR(l_oStat.st_mode)?true:false; l_oAttributes.m_bIsFile=S_ISREG(l_oStat.st_mode)?true:false; l_oAttributes.m_bIsSymbolicLink=S_ISLNK(l_oLStat.st_mode)?true:false; l_oAttributes.m_bIsArchive=false; l_oAttributes.m_bIsReadOnly=l_oStat.st_mode&S_IWUSR?false:true; l_oAttributes.m_bIsHidden=false; l_oAttributes.m_bIsSystem=S_ISBLK(l_oStat.st_mode)|S_ISFIFO(l_oStat.st_mode)|S_ISSOCK(l_oStat.st_mode)|S_ISCHR(l_oStat.st_mode)?true:false; l_oAttributes.m_bIsExecutable=l_oStat.st_mode&S_IXUSR?true:false; l_oAttributes.m_ui64Size=l_oStat.st_size; // Sends to callback if(!m_rEntryEnumeratorCallBack.callback(l_oEntry, l_oAttributes)) { l_bFinished=true; } } i++; } else { l_bFinished=true; } } return true; } #elif defined FS_OS_Windows CEntryEnumeratorWindows::CEntryEnumeratorWindows(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) :CEntryEnumerator(rEntryEnumeratorCallBack) { } boolean CEntryEnumeratorWindows::enumerate(const char* sWildCard) { // $$$ TODO // $$$ Find better method to enumerate files // $$$ under windows including their initial path // $$$ (cFileName member of WIN32_FIND_DATA structure // $$$ loses the initial path !!) // $$$ TODO char l_sExtendedWildCard[1024]; char* l_sExtendedWildCardFileName; int a=GetFullPathName(sWildCard, sizeof(l_sExtendedWildCard), l_sExtendedWildCard, &l_sExtendedWildCardFileName); std::string l_sPath(sWildCard, strlen(sWildCard)-(l_sExtendedWildCardFileName?strlen(l_sExtendedWildCardFileName):0)); WIN32_FIND_DATA l_oFindData; HANDLE l_pFileHandle=FindFirstFile(sWildCard, &l_oFindData); if(l_pFileHandle!=INVALID_HANDLE_VALUE) { boolean l_bFinished=false; while(!l_bFinished) { CEntry l_oEntry(std::string(l_sPath+l_oFindData.cFileName).c_str()); CAttributes l_oAttributes; l_oAttributes.m_bIsDirectory=(l_oFindData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)?true:false; l_oAttributes.m_bIsFile=(l_oFindData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)?false:true; l_oAttributes.m_bIsSymbolicLink=false; l_oAttributes.m_bIsArchive=(l_oFindData.dwFileAttributes&FILE_ATTRIBUTE_ARCHIVE)?true:false; l_oAttributes.m_bIsReadOnly=(l_oFindData.dwFileAttributes&FILE_ATTRIBUTE_READONLY)?true:false; l_oAttributes.m_bIsHidden=(l_oFindData.dwFileAttributes&FILE_ATTRIBUTE_HIDDEN)?true:false; l_oAttributes.m_bIsSystem=(l_oFindData.dwFileAttributes&FILE_ATTRIBUTE_SYSTEM)?true:false; l_oAttributes.m_bIsExecutable=false; // TODO l_oAttributes.m_ui64Size=(l_oFindData.nFileSizeHigh<<16)+l_oFindData.nFileSizeLow; // Sends to callback if(!m_rEntryEnumeratorCallBack.callback(l_oEntry, l_oAttributes)) { l_bFinished=true; } if(!FindNextFile(l_pFileHandle, &l_oFindData)) { l_bFinished=true; } } } return true; } #else CEntryEnumeratorDummy::CEntryEnumeratorDummy(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) :CEntryEnumerator(rEntryEnumeratorCallBack) { } boolean CEntryEnumeratorDummy::enumerate(const char* sWildCard) { return true; } #endif FS_API IEntryEnumerator* FS::createEntryEnumerator(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) { IEntryEnumerator* l_pResult=NULL; #ifdef FS_OS_Linux l_pResult=new CEntryEnumeratorLinux(rEntryEnumeratorCallBack); #elif defined FS_OS_Windows l_pResult=new CEntryEnumeratorWindows(rEntryEnumeratorCallBack); #else l_pResult=new CEntryEnumeratorDummy(rEntryEnumeratorCallBack); #endif return l_pResult; } <commit_msg><commit_after>#include "IEntryEnumerator.h" #include <string> #include <cstring> #ifdef FS_OS_Linux #include <glob.h> #include <sys/stat.h> #elif defined FS_OS_Windows #include <windows.h> #else #endif #include <iostream> using namespace std; using namespace FS; // * 2006-08-30 YRD - Portability note : using namespace FS confuses // windows platform SDK because it defines itself // a 'boolean' type. Thus the following define to // force the use of FS::boolean ! #define boolean FS::boolean // ________________________________________________________________________________________________________________ // namespace FS { class CEntry : public IEntryEnumerator::IEntry { public: CEntry(const string& sName); virtual const char* getName(void); public: string m_sName; }; }; // ________________________________________________________________________________________________________________ // IEntryEnumerator::IEntry::~IEntry(void) { } CEntry::CEntry(const string& sName) :m_sName(sName) { } const char* CEntry::getName(void) { return m_sName.c_str(); } // ________________________________________________________________________________________________________________ // namespace FS { class CAttributes : public IEntryEnumerator::IAttributes { public: CAttributes(void); virtual ~CAttributes(void); virtual boolean isFile(void); virtual boolean isDirectory(void); virtual boolean isSymbolicLink(void); virtual boolean isArchive(void); virtual boolean isReadOnly(void); virtual boolean isHidden(void); virtual boolean isSystem(void); virtual boolean isExecutable(void); virtual uint64 getSize(void); public: boolean m_bIsFile; boolean m_bIsDirectory; boolean m_bIsSymbolicLink; boolean m_bIsArchive; boolean m_bIsReadOnly; boolean m_bIsHidden; boolean m_bIsSystem; boolean m_bIsExecutable; uint64 m_ui64Size; }; }; // ________________________________________________________________________________________________________________ // IEntryEnumerator::IAttributes::~IAttributes(void) { } CAttributes::CAttributes(void) :m_bIsFile(false) ,m_bIsDirectory(false) ,m_bIsSymbolicLink(false) ,m_bIsArchive(false) ,m_bIsReadOnly(false) ,m_bIsHidden(false) ,m_bIsSystem(false) ,m_bIsExecutable(false) ,m_ui64Size(0) { } CAttributes::~CAttributes(void) { } // ________________________________________________________________________________________________________________ // boolean CAttributes::isFile(void) { return m_bIsFile; } boolean CAttributes::isDirectory(void) { return m_bIsDirectory; } boolean CAttributes::isSymbolicLink(void) { return m_bIsSymbolicLink; } boolean CAttributes::isArchive(void) { return m_bIsArchive; } boolean CAttributes::isReadOnly(void) { return m_bIsReadOnly; } boolean CAttributes::isHidden(void) { return m_bIsHidden; } boolean CAttributes::isSystem(void) { return m_bIsSystem; } boolean CAttributes::isExecutable(void) { return m_bIsExecutable; } // ________________________________________________________________________________________________________________ // uint64 CAttributes::getSize(void) { return m_ui64Size; } // ________________________________________________________________________________________________________________ // IEntryEnumerator::~IEntryEnumerator(void) { } // ________________________________________________________________________________________________________________ // namespace FS { class CEntryEnumerator : public IEntryEnumerator { public: CEntryEnumerator(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack); virtual void release(void); protected: IEntryEnumeratorCallBack& m_rEntryEnumeratorCallBack; }; }; // ________________________________________________________________________________________________________________ // CEntryEnumerator::CEntryEnumerator(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) :m_rEntryEnumeratorCallBack(rEntryEnumeratorCallBack) { } void CEntryEnumerator::release(void) { delete this; } // ________________________________________________________________________________________________________________ // #ifdef FS_OS_Linux namespace FS { class CEntryEnumeratorLinux : public CEntryEnumerator { public: CEntryEnumeratorLinux(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack); virtual boolean enumerate(const char* sWildCard); }; }; #elif defined FS_OS_Windows namespace FS { class CEntryEnumeratorWindows : public CEntryEnumerator { public: CEntryEnumeratorWindows(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack); virtual boolean enumerate(const char* sWildCard); }; }; #else namespace FS { class CEntryEnumeratorDummy : public CEntryEnumerator { public: CEntryEnumeratorDummy(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack); virtual boolean enumerate(const char* sWildCard); }; }; #endif // ________________________________________________________________________________________________________________ // #ifdef FS_OS_Linux CEntryEnumeratorLinux::CEntryEnumeratorLinux(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) :CEntryEnumerator(rEntryEnumeratorCallBack) { } boolean CEntryEnumeratorLinux::enumerate(const char* sWildCard) { if(!sWildCard) { return false; } glob_t l_oGlobStruc; memset(&l_oGlobStruc, GLOB_NOSORT, sizeof(l_oGlobStruc)); if(glob(sWildCard, 0, NULL, &l_oGlobStruc)) { return false; } size_t i=0; boolean l_bFinished=false; while(!l_bFinished) { if(i<l_oGlobStruc.gl_pathc) { char* l_sName=l_oGlobStruc.gl_pathv[i]; CEntry l_oEntry(l_sName); CAttributes l_oAttributes; struct stat l_oLStat; struct stat l_oStat; if(!lstat(l_sName, &l_oLStat) && !stat(l_sName, &l_oStat)) { l_oAttributes.m_bIsDirectory=S_ISDIR(l_oStat.st_mode)?true:false; l_oAttributes.m_bIsFile=S_ISREG(l_oStat.st_mode)?true:false; l_oAttributes.m_bIsSymbolicLink=S_ISLNK(l_oLStat.st_mode)?true:false; l_oAttributes.m_bIsArchive=false; l_oAttributes.m_bIsReadOnly=l_oStat.st_mode&S_IWUSR?false:true; l_oAttributes.m_bIsHidden=false; l_oAttributes.m_bIsSystem=S_ISBLK(l_oStat.st_mode)|S_ISFIFO(l_oStat.st_mode)|S_ISSOCK(l_oStat.st_mode)|S_ISCHR(l_oStat.st_mode)?true:false; l_oAttributes.m_bIsExecutable=l_oStat.st_mode&S_IXUSR?true:false; l_oAttributes.m_ui64Size=l_oStat.st_size; // Sends to callback if(!m_rEntryEnumeratorCallBack.callback(l_oEntry, l_oAttributes)) { l_bFinished=true; } } i++; } else { l_bFinished=true; } } return true; } #elif defined FS_OS_Windows CEntryEnumeratorWindows::CEntryEnumeratorWindows(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) :CEntryEnumerator(rEntryEnumeratorCallBack) { } boolean CEntryEnumeratorWindows::enumerate(const char* sWildCard) { if(!sWildCard) { return false; } // $$$ TODO // $$$ Find better method to enumerate files // $$$ under windows including their initial path // $$$ (cFileName member of WIN32_FIND_DATA structure // $$$ loses the initial path !!) // $$$ TODO char l_sExtendedWildCard[1024]; char* l_sExtendedWildCardFileName; int a=GetFullPathName(sWildCard, sizeof(l_sExtendedWildCard), l_sExtendedWildCard, &l_sExtendedWildCardFileName); std::string l_sPath(sWildCard, strlen(sWildCard)-(l_sExtendedWildCardFileName?strlen(l_sExtendedWildCardFileName):0)); WIN32_FIND_DATA l_oFindData; HANDLE l_pFileHandle=FindFirstFile(sWildCard, &l_oFindData); if(l_pFileHandle!=INVALID_HANDLE_VALUE) { boolean l_bFinished=false; while(!l_bFinished) { CEntry l_oEntry(std::string(l_sPath+l_oFindData.cFileName).c_str()); CAttributes l_oAttributes; l_oAttributes.m_bIsDirectory=(l_oFindData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)?true:false; l_oAttributes.m_bIsFile=(l_oFindData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)?false:true; l_oAttributes.m_bIsSymbolicLink=false; l_oAttributes.m_bIsArchive=(l_oFindData.dwFileAttributes&FILE_ATTRIBUTE_ARCHIVE)?true:false; l_oAttributes.m_bIsReadOnly=(l_oFindData.dwFileAttributes&FILE_ATTRIBUTE_READONLY)?true:false; l_oAttributes.m_bIsHidden=(l_oFindData.dwFileAttributes&FILE_ATTRIBUTE_HIDDEN)?true:false; l_oAttributes.m_bIsSystem=(l_oFindData.dwFileAttributes&FILE_ATTRIBUTE_SYSTEM)?true:false; l_oAttributes.m_bIsExecutable=false; // TODO l_oAttributes.m_ui64Size=(l_oFindData.nFileSizeHigh<<16)+l_oFindData.nFileSizeLow; // Sends to callback if(!m_rEntryEnumeratorCallBack.callback(l_oEntry, l_oAttributes)) { l_bFinished=true; } if(!FindNextFile(l_pFileHandle, &l_oFindData)) { l_bFinished=true; } } } return true; } #else CEntryEnumeratorDummy::CEntryEnumeratorDummy(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) :CEntryEnumerator(rEntryEnumeratorCallBack) { } boolean CEntryEnumeratorDummy::enumerate(const char* sWildCard) { if(!sWildCard) { return false; } return true; } #endif FS_API IEntryEnumerator* FS::createEntryEnumerator(IEntryEnumeratorCallBack& rEntryEnumeratorCallBack) { IEntryEnumerator* l_pResult=NULL; #ifdef FS_OS_Linux l_pResult=new CEntryEnumeratorLinux(rEntryEnumeratorCallBack); #elif defined FS_OS_Windows l_pResult=new CEntryEnumeratorWindows(rEntryEnumeratorCallBack); #else l_pResult=new CEntryEnumeratorDummy(rEntryEnumeratorCallBack); #endif return l_pResult; } <|endoftext|>
<commit_before>/** \file json_grep.cc * \brief A simple tool for performing single lookups in a JSON file. * \author Dr. Johannes Ruscheinski * * \copyright (C) 2017,2018,2020 Library of the University of Tübingen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <cstdlib> #include "FileUtil.h" #include "JSON.h" #include "util.h" [[noreturn]] void Usage() { ::Usage("[--print] json_input_file [lookup_path [default]]"); } int Main(int /*argc*/, char *argv[]) { ++argv; if (*argv == nullptr) Usage(); bool print(false); if (std::strcmp(*argv, "--print") == 0) { print = true; ++argv; } if (*argv == nullptr) Usage(); const std::string json_input_filename(*argv); ++argv; std::string lookup_path; if (*argv != nullptr) { lookup_path = *argv; ++argv; } std::string default_value; if (*argv != nullptr) { default_value = *argv; ++argv; } try { std::string json_document; if (not FileUtil::ReadString(json_input_filename, &json_document)) logger->error("could not read \"" + json_input_filename + "\"!"); JSON::Parser parser(json_document); std::shared_ptr<JSON::JSONNode> tree; if (not parser.parse(&tree)) { std::cerr << ::progname << ": " << parser.getErrorMessage() << '\n'; return EXIT_FAILURE; } if (print) std::cout << tree->toString() << '\n'; if (not lookup_path.empty()) std::cerr << lookup_path << ": " << (default_value.empty() ? JSON::LookupString(lookup_path, tree) : JSON::LookupString(lookup_path, tree), default_value) << '\n'; } catch (const std::exception &x) { logger->error("caught exception: " + std::string(x.what())); } return EXIT_SUCCESS; } <commit_msg>Obvious fix.<commit_after>/** \file json_grep.cc * \brief A simple tool for performing single lookups in a JSON file. * \author Dr. Johannes Ruscheinski * * \copyright (C) 2017,2018,2020 Library of the University of Tübingen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <cstdlib> #include "FileUtil.h" #include "JSON.h" #include "util.h" [[noreturn]] void Usage() { ::Usage("[--print] json_input_file [lookup_path [default]]"); } int Main(int /*argc*/, char *argv[]) { ++argv; if (*argv == nullptr) Usage(); bool print(false); if (std::strcmp(*argv, "--print") == 0) { print = true; ++argv; } if (*argv == nullptr) Usage(); const std::string json_input_filename(*argv); ++argv; std::string lookup_path; if (*argv != nullptr) { lookup_path = *argv; ++argv; } std::string default_value; if (*argv != nullptr) { default_value = *argv; ++argv; } std::string json_document; if (not FileUtil::ReadString(json_input_filename, &json_document)) LOG_ERROR("could not read \"" + json_input_filename + "\"!"); JSON::Parser parser(json_document); std::shared_ptr<JSON::JSONNode> tree; if (not parser.parse(&tree)) { std::cerr << ::progname << ": " << parser.getErrorMessage() << '\n'; return EXIT_FAILURE; } if (print) std::cout << tree->toString() << '\n'; if (not lookup_path.empty()) std::cerr << lookup_path << ": " << (default_value.empty() ? JSON::LookupString(lookup_path, tree) : JSON::LookupString(lookup_path, tree, default_value)) << '\n'; else std::cerr << "lookup_path is empty!!!\n"; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#ifndef UTENSOR_MATRIX_OPS #define UTENSOR_MATRIX_OPS #include <limits> //Useful links //http://www.plantation-productions.com/Webster/www.artofasm.com/Linux/HTML/Arraysa2.html //Assume Tensor index order: rows, columns | the first 2 dimensions typedef Tensor<unsigned char> Mat void printMat(Mat mat) { const uint32_t ROWS = mat.getShape()[0]; const uint32_t COLS = mat.getShape()[1]; unsigned char* pData = mat.getPointer({}); for(int i_r = 0; i_r < ROWS; i_r++) { for(int i_c = 0; i_c < COLS; i_c++) { printf("%f ", pData[i_r * COLS + i_c]); } printf("\r\n"); } } void initMatConst(Mat mat, unsigned char value) { const uint32_t ROWS = mat.getShape()[0]; const uint32_t COLS = mat.getShape()[1]; unsigned char* pData = mat.getPointer({}); for(int i_r = 0; i_r < ROWS; i_r++) { for(int i_c = 0; i_c < COLS; i_c++) { pData[i_r * COLS + i_c] = value; } } } void multMat(Mat A, Mat B, Mat C) { const uint32_t A_ROWS = A.getShape()[0]; const uint32_t A_COLS = A.getShape()[1]; const uint32_t B_ROWS = B.getShape()[0]; const uint32_t B_COLS = B.getShape()[1]; const uint32_t C_ROWS = C.getShape()[0]; const uint32_t C_COLS = C.getShape()[1]; unsigned char* A_Data = A.getPointer({}); unsigned char* B_Data = B.getPointer({}); unsigned char* C_Data = C.getPointer({}); if(A_COLS != B_ROWS) { printf("A and B matrices dimension mismatch\r\n"); return; } if(C_ROWS != A_ROWS || C_COLS != B_COLS) { printf("output matrix dimension mismatch\r\n"); return; } for(int r = 0; r < A_ROWS; r++) { for(int c = 0; c < B_COLS; c++) { uint32_t acc = 0; for(int i = 0; i < B_ROWS; i++) { acc += A_Data[i + r * A_COLS] * B_Data[c + i * B_ROWS]; } C_Data[c + r * C_ROWS] = acc; } } } //tensorflow/tensorflow/core/kernels/reference_gemm.h // This is an unoptimized but debuggable implementation of the GEMM matrix // multiply function, used to compare to faster but more opaque versions, or // for bit depths or argument combinations that aren't supported by optimized // code. // It assumes the row-major convention used by TensorFlow, and implements // C = A * B, like the standard BLAS GEMM interface. If the transpose flags are // true, then the relevant matrix is treated as stored in column-major order. template <class T1, class T2, class T3> void ReferenceGemm(bool transpose_a, bool transpose_b, bool transpose_c, size_t m, size_t n, size_t k, const T1* a, int32 offset_a, size_t lda, const T2* b, int32 offset_b, size_t ldb, T3* c, int32 shift_c, int32 offset_c, int32 mult_c, size_t ldc) { int a_i_stride; int a_l_stride; if (transpose_a) { a_i_stride = 1; a_l_stride = lda; } else { a_i_stride = lda; a_l_stride = 1; } int b_j_stride; int b_l_stride; if (transpose_b) { b_j_stride = ldb; b_l_stride = 1; } else { b_j_stride = 1; b_l_stride = ldb; } int c_i_stride; int c_j_stride; if (transpose_c) { c_i_stride = 1; c_j_stride = ldc; } else { c_i_stride = ldc; c_j_stride = 1; } // const int32 highest = static_cast<int32>(Eigen::NumTraits<T3>::highest()); // const int32 lowest = static_cast<int32>(Eigen::NumTraits<T3>::lowest()); const int32 highest = static_cast<int32>(std::numeric_limits<T3>::max()); const int32 lowest = static_cast<int32>(std::numeric_limits<T3>::min()); const int32 rounding = (shift_c < 1) ? 0 : (1 << (shift_c - 1)); int i, j, l; for (j = 0; j < n; j++) { for (i = 0; i < m; i++) { int32 total = 0; for (l = 0; l < k; l++) { const size_t a_index = ((i * a_i_stride) + (l * a_l_stride)); const int32 a_value = static_cast<int32>(a[a_index]) - offset_a; const size_t b_index = ((j * b_j_stride) + (l * b_l_stride)); const int32 b_value = static_cast<int32>(b[b_index]) - offset_b; total += (a_value * b_value); } const size_t c_index = ((i * c_i_stride) + (j * c_j_stride)); int32_t output = ((((total + offset_c) * mult_c) + rounding) >> shift_c); if (output > highest) { output = highest; } if (output < lowest) { output = lowest; } c[c_index] = static_cast<T3>(output); } } } #endif <commit_msg> optimize gemm operation<commit_after>#ifndef UTENSOR_MATRIX_OPS #define UTENSOR_MATRIX_OPS #include <limits> //Useful links //http://www.plantation-productions.com/Webster/www.artofasm.com/Linux/HTML/Arraysa2.html //Assume Tensor index order: rows, columns | the first 2 dimensions typedef Tensor<unsigned char> Mat void printMat(Mat mat) { const uint32_t ROWS = mat.getShape()[0]; const uint32_t COLS = mat.getShape()[1]; unsigned char* pData = mat.getPointer({}); for(int i_r = 0; i_r < ROWS; i_r++) { for(int i_c = 0; i_c < COLS; i_c++) { printf("%f ", pData[i_r * COLS + i_c]); } printf("\r\n"); } } void initMatConst(Mat mat, unsigned char value) { const uint32_t ROWS = mat.getShape()[0]; const uint32_t COLS = mat.getShape()[1]; unsigned char* pData = mat.getPointer({}); for(int i_r = 0; i_r < ROWS; i_r++) { for(int i_c = 0; i_c < COLS; i_c++) { pData[i_r * COLS + i_c] = value; } } } void multMat(Mat A, Mat B, Mat C) { const uint32_t A_ROWS = A.getShape()[0]; const uint32_t A_COLS = A.getShape()[1]; const uint32_t B_ROWS = B.getShape()[0]; const uint32_t B_COLS = B.getShape()[1]; const uint32_t C_ROWS = C.getShape()[0]; const uint32_t C_COLS = C.getShape()[1]; unsigned char* A_Data = A.getPointer({}); unsigned char* B_Data = B.getPointer({}); unsigned char* C_Data = C.getPointer({}); if(A_COLS != B_ROWS) { printf("A and B matrices dimension mismatch\r\n"); return; } if(C_ROWS != A_ROWS || C_COLS != B_COLS) { printf("output matrix dimension mismatch\r\n"); return; } for(int r = 0; r < A_ROWS; r++) { for(int c = 0; c < B_COLS; c++) { uint32_t acc = 0; for(int i = 0; i < B_ROWS; i++) { acc += A_Data[i + r * A_COLS] * B_Data[c + i * B_ROWS]; } C_Data[c + r * C_ROWS] = acc; } } } //tensorflow/tensorflow/core/kernels/reference_gemm.h // This is an unoptimized but debuggable implementation of the GEMM matrix // multiply function, used to compare to faster but more opaque versions, or // for bit depths or argument combinations that aren't supported by optimized // code. // It assumes the row-major convention used by TensorFlow, and implements // C = A * B, like the standard BLAS GEMM interface. If the transpose flags are // true, then the relevant matrix is treated as stored in column-major order. template <class T1, class T2, class T3> void ReferenceGemm(bool transpose_a, bool transpose_b, bool transpose_c, size_t m, size_t n, size_t k, const T1* a, int32 offset_a, size_t lda, const T2* b, int32 offset_b, size_t ldb, T3* c, int32 shift_c, int32 offset_c, int32 mult_c, size_t ldc) { int a_i_stride; int a_l_stride; if (transpose_a) { a_i_stride = 1; a_l_stride = lda; } else { a_i_stride = lda; a_l_stride = 1; } int b_j_stride; int b_l_stride; if (transpose_b) { b_j_stride = ldb; b_l_stride = 1; } else { b_j_stride = 1; b_l_stride = ldb; } int c_i_stride; int c_j_stride; if (transpose_c) { c_i_stride = 1; c_j_stride = ldc; } else { c_i_stride = ldc; c_j_stride = 1; } // const int32 highest = static_cast<int32>(Eigen::NumTraits<T3>::highest()); // const int32 lowest = static_cast<int32>(Eigen::NumTraits<T3>::lowest()); const int32 highest = static_cast<int32>(std::numeric_limits<T3>::max()); const int32 lowest = static_cast<int32>(std::numeric_limits<T3>::min()); const int32 rounding = (shift_c < 1) ? 0 : (1 << (shift_c - 1)); int i, j, l; for (j = 0; j < n; j++) { for (i = 0; i < m; i++) { int32 total = 0; for (l = 0; l < k; l++) { const size_t a_index = ((i * a_i_stride) + (l * a_l_stride)); const int32 a_value = static_cast<int32>(a[a_index]) - offset_a; const size_t b_index = ((j * b_j_stride) + (l * b_l_stride)); const int32 b_value = static_cast<int32>(b[b_index]) - offset_b; total += (a_value * b_value); } const size_t c_index = ((i * c_i_stride) + (j * c_j_stride)); int32_t output = ((((total + offset_c) * mult_c) + rounding) >> shift_c); if (output > highest) { output = highest; } if (output < lowest) { output = lowest; } c[c_index] = static_cast<T3>(output); } } } template <class T1, class T2, class T3> void ReferenceGemm(bool transpose_a, bool transpose_b, bool transpose_c, size_t m, size_t n, size_t k, const T1* a, int32 offset_a, size_t lda, const T2* b, int32 offset_b, size_t ldb, T3* c, int32 shift_c, int32 offset_c, int32 mult_c, size_t ldc) { int a_i_stride = lda; int a_l_stride = 1; if (transpose_a) { a_i_stride = 1; a_l_stride = lda; } int b_j_stride = 1; int b_l_stride = ldb; if (transpose_b) { b_j_stride = ldb; b_l_stride = 1; } int c_i_stride = ldc; int c_j_stride = 1; if (transpose_c) { c_i_stride = 1; c_j_stride = ldc; } // const int32 highest = static_cast<int32>(Eigen::NumTraits<T3>::highest()); // const int32 lowest = static_cast<int32>(Eigen::NumTraits<T3>::lowest()); const int32 highest = static_cast<int32>(std::numeric_limits<T3>::max()); const int32 lowest = static_cast<int32>(std::numeric_limits<T3>::min()); const int32 rounding = (shift_c < 1) ? 0 : (1 << (shift_c - 1)); int i, j, l; for (j = 0; j < n; j++) { for (i = 0; i < m; i++) { int32 total = 0; for (l = 0; l < k; l++) { const size_t a_index = ((i * a_i_stride) + (l * a_l_stride)); const int32 a_value = static_cast<int32>(a[a_index]) - offset_a; const size_t b_index = ((j * b_j_stride) + (l * b_l_stride)); const int32 b_value = static_cast<int32>(b[b_index]) - offset_b; total += (a_value * b_value); } const size_t c_index = ((i * c_i_stride) + (j * c_j_stride)); int32_t output = ((((total + offset_c) * mult_c) + rounding) >> shift_c); if (output > highest) { output = highest; } if (output < lowest) { output = lowest; } c[c_index] = static_cast<T3>(output); } } } #endif <|endoftext|>
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include <commctrl.h> #include "base/command_line.h" #include "base/event_recorder.h" #include "base/gfx/native_theme.h" #include "base/resource_util.h" #include "base/win_util.h" #include "webkit/tools/test_shell/foreground_helper.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_platform_delegate.h" TestShellPlatformDelegate::TestShellPlatformDelegate( const CommandLine& command_line) : command_line_(command_line) { #ifdef _CRTDBG_MAP_ALLOC _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); #endif } TestShellPlatformDelegate::~TestShellPlatformDelegate() { #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif } void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) { } // This test approximates whether you have the Windows XP theme selected by // inspecting a couple of metrics. It does not catch all cases, but it does // pick up on classic vs xp, and normal vs large fonts. Something it misses // is changes to the color scheme (which will infact cause pixel test // failures). // // ** Expected dependencies ** // + Theme: Windows XP // + Color scheme: Default (blue) // + Font size: Normal // + Font smoothing: off (minor impact). // static bool HasLayoutTestThemeDependenciesWin() { // This metric will be 17 when font size is "Normal". The size of drop-down // menus depends on it. if (::GetSystemMetrics(SM_CXVSCROLL) != 17) return false; // Check that the system fonts RenderThemeWin relies on are Tahoma 11 pt. NONCLIENTMETRICS metrics; win_util::GetNonClientMetrics(&metrics); LOGFONTW* system_fonts[] = { &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont }; for (size_t i = 0; i < arraysize(system_fonts); ++i) { if (system_fonts[i]->lfHeight != -11 || 0 != wcscmp(L"Tahoma", system_fonts[i]->lfFaceName)) return false; } return true; } bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() { bool has_deps = HasLayoutTestThemeDependenciesWin(); if (!has_deps) { fprintf(stderr, "\n" "###############################################################\n" "## Layout test system dependencies check failed.\n" "## Some layout tests may fail due to unexpected theme.\n" "##\n" "## To fix, go to Display Properties -> Appearance, and select:\n" "## + Windows and buttons: Windows XP style\n" "## + Color scheme: Default (blue)\n" "## + Font size: Normal\n" "###############################################################\n"); } return has_deps; } void TestShellPlatformDelegate::SuppressErrorReporting() { _set_abort_behavior(0, _WRITE_ABORT_MSG); } void TestShellPlatformDelegate::InitializeGUI() { INITCOMMONCONTROLSEX InitCtrlEx; InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); InitCtrlEx.dwICC = ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrlEx); TestShell::RegisterWindowClass(); } void TestShellPlatformDelegate::SelectUnifiedTheme() { gfx::NativeTheme::instance()->DisableTheming(); } void TestShellPlatformDelegate::SetWindowPositionForRecording( TestShell *shell) { // Move the window to the upper left corner for consistent // record/playback mode. For automation, we want this to work // on build systems where the script invoking us is a background // process. So for this case, make our window the topmost window // as well. ForegroundHelper::SetForeground(shell->mainWnd()); ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0); } <commit_msg>modify test_shell's check-sys-deps to work on vista as well as xp<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include <list> #include <windows.h> #include <commctrl.h> #include "base/command_line.h" #include "base/event_recorder.h" #include "base/gfx/native_theme.h" #include "base/resource_util.h" #include "base/win_util.h" #include "webkit/tools/test_shell/foreground_helper.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_platform_delegate.h" TestShellPlatformDelegate::TestShellPlatformDelegate( const CommandLine& command_line) : command_line_(command_line) { #ifdef _CRTDBG_MAP_ALLOC _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); #endif } TestShellPlatformDelegate::~TestShellPlatformDelegate() { #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif } void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) { } // This test approximates whether you are running the default themes for // your platform by inspecting a couple of metrics. // It does not catch all cases, but it does pick up on classic vs xp, // and normal vs large fonts. Something it misses is changes to the color // scheme (which will infact cause pixel test failures). bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() { std::list<std::string> errors; OSVERSIONINFOEX osvi; ::ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); ::GetVersionEx((OSVERSIONINFO *)&osvi); // default to XP metrics, override if on Vista int requiredVScrollSize = 17; int requiredFontSize = -11; // 8 pt const WCHAR *requiredFont = L"Tahoma"; bool isVista = false; if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0 && osvi.wProductType == VER_NT_WORKSTATION) { requiredFont = L"Segoe UI"; requiredFontSize = -12; // 9 pt isVista = true; } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 && osvi.wProductType == VER_NT_WORKSTATION) { // XP; } else { errors.push_back("Unsupported Operating System version " "(must use XP or Vista)"); } // on both XP and Vista, this metric will be 17 when font size is "Normal". // The size of drop-down menus depends on it. int vScrollSize = ::GetSystemMetrics(SM_CXVSCROLL); if (vScrollSize != requiredVScrollSize) { errors.push_back("Must use normal size fonts (96 dpi)"); } // font smoothing (including ClearType) must be disabled BOOL bFontSmoothing; SystemParametersInfo(SPI_GETFONTSMOOTHING, (UINT)0, (PVOID)&bFontSmoothing, (UINT)0); if (bFontSmoothing) { errors.push_back("Font smoothing (ClearType) must be disabled"); } // Check that we're using the default system fonts NONCLIENTMETRICS metrics; win_util::GetNonClientMetrics(&metrics); LOGFONTW* system_fonts[] = { &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont }; for (size_t i = 0; i < arraysize(system_fonts); ++i) { if (system_fonts[i]->lfHeight != requiredFontSize || wcscmp(requiredFont, system_fonts[i]->lfFaceName)) { if (isVista) errors.push_back("Must use either the Aero or Basic theme"); else errors.push_back("Must use the default XP theme (Luna)"); break; } } if (!errors.empty()) { fprintf(stderr, "%s", "##################################################################\n" "## Layout test system dependencies check failed.\n" "##\n"); for (std::list<std::string>::iterator it = errors.begin(); it != errors.end(); ++it) { fprintf(stderr, "## %s\n", it->c_str()); } fprintf(stderr, "%s", "##\n" "##################################################################\n"); } return errors.empty(); } void TestShellPlatformDelegate::SuppressErrorReporting() { _set_abort_behavior(0, _WRITE_ABORT_MSG); } void TestShellPlatformDelegate::InitializeGUI() { INITCOMMONCONTROLSEX InitCtrlEx; InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); InitCtrlEx.dwICC = ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrlEx); TestShell::RegisterWindowClass(); } void TestShellPlatformDelegate::SelectUnifiedTheme() { gfx::NativeTheme::instance()->DisableTheming(); } void TestShellPlatformDelegate::SetWindowPositionForRecording( TestShell *shell) { // Move the window to the upper left corner for consistent // record/playback mode. For automation, we want this to work // on build systems where the script invoking us is a background // process. So for this case, make our window the topmost window // as well. ForegroundHelper::SetForeground(shell->mainWnd()); ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0); } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "sparse_matrix_storage.hpp" #include <algorithm> #include <cmath> #include <string> #include <utility> #include <vector> #include "jubatus/util/data/unordered_set.h" using std::istream; using std::ostream; using std::make_pair; using std::pair; using std::string; using std::vector; namespace jubatus { namespace core { namespace storage { sparse_matrix_storage::sparse_matrix_storage() { } sparse_matrix_storage::~sparse_matrix_storage() { } sparse_matrix_storage& sparse_matrix_storage::operator =( const sparse_matrix_storage& sms) { tbl_ = sms.tbl_; column2id_ = sms.column2id_; return *this; } void sparse_matrix_storage::set( const string& row, const string& column, float val) { tbl_[row][column2id_.get_id(column)] = val; } void sparse_matrix_storage::set_row( const string& row, const vector<pair<string, float> >& columns) { row_t& row_v = tbl_[row]; for (size_t i = 0; i < columns.size(); ++i) { float& v = row_v[column2id_.get_id(columns[i].first)]; // norm_ptr_->notify(row, v, columns[i].second); v = columns[i].second; } } float sparse_matrix_storage::get( const string& row, const string& column) const { tbl_t::const_iterator it = tbl_.find(row); if (it == tbl_.end()) { return 0.f; } uint64_t id = column2id_.get_id_const(column); if (id == common::key_manager::NOTFOUND) { return 0.f; } row_t::const_iterator cit = it->second.find(id); if (cit == it->second.end()) { return 0.f; } return cit->second; } void sparse_matrix_storage::get_row( const string& row, vector<pair<string, float> >& columns) const { columns.clear(); tbl_t::const_iterator it = tbl_.find(row); if (it == tbl_.end()) { return; } const row_t& row_v = it->second; for (row_t::const_iterator row_it = row_v.begin(); row_it != row_v.end(); ++row_it) { columns.push_back( make_pair(column2id_.get_key(row_it->first), row_it->second)); } } float sparse_matrix_storage::calc_l2norm(const string& row) const { tbl_t::const_iterator it = tbl_.find(row); if (it == tbl_.end()) { return 0.f; } float sq_norm = 0.f; const row_t& row_v = it->second; for (row_t::const_iterator row_it = row_v.begin(); row_it != row_v.end(); ++row_it) { sq_norm += row_it->second * row_it->second; } return std::sqrt(sq_norm); } void sparse_matrix_storage::remove(const string& row, const string& column) { tbl_t::iterator it = tbl_.find(row); if (it == tbl_.end()) { return; } uint64_t id = column2id_.get_id_const(column); if (id == common::key_manager::NOTFOUND) { return; } row_t::iterator cit = it->second.find(id); if (cit == it->second.end()) { return; } // norm_ptr_->notify(row, cit->second, 0.f); it->second.erase(cit); } void sparse_matrix_storage::remove_row(const string& row) { tbl_t::iterator it = tbl_.find(row); if (it == tbl_.end()) { return; } // for (row_t::const_iterator cit = it->second.begin(); // cit != it->second.end(); ++cit){ // norm_ptr_->notify(row, cit->second, 0.f); // } tbl_.erase(it); } void sparse_matrix_storage::get_all_row_ids(vector<string>& ids) const { ids.clear(); for (tbl_t::const_iterator it = tbl_.begin(); it != tbl_.end(); ++it) { ids.push_back(it->first); } } void sparse_matrix_storage::clear() { tbl_t().swap(tbl_); common::key_manager().swap(column2id_); // norm_ptr_->clear(); } void sparse_matrix_storage::pack(msgpack::packer<msgpack::sbuffer>& packer) const { packer.pack_array(2); packer.pack(tbl_); packer.pack(column2id_); } void sparse_matrix_storage::unpack(msgpack::object o) { std::vector<msgpack::object> mems; o.convert(&mems); if (mems.size() != 2) { throw msgpack::type_error(); } mems[0].convert(&tbl_); mems[1].convert(&column2id_); } } // namespace storage } // namespace core } // namespace jubatus <commit_msg>Pack/unpack the storage directly using serialization<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "sparse_matrix_storage.hpp" #include <algorithm> #include <cmath> #include <string> #include <utility> #include <vector> #include "jubatus/util/data/unordered_set.h" using std::istream; using std::ostream; using std::make_pair; using std::pair; using std::string; using std::vector; namespace jubatus { namespace core { namespace storage { sparse_matrix_storage::sparse_matrix_storage() { } sparse_matrix_storage::~sparse_matrix_storage() { } sparse_matrix_storage& sparse_matrix_storage::operator =( const sparse_matrix_storage& sms) { tbl_ = sms.tbl_; column2id_ = sms.column2id_; return *this; } void sparse_matrix_storage::set( const string& row, const string& column, float val) { tbl_[row][column2id_.get_id(column)] = val; } void sparse_matrix_storage::set_row( const string& row, const vector<pair<string, float> >& columns) { row_t& row_v = tbl_[row]; for (size_t i = 0; i < columns.size(); ++i) { float& v = row_v[column2id_.get_id(columns[i].first)]; // norm_ptr_->notify(row, v, columns[i].second); v = columns[i].second; } } float sparse_matrix_storage::get( const string& row, const string& column) const { tbl_t::const_iterator it = tbl_.find(row); if (it == tbl_.end()) { return 0.f; } uint64_t id = column2id_.get_id_const(column); if (id == common::key_manager::NOTFOUND) { return 0.f; } row_t::const_iterator cit = it->second.find(id); if (cit == it->second.end()) { return 0.f; } return cit->second; } void sparse_matrix_storage::get_row( const string& row, vector<pair<string, float> >& columns) const { columns.clear(); tbl_t::const_iterator it = tbl_.find(row); if (it == tbl_.end()) { return; } const row_t& row_v = it->second; for (row_t::const_iterator row_it = row_v.begin(); row_it != row_v.end(); ++row_it) { columns.push_back( make_pair(column2id_.get_key(row_it->first), row_it->second)); } } float sparse_matrix_storage::calc_l2norm(const string& row) const { tbl_t::const_iterator it = tbl_.find(row); if (it == tbl_.end()) { return 0.f; } float sq_norm = 0.f; const row_t& row_v = it->second; for (row_t::const_iterator row_it = row_v.begin(); row_it != row_v.end(); ++row_it) { sq_norm += row_it->second * row_it->second; } return std::sqrt(sq_norm); } void sparse_matrix_storage::remove(const string& row, const string& column) { tbl_t::iterator it = tbl_.find(row); if (it == tbl_.end()) { return; } uint64_t id = column2id_.get_id_const(column); if (id == common::key_manager::NOTFOUND) { return; } row_t::iterator cit = it->second.find(id); if (cit == it->second.end()) { return; } // norm_ptr_->notify(row, cit->second, 0.f); it->second.erase(cit); } void sparse_matrix_storage::remove_row(const string& row) { tbl_t::iterator it = tbl_.find(row); if (it == tbl_.end()) { return; } // for (row_t::const_iterator cit = it->second.begin(); // cit != it->second.end(); ++cit){ // norm_ptr_->notify(row, cit->second, 0.f); // } tbl_.erase(it); } void sparse_matrix_storage::get_all_row_ids(vector<string>& ids) const { ids.clear(); for (tbl_t::const_iterator it = tbl_.begin(); it != tbl_.end(); ++it) { ids.push_back(it->first); } } void sparse_matrix_storage::clear() { tbl_t().swap(tbl_); common::key_manager().swap(column2id_); // norm_ptr_->clear(); } void sparse_matrix_storage::pack(msgpack::packer<msgpack::sbuffer>& packer) const { packer.pack(*this); } void sparse_matrix_storage::unpack(msgpack::object o) { o.convert(this); } } // namespace storage } // namespace core } // namespace jubatus <|endoftext|>
<commit_before>#include "Vajra/Common/Messages/Message.h" #include "Vajra/Engine/Components/DerivedComponents/Lights/DirectionalLight/DirectionalLight.h" #include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h" #include "Vajra/Engine/GameObject/GameObject.h" #include "Vajra/Framework/Core/Framework.h" #include "Vajra/Framework/Logging/Logger.h" #include "Vajra/Framework/OpenGL/OpenGLWrapper/OpenGLWrapper.h" #include "Vajra/Framework/OpenGL/ShaderSet/ShaderSet.h" unsigned int DirectionalLight::componentTypeId = COMPONENT_TYPE_ID_DIRECTIONAL_LIGHT; DirectionalLight::DirectionalLight() : Component() { this->init(); } DirectionalLight::DirectionalLight(Object* object_) : Component(object_) { this->init(); } DirectionalLight::~DirectionalLight() { this->destroy(); } void DirectionalLight::HandleMessage(Message* message) { switch (message->GetMessageType()) { default: FRAMEWORK->GetLogger()->dbglog("\nDirectionalLight got unnecessary msg of type %d", message->GetMessageType()); } } void DirectionalLight::WriteLightPropertiesToShader() { GameObject* gameObject = (GameObject*)this->GetObject(); glm::vec3 position = gameObject->GetTransform()->GetPosition(); glUniform4f(FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet()->GetDirectionalLight()->GetDirectionHandle(), position.x, position.y, position.z, 0.0f); glUniform4f(FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet()->GetDirectionalLight()->GetAmbientColorHandle(), this->ambientColor.r, this->ambientColor.g, this->ambientColor.b, this->ambientColor.a); glUniform4f(FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet()->GetDirectionalLight()->GetDiffuseColorHandle(), this->diffuseColor.r, this->diffuseColor.g, this->diffuseColor.b, this->diffuseColor.a); glUniform4f(FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet()->GetDirectionalLight()->GetSpecularColorHandle(), this->specularColor.r, this->specularColor.g, this->specularColor.b, this->specularColor.a); } void DirectionalLight::init() { GameObject* gameObject = dynamic_cast<GameObject*>(this->GetObject()); if (gameObject != nullptr) { ASSERT(typeid(gameObject) == typeid(GameObject*), "Type of Object* (%s) of id %d was %s", typeid(gameObject).name(), gameObject->GetId(), typeid(GameObject*).name()); } if (gameObject != nullptr) { this->WriteLightPropertiesToShader(); } } void DirectionalLight::destroy() { this->removeSubscriptionToAllMessageTypes(this->GetTypeId()); } <commit_msg>Woops. Fix the light. Was sending position instead of direction to the shader.<commit_after>#include "Vajra/Common/Messages/Message.h" #include "Vajra/Engine/Components/DerivedComponents/Lights/DirectionalLight/DirectionalLight.h" #include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h" #include "Vajra/Engine/GameObject/GameObject.h" #include "Vajra/Framework/Core/Framework.h" #include "Vajra/Framework/Logging/Logger.h" #include "Vajra/Framework/OpenGL/OpenGLWrapper/OpenGLWrapper.h" #include "Vajra/Framework/OpenGL/ShaderSet/ShaderSet.h" unsigned int DirectionalLight::componentTypeId = COMPONENT_TYPE_ID_DIRECTIONAL_LIGHT; DirectionalLight::DirectionalLight() : Component() { this->init(); } DirectionalLight::DirectionalLight(Object* object_) : Component(object_) { this->init(); } DirectionalLight::~DirectionalLight() { this->destroy(); } void DirectionalLight::HandleMessage(Message* message) { switch (message->GetMessageType()) { default: FRAMEWORK->GetLogger()->dbglog("\nDirectionalLight got unnecessary msg of type %d", message->GetMessageType()); } } void DirectionalLight::WriteLightPropertiesToShader() { GameObject* gameObject = (GameObject*)this->GetObject(); glm::vec3 forward = gameObject->GetTransform()->GetForward(); glUniform4f(FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet()->GetDirectionalLight()->GetDirectionHandle(), forward.x, forward.y, forward.z, 0.0f); glUniform4f(FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet()->GetDirectionalLight()->GetAmbientColorHandle(), this->ambientColor.r, this->ambientColor.g, this->ambientColor.b, this->ambientColor.a); glUniform4f(FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet()->GetDirectionalLight()->GetDiffuseColorHandle(), this->diffuseColor.r, this->diffuseColor.g, this->diffuseColor.b, this->diffuseColor.a); glUniform4f(FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet()->GetDirectionalLight()->GetSpecularColorHandle(), this->specularColor.r, this->specularColor.g, this->specularColor.b, this->specularColor.a); } void DirectionalLight::init() { GameObject* gameObject = dynamic_cast<GameObject*>(this->GetObject()); if (gameObject != nullptr) { ASSERT(typeid(gameObject) == typeid(GameObject*), "Type of Object* (%s) of id %d was %s", typeid(gameObject).name(), gameObject->GetId(), typeid(GameObject*).name()); } if (gameObject != nullptr) { this->WriteLightPropertiesToShader(); } } void DirectionalLight::destroy() { this->removeSubscriptionToAllMessageTypes(this->GetTypeId()); } <|endoftext|>
<commit_before><commit_msg>Create 1.2.cpp<commit_after><|endoftext|>
<commit_before>#ifndef ANIMPLUGIN_SKELETON_UTILS_HPP_ #define ANIMPLUGIN_SKELETON_UTILS_HPP_ #include <Core/Animation/Pose/Pose.hpp> #include <Core/Animation/Handle/Skeleton.hpp> namespace Ra { namespace Core { namespace Animation { namespace SkeletonUtils { /// Returns the start and end point of a bone in model space. inline void getBonePoints(const Ra::Core::Animation::Skeleton& skeleton, int boneIdx, Ra::Core::Vector3& startOut, Ra::Core::Vector3& endOut) { // Check bone index is valid CORE_ASSERT(boneIdx >= 0 && boneIdx < skeleton.m_graph.size(), "invalid bone index"); startOut = skeleton.getTransform(boneIdx, Ra::Core::Animation::Handle::SpaceType::MODEL).translation(); auto children = skeleton.m_graph.m_child.at(boneIdx); // A leaf bone has length 0 if (children.size() == 0) { endOut = startOut; } else { // End point is the average of chidren start points. endOut = Ra::Core::Vector3::Zero(); for (auto child : children) { endOut += skeleton.getTransform(child, Ra::Core::Animation::Handle::SpaceType::MODEL).translation(); } endOut *= (1.f / children.size()); } } /// Gives out the nearest point on a given bone. inline Ra::Core::Vector3 projectOnBone(const Ra::Core::Animation::Skeleton& skeleton, int boneIdx, const Ra::Core::Vector3& pos) { Ra::Core::Vector3 start, end; getBonePoints(skeleton, boneIdx, start, end); auto op = pos - start; auto dir = (end - start); // Square length of bone const Scalar length_sq = dir.squaredNorm(); CORE_ASSERT(length_sq != 0.f, "bone has lenght 0, cannot project."); // Project on the line segment const Scalar t = Ra::Core::Math::clamp(op.dot(dir) / length_sq, 0.f, 1.f); return start + (t * dir); } } } } } #endif <commit_msg>Misusing of namespace fixed<commit_after>#ifndef ANIMPLUGIN_SKELETON_UTILS_HPP_ #define ANIMPLUGIN_SKELETON_UTILS_HPP_ #include <Core/Animation/Pose/Pose.hpp> #include <Core/Animation/Handle/Skeleton.hpp> namespace Ra { namespace Core { namespace Animation { namespace SkeletonUtils { /// Returns the start and end point of a bone in model space. inline void getBonePoints(const Skeleton& skeleton, int boneIdx, Vector3& startOut, Vector3& endOut) { // Check bone index is valid CORE_ASSERT(boneIdx >= 0 && boneIdx < skeleton.m_graph.size(), "invalid bone index"); startOut = skeleton.getTransform(boneIdx, Handle::SpaceType::MODEL).translation(); auto children = skeleton.m_graph.m_child.at(boneIdx); // A leaf bone has length 0 if (children.size() == 0) { endOut = startOut; } else { // End point is the average of chidren start points. endOut = Vector3::Zero(); for (auto child : children) { endOut += skeleton.getTransform(child, Handle::SpaceType::MODEL).translation(); } endOut *= (1.f / children.size()); } } /// Gives out the nearest point on a given bone. inline Vector3 projectOnBone(const Skeleton& skeleton, int boneIdx, const Vector3& pos) { Vector3 start, end; getBonePoints(skeleton, boneIdx, start, end); auto op = pos - start; auto dir = (end - start); // Square length of bone const Scalar length_sq = dir.squaredNorm(); CORE_ASSERT(length_sq != 0.f, "bone has lenght 0, cannot project."); // Project on the line segment const Scalar t = Math::clamp(op.dot(dir) / length_sq, 0.f, 1.f); return start + (t * dir); } } } } } #endif <|endoftext|>
<commit_before>// Copyright 2014 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __rosidl_typesupport_introspection_cpp__field_types__hpp__ #define __rosidl_typesupport_introspection_cpp__field_types__hpp__ #include <cstdint> namespace rosidl_typesupport_introspection_cpp { const uint8_t ROS_TYPE_BOOL = 1; const uint8_t ROS_TYPE_BYTE = 2; const uint8_t ROS_TYPE_CHAR = 3; const uint8_t ROS_TYPE_FLOAT32 = 4; const uint8_t ROS_TYPE_FLOAT64 = 5; const uint8_t ROS_TYPE_INT8 = 6; const uint8_t ROS_TYPE_UINT8 = 7; const uint8_t ROS_TYPE_INT16 = 8; const uint8_t ROS_TYPE_UINT16 = 9; const uint8_t ROS_TYPE_INT32 = 10; const uint8_t ROS_TYPE_UINT32 = 11; const uint8_t ROS_TYPE_INT64 = 12; const uint8_t ROS_TYPE_UINT64 = 13; const uint8_t ROS_TYPE_STRING = 14; const uint8_t ROS_TYPE_MESSAGE = 15; } // namespace rosidl_typesupport_introspection_cpp #endif // __rosidl_typesupport_introspection_cpp__field_types__hpp__ <commit_msg>style only<commit_after>// Copyright 2014 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __rosidl_typesupport_introspection_cpp__field_types__hpp__ #define __rosidl_typesupport_introspection_cpp__field_types__hpp__ #include <cstdint> namespace rosidl_typesupport_introspection_cpp { const uint8_t ROS_TYPE_BOOL = 1; const uint8_t ROS_TYPE_BYTE = 2; const uint8_t ROS_TYPE_CHAR = 3; const uint8_t ROS_TYPE_FLOAT32 = 4; const uint8_t ROS_TYPE_FLOAT64 = 5; const uint8_t ROS_TYPE_INT8 = 6; const uint8_t ROS_TYPE_UINT8 = 7; const uint8_t ROS_TYPE_INT16 = 8; const uint8_t ROS_TYPE_UINT16 = 9; const uint8_t ROS_TYPE_INT32 = 10; const uint8_t ROS_TYPE_UINT32 = 11; const uint8_t ROS_TYPE_INT64 = 12; const uint8_t ROS_TYPE_UINT64 = 13; const uint8_t ROS_TYPE_STRING = 14; const uint8_t ROS_TYPE_MESSAGE = 15; } // namespace rosidl_typesupport_introspection_cpp #endif // __rosidl_typesupport_introspection_cpp__field_types__hpp__ <|endoftext|>
<commit_before>#include <nanyc/library.h> #include <nanyc/program.h> #include <yuni/yuni.h> #include <yuni/core/getopt.h> #include <yuni/core/string.h> #include <yuni/io/filename-manipulation.h> #include <yuni/datetime/timestamp.h> #include <yuni/core/system/console/console.h> #include <yuni/core/process/program.h> #include <iostream> #include <vector> #include <algorithm> #include <memory> #include <random> #include "libnanyc.h" namespace ny { namespace unittests { namespace { constexpr const char runningText[] = " running "; struct Entry final { yuni::String module; yuni::String name; }; struct Result final { Entry entry; bool success; int64_t duration_ms; }; struct App final { App(); App(App&&) = default; ~App(); void importFilenames(const std::vector<AnyString>&); void fetch(bool nsl); void run(const Entry&); int run(); bool statstics(int64_t duration); void setcolor(yuni::System::Console::Color) const; void resetcolor() const; bool inExecutorMode() const; struct final { uint32_t total = 0; uint32_t passing = 0; uint32_t failed = 0; } stats; nycompile_opts_t opts; bool interactive = true; bool colors = true; uint32_t loops = 1; bool shuffle = false; std::vector<Entry> unittests; std::vector<yuni::String> filenames; std::vector<Result> results; Entry execinfo; AnyString argv0; private: void startEntry(const Entry&); void endEntry(const Entry&, bool, int64_t); bool execute(const Entry& entry); yuni::String runningMsg; }; App::App() { memset(&opts, 0x0, sizeof(opts)); opts.userdata = this;; } App::~App() { free(opts.sources.items); } void App::setcolor(yuni::System::Console::Color c) const { if (colors) yuni::System::Console::SetTextColor(std::cout, c); } void App::resetcolor() const { if (colors) yuni::System::Console::ResetTextColor(std::cout); } bool App::inExecutorMode() const { return not execinfo.name.empty(); } auto now() { return yuni::DateTime::NowMilliSeconds(); } bool operator < (const Entry& a, const Entry& b) { return std::tie(a.module, a.name) < std::tie(b.module, b.name); } const char* plurals(auto count, const char* single, const char* many) { return (count <= 1) ? single : many; } void App::importFilenames(const std::vector<AnyString>& list) { uint32_t count = static_cast<uint32_t>(list.size()); filenames.resize(count); std::transform(std::begin(list), std::end(list), std::begin(filenames), [](auto& item) -> yuni::String { return std::move(yuni::IO::Canonicalize(item)); }); opts.sources.count = count; opts.sources.items = (nysource_opts_t*) calloc(count, sizeof(nysource_opts_t)); if (unlikely(!opts.sources.items)) throw std::bad_alloc(); for (uint32_t i = 0; i != count; ++i) { opts.sources.items[i].filename.len = filenames[i].size(); opts.sources.items[i].filename.c_str = filenames[i].c_str(); } } void App::fetch(bool nsl) { unittests.reserve(512); // arbitrary opts.with_nsl_unittests = nsl ? nytrue : nyfalse; opts.on_unittest = [](void* userdata, const char* mod, uint32_t mlen, const char* name, uint32_t nlen) { auto& self = *reinterpret_cast<App*>(userdata); self.unittests.emplace_back(); auto& entry = self.unittests.back(); entry.module.assign(mod, mlen); entry.name.assign(name, nlen); }; std::cout << "searching for unittests in all source files...\n"; auto start = now(); nyprogram_compile(&opts); opts.on_unittest = nullptr; std::sort(std::begin(unittests), std::end(unittests)); auto duration = now() - start; std::cout << unittests.size() << ' ' << plurals(unittests.size(), "test", "tests"); std::cout << " found (in " << duration << "ms)\n"; } void App::startEntry(const Entry& entry) { if (interactive) { setcolor(yuni::System::Console::bold); std::cout << runningText; resetcolor(); auto previousLength = runningMsg.size(); runningMsg.clear(); runningMsg << entry.module << '/' << entry.name << "... "; if (runningMsg.size() < previousLength) runningMsg.resize(previousLength, " "); std::cout << runningMsg << '\r' << std::flush; } } void App::endEntry(const Entry& entry, bool success, int64_t duration) { Result result; result.entry = entry; result.success = success; result.duration_ms = duration; results.emplace_back(std::move(result)); } bool App::statstics(int64_t duration) { if (interactive) { runningMsg.resize(runningMsg.size() + AnyString(runningText).size()); runningMsg.fill(' '); std::cout << runningMsg << '\r'; } for (auto& result: results) { ++(result.success ? stats.passing : stats.failed); if (result.success) { setcolor(yuni::System::Console::green); #ifndef YUNI_OS_WINDOWS std::cout << " \u2713 "; #else std::cout << " OK "; #endif resetcolor(); } else { setcolor(yuni::System::Console::red); std::cout << " ERR "; resetcolor(); } std::cout << result.entry.module << '/' << result.entry.name; setcolor(yuni::System::Console::lightblue); std::cout << " (" << result.duration_ms << "ms)"; resetcolor(); std::cout << '\n'; } std::cout << "\n " << stats.total << ' ' << plurals(stats.total, "test", "tests"); if (stats.passing != 0) { std::cout << ", "; setcolor(yuni::System::Console::red); std::cout << stats.passing << " passing"; resetcolor(); } if (stats.failed) { std::cout << ", "; setcolor(yuni::System::Console::red); std::cout << stats.failed << " failed"; resetcolor(); } std::cout << " ("; if (duration < 10000) std::cout << duration << "ms)"; else std::cout << (duration / 1000) << "s)"; std::cout << "\n\n"; return stats.failed == 0 and stats.total != 0; } bool App::execute(const Entry& entry) { auto* program = nyprogram_compile(&opts); bool success = program != nullptr; if (program) { nyprogram_free(program); } return success; } void App::run(const Entry& entry) { startEntry(entry); yuni::Process::Program program; program.durationPrecision(yuni::Process::Program::dpMilliseconds); program.program(argv0); program.argumentAdd("--executor-module"); program.argumentAdd(entry.module); program.argumentAdd("--executor-name"); program.argumentAdd(entry.name); for (auto& filename: filenames) program.argumentAdd(filename); auto start = now(); bool success = program.execute(); success = success and (program.wait() == 0); auto duration = now() - start; endEntry(entry, success, duration); } void shuffleDeck(std::vector<Entry>& unittests) { std::cout << "shuffling the tests...\n" << std::flush; auto seed = now(); auto useed = static_cast<uint32_t>(seed); std::shuffle(unittests.begin(), unittests.end(), std::default_random_engine(useed)); } int App::run() { bool success; if (not inExecutorMode()) { stats.total = static_cast<uint32_t>(loops * unittests.size()); results.reserve(stats.total); std::cout << '\n'; auto start = now(); for (uint32_t l = 0; l != loops; ++l) { if (unlikely(shuffle)) shuffleDeck(unittests); for (auto& entry: unittests) run(entry); } auto duration = now() - start; success = statstics(duration); } else { success = execute(execinfo); } return success ? EXIT_SUCCESS : EXIT_FAILURE; } int printVersion() { std::cout << libnanyc_version_to_cstr() << '\n'; return EXIT_SUCCESS; } int printBugreport() { uint32_t length; auto* text = libnanyc_get_bugreportdetails(&length); if (text) { std::cout.write(text, length); free(text); } std::cout << '\n'; return EXIT_SUCCESS; } App prepare(int argc, char** argv) { App app; bool version = false; bool bugreport = false; bool nsl = false; bool verbose = false; bool nocolors = false; std::vector<AnyString> filenames; yuni::GetOpt::Parser options; options.add(filenames, 'i', "", "Input nanyc source files"); options.addFlag(nsl, ' ', "nsl", "Import NSL unittests"); options.add(app.execinfo.module, ' ', "executor-module", "Executor mode, module name (internal use)", false); options.add(app.execinfo.name, ' ', "executor-name", "Executor mode, unittest (internal use)", false); options.addParagraph("\nEntropy"); options.add(app.loops, 'n', "loops", "Number of loops (default: 1)"); options.addFlag(app.shuffle, 's', "shuffle", "Randomly rearrange the unittests"); options.addParagraph("\nDisplay"); options.addFlag(nocolors, ' ', "no-colors", "Disable color output"); options.addParagraph("\nHelp"); options.addFlag(verbose, 'v', "verbose", "More stuff on the screen"); options.addFlag(bugreport, 'b', "bugreport", "Display some useful information to report a bug"); options.addFlag(version, ' ', "version", "Print the version"); options.remainingArguments(filenames); if (not options(argc, argv)) { if (options.errors()) throw std::runtime_error("Abort due to error"); throw EXIT_SUCCESS; } if (unlikely(version)) throw printVersion(); if (unlikely(bugreport)) throw printBugreport(); if (unlikely(verbose)) printBugreport(); app.importFilenames(filenames); if (not app.inExecutorMode()) { if (unlikely(app.loops > 100)) throw "number of loops greater than hard-limit '100'"; app.interactive = yuni::System::Console::IsStdoutTTY(); app.colors = (not nocolors) and app.interactive; app.argv0 = argv[0]; app.fetch(nsl); } return app; } } // namespace } // namespace unittests } // namespace ny int main(int argc, char** argv) { try { auto app = ny::unittests::prepare(argc, argv); return app.run(); } catch (const char* e) { std::cerr << "error: " << e << '\n'; } catch (const std::exception& e) { std::cerr << "exception: " << e.what() << '\n'; } catch (int e) { return e; } return EXIT_FAILURE;; } <commit_msg>unittests: fix non interactive mode<commit_after>#include <nanyc/library.h> #include <nanyc/program.h> #include <yuni/yuni.h> #include <yuni/core/getopt.h> #include <yuni/core/string.h> #include <yuni/io/filename-manipulation.h> #include <yuni/datetime/timestamp.h> #include <yuni/core/system/console/console.h> #include <yuni/core/process/program.h> #include <iostream> #include <vector> #include <algorithm> #include <memory> #include <random> #include "libnanyc.h" namespace ny { namespace unittests { namespace { constexpr const char runningText[] = " running "; struct Entry final { yuni::String module; yuni::String name; }; struct Result final { Entry entry; bool success; int64_t duration_ms; }; struct App final { App(); App(App&&) = default; ~App(); void importFilenames(const std::vector<AnyString>&); void fetch(bool nsl); void run(const Entry&); int run(); bool statstics(int64_t duration); void setcolor(yuni::System::Console::Color) const; void resetcolor() const; bool inExecutorMode() const; struct final { uint32_t total = 0; uint32_t passing = 0; uint32_t failed = 0; } stats; nycompile_opts_t opts; bool interactive = true; bool colors = true; uint32_t loops = 1; bool shuffle = false; std::vector<Entry> unittests; std::vector<yuni::String> filenames; std::vector<Result> results; Entry execinfo; AnyString argv0; private: void startEntry(const Entry&); void endEntry(const Entry&, bool, int64_t); bool execute(const Entry& entry); yuni::String runningMsg; }; App::App() { memset(&opts, 0x0, sizeof(opts)); opts.userdata = this;; } App::~App() { free(opts.sources.items); } void App::setcolor(yuni::System::Console::Color c) const { if (colors) yuni::System::Console::SetTextColor(std::cout, c); } void App::resetcolor() const { if (colors) yuni::System::Console::ResetTextColor(std::cout); } bool App::inExecutorMode() const { return not execinfo.name.empty(); } auto now() { return yuni::DateTime::NowMilliSeconds(); } bool operator < (const Entry& a, const Entry& b) { return std::tie(a.module, a.name) < std::tie(b.module, b.name); } const char* plurals(auto count, const char* single, const char* many) { return (count <= 1) ? single : many; } void App::importFilenames(const std::vector<AnyString>& list) { uint32_t count = static_cast<uint32_t>(list.size()); filenames.resize(count); std::transform(std::begin(list), std::end(list), std::begin(filenames), [](auto& item) -> yuni::String { return std::move(yuni::IO::Canonicalize(item)); }); opts.sources.count = count; opts.sources.items = (nysource_opts_t*) calloc(count, sizeof(nysource_opts_t)); if (unlikely(!opts.sources.items)) throw std::bad_alloc(); for (uint32_t i = 0; i != count; ++i) { opts.sources.items[i].filename.len = filenames[i].size(); opts.sources.items[i].filename.c_str = filenames[i].c_str(); } } void App::fetch(bool nsl) { unittests.reserve(512); // arbitrary opts.with_nsl_unittests = nsl ? nytrue : nyfalse; opts.on_unittest = [](void* userdata, const char* mod, uint32_t mlen, const char* name, uint32_t nlen) { auto& self = *reinterpret_cast<App*>(userdata); self.unittests.emplace_back(); auto& entry = self.unittests.back(); entry.module.assign(mod, mlen); entry.name.assign(name, nlen); }; std::cout << "searching for unittests in all source files...\n"; auto start = now(); nyprogram_compile(&opts); opts.on_unittest = nullptr; std::sort(std::begin(unittests), std::end(unittests)); auto duration = now() - start; std::cout << unittests.size() << ' ' << plurals(unittests.size(), "test", "tests"); std::cout << " found (in " << duration << "ms)\n"; } void App::startEntry(const Entry& entry) { if (interactive) { setcolor(yuni::System::Console::bold); std::cout << runningText; resetcolor(); auto previousLength = runningMsg.size(); runningMsg.clear(); runningMsg << entry.module << '/' << entry.name << "... "; if (runningMsg.size() < previousLength) runningMsg.resize(previousLength, " "); std::cout << runningMsg << '\r' << std::flush; } } void App::endEntry(const Entry& entry, bool success, int64_t duration) { Result result; result.entry = entry; result.success = success; result.duration_ms = duration; results.emplace_back(std::move(result)); } bool App::statstics(int64_t duration) { if (interactive) { runningMsg.resize(runningMsg.size() + AnyString(runningText).size()); runningMsg.fill(' '); std::cout << runningMsg << '\r'; } for (auto& result: results) { ++(result.success ? stats.passing : stats.failed); if (result.success) { setcolor(yuni::System::Console::green); #ifndef YUNI_OS_WINDOWS std::cout << " \u2713 "; #else std::cout << " OK "; #endif resetcolor(); } else { setcolor(yuni::System::Console::red); std::cout << " ERR "; resetcolor(); } std::cout << result.entry.module << '/' << result.entry.name; setcolor(yuni::System::Console::lightblue); std::cout << " (" << result.duration_ms << "ms)"; resetcolor(); std::cout << '\n'; } std::cout << "\n " << stats.total << ' ' << plurals(stats.total, "test", "tests"); if (stats.passing != 0) { std::cout << ", "; setcolor(yuni::System::Console::red); std::cout << stats.passing << " passing"; resetcolor(); } if (stats.failed) { std::cout << ", "; setcolor(yuni::System::Console::red); std::cout << stats.failed << " failed"; resetcolor(); } std::cout << " ("; if (duration < 10000) std::cout << duration << "ms)"; else std::cout << (duration / 1000) << "s)"; std::cout << "\n\n"; return stats.failed == 0 and stats.total != 0; } bool App::execute(const Entry& entry) { auto* program = nyprogram_compile(&opts); bool success = program != nullptr; if (program) { nyprogram_free(program); } return success; } void App::run(const Entry& entry) { startEntry(entry); yuni::Process::Program program; program.durationPrecision(yuni::Process::Program::dpMilliseconds); program.program(argv0); program.argumentAdd("--executor-module"); program.argumentAdd(entry.module); program.argumentAdd("--executor-name"); program.argumentAdd(entry.name); for (auto& filename: filenames) program.argumentAdd(filename); auto start = now(); bool success = program.execute(); success = success and (program.wait() == 0); auto duration = now() - start; endEntry(entry, success, duration); } void shuffleDeck(std::vector<Entry>& unittests) { std::cout << "shuffling the tests...\n" << std::flush; auto seed = now(); auto useed = static_cast<uint32_t>(seed); std::shuffle(unittests.begin(), unittests.end(), std::default_random_engine(useed)); } int App::run() { bool success; if (not inExecutorMode()) { if (not interactive) { std::cout << '\n'; setcolor(yuni::System::Console::bold); std::cout << "running all tests..."; resetcolor(); std::cout << '\n'; } stats.total = static_cast<uint32_t>(loops * unittests.size()); results.reserve(stats.total); std::cout << '\n'; auto start = now(); for (uint32_t l = 0; l != loops; ++l) { if (unlikely(shuffle)) shuffleDeck(unittests); for (auto& entry: unittests) run(entry); } auto duration = now() - start; success = statstics(duration); } else { success = execute(execinfo); } return success ? EXIT_SUCCESS : EXIT_FAILURE; } int printVersion() { std::cout << libnanyc_version_to_cstr() << '\n'; return EXIT_SUCCESS; } int printBugreport() { uint32_t length; auto* text = libnanyc_get_bugreportdetails(&length); if (text) { std::cout.write(text, length); free(text); } std::cout << '\n'; return EXIT_SUCCESS; } App prepare(int argc, char** argv) { App app; bool version = false; bool bugreport = false; bool nsl = false; bool verbose = false; bool nocolors = false; std::vector<AnyString> filenames; yuni::GetOpt::Parser options; options.add(filenames, 'i', "", "Input nanyc source files"); options.addFlag(nsl, ' ', "nsl", "Import NSL unittests"); options.add(app.execinfo.module, ' ', "executor-module", "Executor mode, module name (internal use)", false); options.add(app.execinfo.name, ' ', "executor-name", "Executor mode, unittest (internal use)", false); options.addParagraph("\nEntropy"); options.add(app.loops, 'n', "loops", "Number of loops (default: 1)"); options.addFlag(app.shuffle, 's', "shuffle", "Randomly rearrange the unittests"); options.addParagraph("\nDisplay"); options.addFlag(nocolors, ' ', "no-colors", "Disable color output"); options.addParagraph("\nHelp"); options.addFlag(verbose, 'v', "verbose", "More stuff on the screen"); options.addFlag(bugreport, 'b', "bugreport", "Display some useful information to report a bug"); options.addFlag(version, ' ', "version", "Print the version"); options.remainingArguments(filenames); if (not options(argc, argv)) { if (options.errors()) throw std::runtime_error("Abort due to error"); throw EXIT_SUCCESS; } if (unlikely(version)) throw printVersion(); if (unlikely(bugreport)) throw printBugreport(); if (unlikely(verbose)) printBugreport(); app.importFilenames(filenames); if (not app.inExecutorMode()) { if (unlikely(app.loops > 100)) throw "number of loops greater than hard-limit '100'"; bool istty = yuni::System::Console::IsStdoutTTY(); app.interactive = istty; app.colors = (not nocolors) and istty; app.argv0 = argv[0]; app.fetch(nsl); } return app; } } // namespace } // namespace unittests } // namespace ny int main(int argc, char** argv) { try { auto app = ny::unittests::prepare(argc, argv); return app.run(); } catch (const char* e) { std::cerr << "error: " << e << '\n'; } catch (const std::exception& e) { std::cerr << "exception: " << e.what() << '\n'; } catch (int e) { return e; } return EXIT_FAILURE;; } <|endoftext|>
<commit_before>#include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <stdlib.h> #include <QtGlobal> #include <QtWidgets> #ifndef Q_OS_DARWIN #include <QtSingleApplication> #endif int main(int argc, char *argv[]) { #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif // Non Darwin platforms uses QSingleApplication to ensure only one running instance. #ifndef Q_OS_DARWIN QtSingleApplication app(argc, argv); if (app.sendMessage("")) { return 0; } #else QApplication app(argc, argv); #endif app.setOrganizationName("Yubico"); app.setApplicationName("YubiKey Manager"); app.setApplicationDisplayName("YubiKey Manager"); app.setApplicationVersion("0.2.0"); QString app_dir = app.applicationDirPath(); QString main_qml = "/qml/Main.qml"; QString path_prefix; QString url_prefix; if (QFileInfo::exists(":" + main_qml)) { // Embedded resources path_prefix = ":"; url_prefix = "qrc://"; } else if (QFileInfo::exists(app_dir + main_qml)) { // Try relative to executable path_prefix = app_dir; url_prefix = app_dir; } else { //Assume qml/main.qml in cwd. app_dir = "."; path_prefix = "."; url_prefix = "."; } app.setWindowIcon(QIcon(path_prefix + "/images/windowicon.png")); QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("appDir", app_dir); engine.rootContext()->setContextProperty("urlPrefix", url_prefix); qputenv("PYTHONDONTWRITEBYTECODE", "1"); engine.load(QUrl(url_prefix + main_qml)); #ifndef Q_OS_DARWIN // Wake up the root window on a message from new instance. for (auto object : engine.rootObjects()) { if (QWindow *window = qobject_cast<QWindow*>(object)) { QObject::connect(&app, &QtSingleApplication::messageReceived, [window]() { window->show(); window->raise(); window->requestActivate(); }); } } #endif return app.exec(); } <commit_msg>Don't set hardcoded strings.<commit_after>#include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <stdlib.h> #include <QtGlobal> #include <QtWidgets> #ifndef Q_OS_DARWIN #include <QtSingleApplication> #endif int main(int argc, char *argv[]) { #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif // Non Darwin platforms uses QSingleApplication to ensure only one running instance. #ifndef Q_OS_DARWIN QtSingleApplication app(argc, argv); if (app.sendMessage("")) { return 0; } #else QApplication app(argc, argv); #endif QString app_dir = app.applicationDirPath(); QString main_qml = "/qml/Main.qml"; QString path_prefix; QString url_prefix; if (QFileInfo::exists(":" + main_qml)) { // Embedded resources path_prefix = ":"; url_prefix = "qrc://"; } else if (QFileInfo::exists(app_dir + main_qml)) { // Try relative to executable path_prefix = app_dir; url_prefix = app_dir; } else { //Assume qml/main.qml in cwd. app_dir = "."; path_prefix = "."; url_prefix = "."; } app.setWindowIcon(QIcon(path_prefix + "/images/windowicon.png")); QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("appDir", app_dir); engine.rootContext()->setContextProperty("urlPrefix", url_prefix); qputenv("PYTHONDONTWRITEBYTECODE", "1"); engine.load(QUrl(url_prefix + main_qml)); #ifndef Q_OS_DARWIN // Wake up the root window on a message from new instance. for (auto object : engine.rootObjects()) { if (QWindow *window = qobject_cast<QWindow*>(object)) { QObject::connect(&app, &QtSingleApplication::messageReceived, [window]() { window->show(); window->raise(); window->requestActivate(); }); } } #endif return app.exec(); } <|endoftext|>
<commit_before>#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include "numpy/arrayobject.h" #include "part_int.h" #include <set> /*Wraps the flux_extractor into a python module called spectra_priv. Don't call this directly, call the python wrapper.*/ /*Check whether the passed array has type typename. Returns 1 if it doesn't, 0 if it does.*/ int check_type(PyArrayObject * arr, int npy_typename) { return !PyArray_EquivTypes(PyArray_DESCR(arr), PyArray_DescrFromType(npy_typename)); } int check_float(PyArrayObject * arr) { return check_type(arr, NPY_FLOAT); } /* When handed a list of particles, * return a list of bools with True for those nearby to a sightline*/ extern "C" PyObject * Py_near_lines(PyObject *self, PyObject *args) { int NumLos; long long Npart; double box100; PyArrayObject *cofm, *axis, *pos, *hh, *is_a_line; PyObject *out; if(!PyArg_ParseTuple(args, "dO!O!O!O!",&box100, &PyArray_Type, &pos, &PyArray_Type, &hh, &PyArray_Type, &axis, &PyArray_Type, &cofm) ) return NULL; if(2 > PyArray_NDIM(cofm) || 1 > PyArray_NDIM(axis)){ PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } NumLos = PyArray_DIM(cofm,0); Npart = PyArray_DIM(pos,0); if(NumLos != PyArray_DIM(axis,0) || 3 != PyArray_DIM(cofm,1)){ PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } if(check_type(cofm, NPY_DOUBLE) || check_type(axis,NPY_INT)){ PyErr_SetString(PyExc_ValueError, "cofm must have 64-bit float type and axis must be a 32-bit integer\n"); return NULL; } if(check_float(pos) || check_float(hh)){ PyErr_SetString(PyExc_TypeError, "pos and h must have 32-bit float type\n"); return NULL; } //Setup los_tables //PyArray_GETCONTIGUOUS increments the reference count of the object, //so to avoid leaking we need to save the PyArrayObject pointer. cofm = PyArray_GETCONTIGUOUS(cofm); axis = PyArray_GETCONTIGUOUS(axis); double * Cofm =(double *) PyArray_DATA(cofm); int32_t * Axis =(int32_t *) PyArray_DATA(axis); IndexTable sort_los_table(Cofm, Axis, NumLos, box100); //Set of particles near a line std::set<int> near_lines; //find lists //DANGER: potentially huge allocation pos = PyArray_GETCONTIGUOUS(pos); hh = PyArray_GETCONTIGUOUS(hh); const float * Pos =(float *) PyArray_DATA(pos); const float * h = (float *) PyArray_DATA(hh); #pragma omp parallel for for(long long i=0; i < Npart; i++){ std::map<int, double> nearby=sort_los_table.get_near_lines(&(Pos[3*i]),h[i]); if(nearby.size()>0){ #pragma omp critical { near_lines.insert(i); } } } //Copy data into python npy_intp size = near_lines.size(); is_a_line = (PyArrayObject *) PyArray_SimpleNew(1, &size, NPY_INT); int i=0; for (std::set<int>::const_iterator it = near_lines.begin(); it != near_lines.end() && i < size; ++it, ++i){ *(npy_int *)PyArray_GETPTR1(is_a_line,i) = (*it); } out = Py_BuildValue("O", is_a_line); Py_DECREF(is_a_line); //Because PyArray_GETCONTIGUOUS incremented the reference count, //and may have made an allocation, in which case this does not point to what it used to. Py_DECREF(pos); Py_DECREF(hh); Py_DECREF(cofm); Py_DECREF(axis); return out; } /*****************************************************************************/ /*Interface for SPH interpolation*/ extern "C" PyObject * Py_Particle_Interpolation(PyObject *self, PyObject *args) { //Things which should be from input int nbins, NumLos, compute_tau, kernel; long long Npart; double box100, velfac, lambda, gamma, fosc, amumass, atime; npy_intp size[2]; //Input variables in np format PyArrayObject *pos, *vel, *dens, *temp, *h; PyArrayObject *cofm, *axis; //Get our input if(!PyArg_ParseTuple(args, "iiidddddddO!O!O!O!O!O!O!", &compute_tau, &nbins, &kernel, &box100, &velfac, &atime, &lambda, &gamma, &fosc, &amumass, &PyArray_Type, &pos, &PyArray_Type, &vel, &PyArray_Type, &dens, &PyArray_Type, &temp, &PyArray_Type, &h, &PyArray_Type, &axis, &PyArray_Type, &cofm) ) { PyErr_SetString(PyExc_AttributeError, "Incorrect arguments: use compute_tau, nbins, boxsize, velfac, atime, lambda, gamma, fosc, species mass (amu), pos, vel, dens, temp, h, axis, cofm\n"); return NULL; } //Check that our input has the right types if(check_float(pos) || check_float(vel) || check_float(dens) || check_float(temp) || check_float(h)){ PyErr_SetString(PyExc_TypeError, "One of the data arrays does not have 32-bit float type\n"); return NULL; } if(check_type(cofm,NPY_DOUBLE)){ PyErr_SetString(PyExc_TypeError, "Sightline positions must have 64-bit float type\n"); return NULL; } if(check_type(axis, NPY_INT32)){ PyErr_SetString(PyExc_TypeError, "Axis must be a 32-bit integer\n"); return NULL; } NumLos = PyArray_DIM(cofm,0); Npart = PyArray_DIM(pos,0); //Malloc stuff size[0] = NumLos; size[1] = nbins; if(Npart != PyArray_DIM(dens,0) || Npart != PyArray_DIM(h,0)) { PyErr_SetString(PyExc_ValueError, " Dens, pos and h must have the same length\n"); return NULL; } if(NumLos != PyArray_DIM(axis,0) || 3 != PyArray_DIM(cofm,1)) { PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } //Initialise P from the data in the input numpy arrays. //Note: better be sure they are float32 in the calling function. //PyArray_GETCONTIGUOUS increments the reference count of the object, pos = PyArray_GETCONTIGUOUS(pos); dens = PyArray_GETCONTIGUOUS(dens); h = PyArray_GETCONTIGUOUS(h); float * Pos =(float *) PyArray_DATA(pos); float * Hh= (float *) PyArray_DATA(h); float * Dens =(float *) PyArray_DATA(dens); cofm = PyArray_GETCONTIGUOUS(cofm); axis = PyArray_GETCONTIGUOUS(axis); double * Cofm =(double *) PyArray_DATA(cofm); int32_t * Axis =(int32_t *) PyArray_DATA(axis); if( !Pos || !Dens || !Hh || !Cofm || !Axis ){ PyErr_SetString(PyExc_MemoryError, "Getting contiguous copies of input arrays failed\n"); return NULL; } ParticleInterp pint(nbins, lambda, gamma, fosc, amumass, box100, velfac, atime, Cofm, Axis ,NumLos, kernel); PyObject * for_return; /* Allocate array space. This is (I hope) contiguous. * Note: for an array of shape (a,b), element (i,j) can be accessed as * [i*b+j] */ if (compute_tau){ vel = PyArray_GETCONTIGUOUS(vel); temp = PyArray_GETCONTIGUOUS(temp); float * Vel =(float *) PyArray_DATA(vel); float * Temp =(float *) PyArray_DATA(temp); if( !Vel || !Temp ){ PyErr_SetString(PyExc_MemoryError, "Getting contiguous copies of Vel and Temp failed\n"); return NULL; } PyArrayObject * tau_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); double * tau = (double *) PyArray_DATA(tau_out); if ( !tau_out ){ PyErr_SetString(PyExc_MemoryError, "Could not allocate memory for tau\n"); return NULL; } PyArray_FILLWBYTE(tau_out, 0); //Do the work pint.compute_tau(tau, Pos, Vel, Dens, Temp, Hh, Npart); //Build a tuple from the interp struct for_return = Py_BuildValue("O", tau_out); Py_DECREF(tau_out); Py_DECREF(vel); Py_DECREF(temp); } else{ PyArrayObject * colden_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); double * colden = (double *) PyArray_DATA(colden_out); if ( !colden_out ){ PyErr_SetString(PyExc_MemoryError, "Could not allocate memory for colden\n"); return NULL; } //Initialise output arrays to 0. PyArray_FILLWBYTE(colden_out, 0); //Do the work pint.compute_colden(colden, Pos, Dens, Hh, Npart); //Build a tuple from the interp struct for_return = Py_BuildValue("O", colden_out); Py_DECREF(colden_out); } //Because PyArray_GETCONTIGUOUS incremented the reference count, //and may have made an allocation, in which case this does not point to what it used to. Py_DECREF(pos); Py_DECREF(dens); Py_DECREF(h); Py_DECREF(cofm); Py_DECREF(axis); return for_return; } extern "C" PyObject * Py_mean_flux(PyObject *self, PyObject *args) { PyArrayObject *Tau; double mean_flux_desired, tol; int nbins; if(!PyArg_ParseTuple(args, "O!did", &PyArray_Type,&Tau, &mean_flux_desired, &nbins, &tol) ) { PyErr_SetString(PyExc_AttributeError, "Incorrect arguments: use tau (array), mean_flux_desired (double), nbins (int), tol (double)\n"); return NULL; } Tau = PyArray_GETCONTIGUOUS(Tau); double * tau =(double *) PyArray_DATA(Tau); double mean_flux; double tau_mean_flux; double scale, newscale=100; double des_flux_bins=mean_flux_desired*nbins; do { int i; scale=newscale; mean_flux=0; tau_mean_flux=0; for(i=0; i< nbins; i++) { double temp=exp(-scale*tau[i]); mean_flux+=temp; tau_mean_flux+=temp*tau[i]; } newscale=scale+(mean_flux-des_flux_bins)/tau_mean_flux; /*We don't want the absorption to change sign and become emission; * 0 is too far. */ if(newscale < 0) newscale=0; }while(fabs(newscale-scale) > tol*newscale); Py_DECREF(Tau); return Py_BuildValue("d",newscale); } static PyMethodDef spectrae[] = { {"_Particle_Interpolate", Py_Particle_Interpolation, METH_VARARGS, "Find absorption or column density by interpolating particles. " " Arguments: compute_tau nbins, boxsize, velfac, atime, lambda, gamma, fosc, species mass (amu), pos, vel, dens, temp, h, axis, cofm" " "}, {"_near_lines", Py_near_lines,METH_VARARGS, "Give a list of particles and sightlines, " "return a list of booleans for those particles near " "a sightline." " Arguments: box, pos, h, axis, cofm"}, {"_rescale_mean_flux",Py_mean_flux,METH_VARARGS, "Compute the scale factor for spectra to have the desired mean flux." ""}, {NULL, NULL, 0, NULL}, }; //Python 3 changed the module initialisation. #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_spectra_priv", /* m_name */ "C functions for accelerating spectral work", /* m_doc */ -1, /* m_size */ spectrae, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif static PyObject * moduleinit(void) { PyObject *m; #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); import_array(); #else m = Py_InitModule3("_spectra_priv",spectrae, "C functions for accelerating spectral work"); _import_array(); #endif if (m == NULL) return NULL; return m; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC init_spectra_priv(void) { moduleinit(); } #else PyMODINIT_FUNC PyInit__spectra_priv(void) { return moduleinit(); } #endif <commit_msg>Speed up the C mean flux rescaling<commit_after>#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include "numpy/arrayobject.h" #include "part_int.h" #include <set> /*Wraps the flux_extractor into a python module called spectra_priv. Don't call this directly, call the python wrapper.*/ /*Check whether the passed array has type typename. Returns 1 if it doesn't, 0 if it does.*/ int check_type(PyArrayObject * arr, int npy_typename) { return !PyArray_EquivTypes(PyArray_DESCR(arr), PyArray_DescrFromType(npy_typename)); } int check_float(PyArrayObject * arr) { return check_type(arr, NPY_FLOAT); } /* When handed a list of particles, * return a list of bools with True for those nearby to a sightline*/ extern "C" PyObject * Py_near_lines(PyObject *self, PyObject *args) { int NumLos; long long Npart; double box100; PyArrayObject *cofm, *axis, *pos, *hh, *is_a_line; PyObject *out; if(!PyArg_ParseTuple(args, "dO!O!O!O!",&box100, &PyArray_Type, &pos, &PyArray_Type, &hh, &PyArray_Type, &axis, &PyArray_Type, &cofm) ) return NULL; if(2 > PyArray_NDIM(cofm) || 1 > PyArray_NDIM(axis)){ PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } NumLos = PyArray_DIM(cofm,0); Npart = PyArray_DIM(pos,0); if(NumLos != PyArray_DIM(axis,0) || 3 != PyArray_DIM(cofm,1)){ PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } if(check_type(cofm, NPY_DOUBLE) || check_type(axis,NPY_INT)){ PyErr_SetString(PyExc_ValueError, "cofm must have 64-bit float type and axis must be a 32-bit integer\n"); return NULL; } if(check_float(pos) || check_float(hh)){ PyErr_SetString(PyExc_TypeError, "pos and h must have 32-bit float type\n"); return NULL; } //Setup los_tables //PyArray_GETCONTIGUOUS increments the reference count of the object, //so to avoid leaking we need to save the PyArrayObject pointer. cofm = PyArray_GETCONTIGUOUS(cofm); axis = PyArray_GETCONTIGUOUS(axis); double * Cofm =(double *) PyArray_DATA(cofm); int32_t * Axis =(int32_t *) PyArray_DATA(axis); IndexTable sort_los_table(Cofm, Axis, NumLos, box100); //Set of particles near a line std::set<int> near_lines; //find lists //DANGER: potentially huge allocation pos = PyArray_GETCONTIGUOUS(pos); hh = PyArray_GETCONTIGUOUS(hh); const float * Pos =(float *) PyArray_DATA(pos); const float * h = (float *) PyArray_DATA(hh); #pragma omp parallel for for(long long i=0; i < Npart; i++){ std::map<int, double> nearby=sort_los_table.get_near_lines(&(Pos[3*i]),h[i]); if(nearby.size()>0){ #pragma omp critical { near_lines.insert(i); } } } //Copy data into python npy_intp size = near_lines.size(); is_a_line = (PyArrayObject *) PyArray_SimpleNew(1, &size, NPY_INT); int i=0; for (std::set<int>::const_iterator it = near_lines.begin(); it != near_lines.end() && i < size; ++it, ++i){ *(npy_int *)PyArray_GETPTR1(is_a_line,i) = (*it); } out = Py_BuildValue("O", is_a_line); Py_DECREF(is_a_line); //Because PyArray_GETCONTIGUOUS incremented the reference count, //and may have made an allocation, in which case this does not point to what it used to. Py_DECREF(pos); Py_DECREF(hh); Py_DECREF(cofm); Py_DECREF(axis); return out; } /*****************************************************************************/ /*Interface for SPH interpolation*/ extern "C" PyObject * Py_Particle_Interpolation(PyObject *self, PyObject *args) { //Things which should be from input int nbins, NumLos, compute_tau, kernel; long long Npart; double box100, velfac, lambda, gamma, fosc, amumass, atime; npy_intp size[2]; //Input variables in np format PyArrayObject *pos, *vel, *dens, *temp, *h; PyArrayObject *cofm, *axis; //Get our input if(!PyArg_ParseTuple(args, "iiidddddddO!O!O!O!O!O!O!", &compute_tau, &nbins, &kernel, &box100, &velfac, &atime, &lambda, &gamma, &fosc, &amumass, &PyArray_Type, &pos, &PyArray_Type, &vel, &PyArray_Type, &dens, &PyArray_Type, &temp, &PyArray_Type, &h, &PyArray_Type, &axis, &PyArray_Type, &cofm) ) { PyErr_SetString(PyExc_AttributeError, "Incorrect arguments: use compute_tau, nbins, boxsize, velfac, atime, lambda, gamma, fosc, species mass (amu), pos, vel, dens, temp, h, axis, cofm\n"); return NULL; } //Check that our input has the right types if(check_float(pos) || check_float(vel) || check_float(dens) || check_float(temp) || check_float(h)){ PyErr_SetString(PyExc_TypeError, "One of the data arrays does not have 32-bit float type\n"); return NULL; } if(check_type(cofm,NPY_DOUBLE)){ PyErr_SetString(PyExc_TypeError, "Sightline positions must have 64-bit float type\n"); return NULL; } if(check_type(axis, NPY_INT32)){ PyErr_SetString(PyExc_TypeError, "Axis must be a 32-bit integer\n"); return NULL; } NumLos = PyArray_DIM(cofm,0); Npart = PyArray_DIM(pos,0); //Malloc stuff size[0] = NumLos; size[1] = nbins; if(Npart != PyArray_DIM(dens,0) || Npart != PyArray_DIM(h,0)) { PyErr_SetString(PyExc_ValueError, " Dens, pos and h must have the same length\n"); return NULL; } if(NumLos != PyArray_DIM(axis,0) || 3 != PyArray_DIM(cofm,1)) { PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } //Initialise P from the data in the input numpy arrays. //Note: better be sure they are float32 in the calling function. //PyArray_GETCONTIGUOUS increments the reference count of the object, pos = PyArray_GETCONTIGUOUS(pos); dens = PyArray_GETCONTIGUOUS(dens); h = PyArray_GETCONTIGUOUS(h); float * Pos =(float *) PyArray_DATA(pos); float * Hh= (float *) PyArray_DATA(h); float * Dens =(float *) PyArray_DATA(dens); cofm = PyArray_GETCONTIGUOUS(cofm); axis = PyArray_GETCONTIGUOUS(axis); double * Cofm =(double *) PyArray_DATA(cofm); int32_t * Axis =(int32_t *) PyArray_DATA(axis); if( !Pos || !Dens || !Hh || !Cofm || !Axis ){ PyErr_SetString(PyExc_MemoryError, "Getting contiguous copies of input arrays failed\n"); return NULL; } ParticleInterp pint(nbins, lambda, gamma, fosc, amumass, box100, velfac, atime, Cofm, Axis ,NumLos, kernel); PyObject * for_return; /* Allocate array space. This is (I hope) contiguous. * Note: for an array of shape (a,b), element (i,j) can be accessed as * [i*b+j] */ if (compute_tau){ vel = PyArray_GETCONTIGUOUS(vel); temp = PyArray_GETCONTIGUOUS(temp); float * Vel =(float *) PyArray_DATA(vel); float * Temp =(float *) PyArray_DATA(temp); if( !Vel || !Temp ){ PyErr_SetString(PyExc_MemoryError, "Getting contiguous copies of Vel and Temp failed\n"); return NULL; } PyArrayObject * tau_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); double * tau = (double *) PyArray_DATA(tau_out); if ( !tau_out ){ PyErr_SetString(PyExc_MemoryError, "Could not allocate memory for tau\n"); return NULL; } PyArray_FILLWBYTE(tau_out, 0); //Do the work pint.compute_tau(tau, Pos, Vel, Dens, Temp, Hh, Npart); //Build a tuple from the interp struct for_return = Py_BuildValue("O", tau_out); Py_DECREF(tau_out); Py_DECREF(vel); Py_DECREF(temp); } else{ PyArrayObject * colden_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); double * colden = (double *) PyArray_DATA(colden_out); if ( !colden_out ){ PyErr_SetString(PyExc_MemoryError, "Could not allocate memory for colden\n"); return NULL; } //Initialise output arrays to 0. PyArray_FILLWBYTE(colden_out, 0); //Do the work pint.compute_colden(colden, Pos, Dens, Hh, Npart); //Build a tuple from the interp struct for_return = Py_BuildValue("O", colden_out); Py_DECREF(colden_out); } //Because PyArray_GETCONTIGUOUS incremented the reference count, //and may have made an allocation, in which case this does not point to what it used to. Py_DECREF(pos); Py_DECREF(dens); Py_DECREF(h); Py_DECREF(cofm); Py_DECREF(axis); return for_return; } extern "C" PyObject * Py_mean_flux(PyObject *self, PyObject *args) { PyArrayObject *Tau; double mean_flux_desired, tol; int nbins; if(!PyArg_ParseTuple(args, "O!did", &PyArray_Type,&Tau, &mean_flux_desired, &nbins, &tol) ) { PyErr_SetString(PyExc_AttributeError, "Incorrect arguments: use tau (array), mean_flux_desired (double), nbins (int), tol (double)\n"); return NULL; } Tau = PyArray_GETCONTIGUOUS(Tau); const double * tau =(double *) PyArray_DATA(Tau); const double des_flux_bins=mean_flux_desired*nbins; double scale, newscale=1; do { scale=newscale; double mean_flux=0; double tau_mean_flux=0; #pragma omp parallel for for(int i=0; i< nbins; i++) { const double temp=exp(-scale*tau[i]); mean_flux+=temp; tau_mean_flux+=temp*tau[i]; } /*Newton-Raphson*/ newscale=scale+(mean_flux-des_flux_bins)/tau_mean_flux; /*We don't want the absorption to change sign and become emission; * 0 is too far. */ if(newscale <= 0) { newscale=1e-10; } }while(fabs(newscale-scale) > tol*newscale); Py_DECREF(Tau); return Py_BuildValue("d",newscale); } static PyMethodDef spectrae[] = { {"_Particle_Interpolate", Py_Particle_Interpolation, METH_VARARGS, "Find absorption or column density by interpolating particles. " " Arguments: compute_tau nbins, boxsize, velfac, atime, lambda, gamma, fosc, species mass (amu), pos, vel, dens, temp, h, axis, cofm" " "}, {"_near_lines", Py_near_lines,METH_VARARGS, "Give a list of particles and sightlines, " "return a list of booleans for those particles near " "a sightline." " Arguments: box, pos, h, axis, cofm"}, {"_rescale_mean_flux",Py_mean_flux,METH_VARARGS, "Compute the scale factor for spectra to have the desired mean flux." ""}, {NULL, NULL, 0, NULL}, }; //Python 3 changed the module initialisation. #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_spectra_priv", /* m_name */ "C functions for accelerating spectral work", /* m_doc */ -1, /* m_size */ spectrae, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif static PyObject * moduleinit(void) { PyObject *m; #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); import_array(); #else m = Py_InitModule3("_spectra_priv",spectrae, "C functions for accelerating spectral work"); _import_array(); #endif if (m == NULL) return NULL; return m; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC init_spectra_priv(void) { moduleinit(); } #else PyMODINIT_FUNC PyInit__spectra_priv(void) { return moduleinit(); } #endif <|endoftext|>
<commit_before>/****************************************************** * This is the main file for the mips1 ArchC model * * This file is automatically generated by ArchC * * WITHOUT WARRANTY OF ANY KIND, either express * * or implied. * * For more information on ArchC, please visit: * * http://www.archc.org * * * * The ArchC Team * * Computer Systems Laboratory (LSC) * * IC-UNICAMP * * http://www.lsc.ic.unicamp.br * ******************************************************/ // Rodolfo editou aqui // const char *project_name="mips1"; const char *project_file="mips1.ac"; const char *archc_version="2.0beta1"; const char *archc_options="-abi -dy "; #include <systemc.h> #include "mips1.H" #include "ac_tlm_mem.h" #include "bus.h" using user::ac_tlm_mem; using user::bus; int sc_main(int ac, char *av[]) { //! ISA simulator mips1 mips1_proc1("mips1"); //mips1 mips1_proc2("mips2"); ac_tlm_mem mem("mem"); bus membus("bus"); #ifdef AC_DEBUG ac_trace("mips1_proc1.trace"); //ac_trace("mips1_proc2.trace"); #endif for (int i = 0; i<ac; i++) { printf("AV%d = %s\n", i, av[i]); } mips1_proc1.DM_port(membus.target_export[0]); //mips1_proc2.DM_port(membus.target_export[1]); membus.DM_port(mem.target_export); char aux[100]; strcpy(aux, av[1]); mips1_proc1.init(ac, av); cerr << endl; strcpy(av[1],aux); for (int i = 0; i<ac; i++) { printf("AV%d = %s\n", i, av[i]); } //mips1_proc2.init(ac, av); cerr << endl; sc_start(); //mips1_proc1.PrintStat(); cerr << endl; //mips1_proc2.PrintStat(); cerr << endl; #ifdef AC_STATS mips1_proc1.ac_sim_stats.time = sc_simulation_time(); mips1_proc1.ac_sim_stats.print(); //mips1_proc2.ac_sim_stats.time = sc_simulation_time(); //mips1_proc2.ac_sim_stats.print(); #endif #ifdef AC_DEBUG ac_close_trace(); #endif return mips1_proc1.ac_exit_status; } <commit_msg>2nd processor initiates in STOP state<commit_after>/****************************************************** * This is the main file for the mips1 ArchC model * * This file is automatically generated by ArchC * * WITHOUT WARRANTY OF ANY KIND, either express * * or implied. * * For more information on ArchC, please visit: * * http://www.archc.org * * * * The ArchC Team * * Computer Systems Laboratory (LSC) * * IC-UNICAMP * * http://www.lsc.ic.unicamp.br * ******************************************************/ // Rodolfo editou aqui // const char *project_name="mips1"; const char *project_file="mips1.ac"; const char *archc_version="2.0beta1"; const char *archc_options="-abi -dy "; #include <systemc.h> #include "mips1.H" #include "ac_tlm_mem.h" #include "bus.h" using user::ac_tlm_mem; using user::bus; int sc_main(int ac, char *av[]) { //! ISA simulator mips1 mips1_proc1("mips1"); mips1 mips1_proc2("mips2"); ac_tlm_mem mem("mem"); bus membus("bus"); #ifdef AC_DEBUG ac_trace("mips1_proc1.trace"); ac_trace("mips1_proc2.trace"); #endif mips1_proc1.DM_port(membus.target_export[0]); mips1_proc2.DM_port(membus.target_export[1]); membus.DM_port(mem.target_export); char av1[128]; strcpy(av1, av[1]); mips1_proc1.init(ac, av); cerr << endl; strcpy(av[1],av1); mips1_proc2.init(ac, av); mips1_proc2.ac_stop_flag = 1; mips1_proc2.ac_wait_sig = 0; cerr << endl; sc_start(); mips1_proc1.PrintStat(); cerr << endl; mips1_proc2.PrintStat(); cerr << endl; #ifdef AC_STATS mips1_proc1.ac_sim_stats.time = sc_simulation_time(); mips1_proc1.ac_sim_stats.print(); mips1_proc2.ac_sim_stats.time = sc_simulation_time(); mips1_proc2.ac_sim_stats.print(); #endif #ifdef AC_DEBUG ac_close_trace(); #endif return mips1_proc1.ac_exit_status; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2015 Stefan Tröger <stefantroeger@gmx.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <QMessageBox> #include <QMenu> #endif #include "ViewProviderLoft.h" //#include "TaskLoftParameters.h" #include "TaskLoftParameters.h" #include <Mod/PartDesign/App/Body.h> #include <Mod/PartDesign/App/FeatureLoft.h> #include <Mod/Sketcher/App/SketchObject.h> #include <Gui/Control.h> #include <Gui/Command.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <TopExp.hxx> #include <TopTools_IndexedMapOfShape.hxx> using namespace PartDesignGui; PROPERTY_SOURCE(PartDesignGui::ViewProviderLoft,PartDesignGui::ViewProvider) ViewProviderLoft::ViewProviderLoft() { } ViewProviderLoft::~ViewProviderLoft() { } std::vector<App::DocumentObject*> ViewProviderLoft::claimChildren(void)const { std::vector<App::DocumentObject*> temp; PartDesign::Loft* pcLoft = static_cast<PartDesign::Loft*>(getObject()); App::DocumentObject* sketch = pcLoft->getVerifiedSketch(true); if (sketch != NULL) temp.push_back(sketch); for(App::DocumentObject* obj : pcLoft->Sections.getValues()) { if (obj != NULL) temp.push_back(obj); } return temp; } void ViewProviderLoft::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { QAction* act; act = menu->addAction(QObject::tr("Edit loft"), receiver, member); act->setData(QVariant((int)ViewProvider::Default)); } bool ViewProviderLoft::doubleClicked(void) { Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().setEdit('%s',0)",this->pcObject->getNameInDocument()); return true; } bool ViewProviderLoft::setEdit(int ModNum) { if (ModNum == ViewProvider::Default) setPreviewDisplayMode(true); return ViewProviderAddSub::setEdit(ModNum); } TaskDlgFeatureParameters* ViewProviderLoft::getEditDialog() { return new TaskDlgLoftParameters(this); } void ViewProviderLoft::unsetEdit(int ModNum) { setPreviewDisplayMode(false); ViewProviderAddSub::unsetEdit(ModNum); } bool ViewProviderLoft::onDelete(const std::vector<std::string> & /*s*/) {/* PartDesign::Loft* pcLoft = static_cast<PartDesign::Loft*>(getObject()); // get the Sketch Sketcher::SketchObject *pcSketch = 0; if (pcLoft->Sketch.getValue()) pcSketch = static_cast<Sketcher::SketchObject*>(pcLoft->Sketch.getValue()); // if abort command deleted the object the sketch is visible again if (pcSketch && Gui::Application::Instance->getViewProvider(pcSketch)) Gui::Application::Instance->getViewProvider(pcSketch)->show(); return ViewProvider::onDelete(s);*/ return true; } void ViewProviderLoft::highlightReferences(const bool /*on*/, bool /*auxillery*/) {/* PartDesign::Loft* pcLoft = static_cast<PartDesign::Loft*>(getObject()); Part::Feature* base; if(!auxillery) base = static_cast<Part::Feature*>(pcLoft->Spine.getValue()); else base = static_cast<Part::Feature*>(pcLoft->AuxillerySpine.getValue()); if (base == NULL) return; PartGui::ViewProviderPart* svp = dynamic_cast<PartGui::ViewProviderPart*>( Gui::Application::Instance->getViewProvider(base)); if (svp == NULL) return; std::vector<std::string> edges; if(!auxillery) edges = pcLoft->Spine.getSubValuesStartsWith("Edge"); else edges = pcLoft->AuxillerySpine.getSubValuesStartsWith("Edge"); if (on) { if (!edges.empty() && originalLineColors.empty()) { TopTools_IndexedMapOfShape eMap; TopExp::MapShapes(base->Shape.getValue(), TopAbs_EDGE, eMap); originalLineColors = svp->LineColorArray.getValues(); std::vector<App::Color> colors = originalLineColors; colors.resize(eMap.Extent(), svp->LineColor.getValue()); for (std::string e : edges) { int idx = atoi(e.substr(4).c_str()) - 1; if (idx < colors.size()) colors[idx] = App::Color(1.0,0.0,1.0); // magenta } svp->LineColorArray.setValues(colors); } } else { if (!edges.empty() && !originalLineColors.empty()) { svp->LineColorArray.setValues(originalLineColors); originalLineColors.clear(); } }*/ } QIcon ViewProviderLoft::getIcon(void) const { QString str = QString::fromLatin1("PartDesign_"); auto* prim = static_cast<PartDesign::Loft*>(getObject()); if(prim->getAddSubType() == PartDesign::FeatureAddSub::Additive) str += QString::fromLatin1("Additive_"); else str += QString::fromLatin1("Subtractive_"); str += QString::fromLatin1("Loft.svg"); return Gui::BitmapFactory().pixmap(str.toStdString().c_str()); } <commit_msg>PDN: Fix Loft claimChildren to only grab sketches<commit_after>/*************************************************************************** * Copyright (c) 2015 Stefan Tröger <stefantroeger@gmx.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <QMessageBox> #include <QMenu> #endif #include "ViewProviderLoft.h" //#include "TaskLoftParameters.h" #include "TaskLoftParameters.h" #include <Mod/PartDesign/App/Body.h> #include <Mod/PartDesign/App/FeatureLoft.h> #include <Mod/Sketcher/App/SketchObject.h> #include <Gui/Control.h> #include <Gui/Command.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <TopExp.hxx> #include <TopTools_IndexedMapOfShape.hxx> using namespace PartDesignGui; PROPERTY_SOURCE(PartDesignGui::ViewProviderLoft,PartDesignGui::ViewProvider) ViewProviderLoft::ViewProviderLoft() { } ViewProviderLoft::~ViewProviderLoft() { } std::vector<App::DocumentObject*> ViewProviderLoft::claimChildren(void)const { std::vector<App::DocumentObject*> temp; PartDesign::Loft* pcLoft = static_cast<PartDesign::Loft*>(getObject()); App::DocumentObject* sketch = pcLoft->getVerifiedSketch(true); if (sketch != NULL) temp.push_back(sketch); for(App::DocumentObject* obj : pcLoft->Sections.getValues()) { if (obj != NULL && obj->isDerivedFrom(Part::Part2DObject::getClassTypeId())) temp.push_back(obj); } return temp; } void ViewProviderLoft::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { QAction* act; act = menu->addAction(QObject::tr("Edit loft"), receiver, member); act->setData(QVariant((int)ViewProvider::Default)); } bool ViewProviderLoft::doubleClicked(void) { Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().setEdit('%s',0)",this->pcObject->getNameInDocument()); return true; } bool ViewProviderLoft::setEdit(int ModNum) { if (ModNum == ViewProvider::Default) setPreviewDisplayMode(true); return ViewProviderAddSub::setEdit(ModNum); } TaskDlgFeatureParameters* ViewProviderLoft::getEditDialog() { return new TaskDlgLoftParameters(this); } void ViewProviderLoft::unsetEdit(int ModNum) { setPreviewDisplayMode(false); ViewProviderAddSub::unsetEdit(ModNum); } bool ViewProviderLoft::onDelete(const std::vector<std::string> & /*s*/) {/* PartDesign::Loft* pcLoft = static_cast<PartDesign::Loft*>(getObject()); // get the Sketch Sketcher::SketchObject *pcSketch = 0; if (pcLoft->Sketch.getValue()) pcSketch = static_cast<Sketcher::SketchObject*>(pcLoft->Sketch.getValue()); // if abort command deleted the object the sketch is visible again if (pcSketch && Gui::Application::Instance->getViewProvider(pcSketch)) Gui::Application::Instance->getViewProvider(pcSketch)->show(); return ViewProvider::onDelete(s);*/ return true; } void ViewProviderLoft::highlightReferences(const bool /*on*/, bool /*auxillery*/) {/* PartDesign::Loft* pcLoft = static_cast<PartDesign::Loft*>(getObject()); Part::Feature* base; if(!auxillery) base = static_cast<Part::Feature*>(pcLoft->Spine.getValue()); else base = static_cast<Part::Feature*>(pcLoft->AuxillerySpine.getValue()); if (base == NULL) return; PartGui::ViewProviderPart* svp = dynamic_cast<PartGui::ViewProviderPart*>( Gui::Application::Instance->getViewProvider(base)); if (svp == NULL) return; std::vector<std::string> edges; if(!auxillery) edges = pcLoft->Spine.getSubValuesStartsWith("Edge"); else edges = pcLoft->AuxillerySpine.getSubValuesStartsWith("Edge"); if (on) { if (!edges.empty() && originalLineColors.empty()) { TopTools_IndexedMapOfShape eMap; TopExp::MapShapes(base->Shape.getValue(), TopAbs_EDGE, eMap); originalLineColors = svp->LineColorArray.getValues(); std::vector<App::Color> colors = originalLineColors; colors.resize(eMap.Extent(), svp->LineColor.getValue()); for (std::string e : edges) { int idx = atoi(e.substr(4).c_str()) - 1; if (idx < colors.size()) colors[idx] = App::Color(1.0,0.0,1.0); // magenta } svp->LineColorArray.setValues(colors); } } else { if (!edges.empty() && !originalLineColors.empty()) { svp->LineColorArray.setValues(originalLineColors); originalLineColors.clear(); } }*/ } QIcon ViewProviderLoft::getIcon(void) const { QString str = QString::fromLatin1("PartDesign_"); auto* prim = static_cast<PartDesign::Loft*>(getObject()); if(prim->getAddSubType() == PartDesign::FeatureAddSub::Additive) str += QString::fromLatin1("Additive_"); else str += QString::fromLatin1("Subtractive_"); str += QString::fromLatin1("Loft.svg"); return Gui::BitmapFactory().pixmap(str.toStdString().c_str()); } <|endoftext|>
<commit_before>#include <ecl/thread/thread.hpp> #include <CppUTest/TestHarness.h> #include <CppUTest/CommandLineTestRunner.h> #include <cstring> #include <thread> // Error code helper // TODO: move it to 'utils' headers and protect with check of // current test state (enabled or disabled) static SimpleString StringFrom(ecl::err err) { return SimpleString{ecl::err_to_str(err)}; } //------------------------------------------------------------------------------ // Native thread in not started state tests static int dummy_ctx = 0; static ecl::err dummy_routine(void *arg) { (void) arg; return ecl::err::ok; } static char name[16] = {0}; static ssize_t name_size; TEST_GROUP(not_started_native_thread) { void setup() { memset(name, 0, sizeof(name)); name_size = 0; } void teardown() { } }; TEST(not_started_native_thread, get_name_test) { ecl::native_thread tr; name_size = tr.get_name(name, sizeof(name)); CHECK_EQUAL(0, name_size); STRCMP_EQUAL("", name); } TEST(not_started_native_thread, set_name_test) { ecl::native_thread tr; const char new_name[] = "cool_thread"; auto rc = tr.set_name(new_name); CHECK_EQUAL(ecl::err::ok, rc); name_size = tr.get_name(name, sizeof(name)); CHECK_EQUAL(sizeof(new_name) - 1, name_size); STRCMP_EQUAL(new_name, name); } TEST(not_started_native_thread, set_stack_size) { ecl::native_thread tr; auto rc = tr.set_stack_size(1024); CHECK_EQUAL(ecl::err::ok, rc); } TEST(not_started_native_thread, set_routine) { ecl::native_thread tr; auto rc = tr.set_routine(dummy_routine, nullptr); CHECK_EQUAL(ecl::err::ok, rc); rc = tr.set_routine(dummy_routine, &dummy_ctx); CHECK_EQUAL(ecl::err::ok, rc); } TEST(not_started_native_thread, join) { ecl::native_thread tr; ecl::err dummy_retval; auto rc = tr.join(dummy_retval); CHECK_EQUAL(ecl::err::srch, rc); rc = tr.join(); CHECK_EQUAL(ecl::err::srch, rc); } TEST(not_started_native_thread, detach) { ecl::native_thread tr; auto rc = tr.detach(); CHECK_EQUAL(ecl::err::srch, rc); } //------------------------------------------------------------------------------ struct test_arg { ecl::semaphore sem; bool started; bool completed; ecl::err required_retval; }; static test_arg routine_arg; static ecl::err test_routine(void *arg) { CHECK_EQUAL(&routine_arg, arg); test_arg *targ = reinterpret_cast< test_arg * >(arg); targ->started = true; targ->sem.wait(); targ->completed = true; return targ->required_retval; } static ecl::native_thread started_tr; static bool started_tr_joined_or_detached; TEST_GROUP(started_native_thread) { void setup() { memset(name, 0, sizeof(name)); name_size = 0; // Set unusual error code routine_arg.required_retval = ecl::err::loop; // Thread shoulnd't be joined by default started_tr_joined_or_detached = false; auto rc = started_tr.set_routine(test_routine, reinterpret_cast< void* >(&routine_arg)); CHECK_EQUAL(ecl::err::ok, rc); rc = started_tr.start(); CHECK_EQUAL(ecl::err::ok, rc); // TODO: might be useful to add here some delay CHECK_EQUAL(true, routine_arg.started); // Thread shouldn't complete by itself CHECK_EQUAL(false, routine_arg.completed); } void teardown() { if (!started_tr_joined_or_detached) { routine_arg.sem.signal(); auto rc = started_tr.join(); CHECK_EQUAL(ecl::err::ok, rc); CHECK_EQUAL(true, routine_arg.completed); } // Reset name and state routine_arg.started = false; routine_arg.completed = false; started_tr.set_name(""); } }; TEST(started_native_thread, basic) { // Thread in this test just starts and finishes. // See setup()/teardown() section } TEST(started_native_thread, get_name_test) { name_size = started_tr.get_name(name, sizeof(name)); CHECK_EQUAL(0, name_size); STRCMP_EQUAL("", name); } TEST(started_native_thread, set_name_test) { const char new_name[] = "cool_thread"; auto rc = started_tr.set_name(new_name); CHECK_EQUAL(ecl::err::ok, rc); name_size = started_tr.get_name(name, sizeof(name)); CHECK_EQUAL(sizeof(new_name) - 1, name_size); STRCMP_EQUAL(new_name, name); } TEST(started_native_thread, join_with_parameter) { routine_arg.sem.signal(); ecl::err thread_retval; auto rc = started_tr.join(thread_retval); CHECK_EQUAL(ecl::err::ok, rc); CHECK_EQUAL(true, routine_arg.completed); CHECK_EQUAL(routine_arg.required_retval, thread_retval); // Notify shutdown routine that thread already joined started_tr_joined_or_detached = true; } //------------------------------------------------------------------------------ // TODO: state of detached thread cannot be restored back to the initial state // more tests in detached mode will require additional routine that // will return new thread or allocate new thread in heap and delete it // after test finishes static ecl::native_thread detached_tr; TEST_GROUP(detached_native_thread) { void setup() { auto rc = detached_tr.set_routine(test_routine, reinterpret_cast< void* >(&routine_arg)); CHECK_EQUAL(ecl::err::ok, rc); rc = detached_tr.start(); CHECK_EQUAL(ecl::err::ok, rc); // TODO: might be useful to add here some delay CHECK_EQUAL(true, routine_arg.started); // Thread shouldn't complete by itself CHECK_EQUAL(false, routine_arg.completed); rc = detached_tr.detach(); CHECK_EQUAL(ecl::err::ok, rc); } void teardown() { // Reset state routine_arg.started = false; routine_arg.completed = false; } }; TEST(detached_native_thread, basic) { // Let thread go routine_arg.sem.signal(); // Some time is requried to let thread finish std::this_thread::sleep_for(std::chrono::milliseconds(100)); CHECK_EQUAL(true, routine_arg.completed); } //------------------------------------------------------------------------------ int main(int argc, char *argv[]) { return CommandLineTestRunner::RunAllTests(argc, argv); } <commit_msg>>#145 Add small delay to thread unit to avoid race condition<commit_after>#include <ecl/thread/thread.hpp> #include <CppUTest/TestHarness.h> #include <CppUTest/CommandLineTestRunner.h> #include <cstring> #include <thread> // Error code helper // TODO: move it to 'utils' headers and protect with check of // current test state (enabled or disabled) static SimpleString StringFrom(ecl::err err) { return SimpleString{ecl::err_to_str(err)}; } //------------------------------------------------------------------------------ // Native thread in not started state tests static int dummy_ctx = 0; static ecl::err dummy_routine(void *arg) { (void) arg; return ecl::err::ok; } static char name[16] = {0}; static ssize_t name_size; TEST_GROUP(not_started_native_thread) { void setup() { memset(name, 0, sizeof(name)); name_size = 0; } void teardown() { } }; TEST(not_started_native_thread, get_name_test) { ecl::native_thread tr; name_size = tr.get_name(name, sizeof(name)); CHECK_EQUAL(0, name_size); STRCMP_EQUAL("", name); } TEST(not_started_native_thread, set_name_test) { ecl::native_thread tr; const char new_name[] = "cool_thread"; auto rc = tr.set_name(new_name); CHECK_EQUAL(ecl::err::ok, rc); name_size = tr.get_name(name, sizeof(name)); CHECK_EQUAL(sizeof(new_name) - 1, name_size); STRCMP_EQUAL(new_name, name); } TEST(not_started_native_thread, set_stack_size) { ecl::native_thread tr; auto rc = tr.set_stack_size(1024); CHECK_EQUAL(ecl::err::ok, rc); } TEST(not_started_native_thread, set_routine) { ecl::native_thread tr; auto rc = tr.set_routine(dummy_routine, nullptr); CHECK_EQUAL(ecl::err::ok, rc); rc = tr.set_routine(dummy_routine, &dummy_ctx); CHECK_EQUAL(ecl::err::ok, rc); } TEST(not_started_native_thread, join) { ecl::native_thread tr; ecl::err dummy_retval; auto rc = tr.join(dummy_retval); CHECK_EQUAL(ecl::err::srch, rc); rc = tr.join(); CHECK_EQUAL(ecl::err::srch, rc); } TEST(not_started_native_thread, detach) { ecl::native_thread tr; auto rc = tr.detach(); CHECK_EQUAL(ecl::err::srch, rc); } //------------------------------------------------------------------------------ struct test_arg { ecl::semaphore sem; bool started; bool completed; ecl::err required_retval; }; static test_arg routine_arg; static ecl::err test_routine(void *arg) { CHECK_EQUAL(&routine_arg, arg); test_arg *targ = reinterpret_cast< test_arg * >(arg); targ->started = true; targ->sem.wait(); targ->completed = true; return targ->required_retval; } static ecl::native_thread started_tr; static bool started_tr_joined_or_detached; TEST_GROUP(started_native_thread) { void setup() { memset(name, 0, sizeof(name)); name_size = 0; // Set unusual error code routine_arg.required_retval = ecl::err::loop; // Thread shoulnd't be joined by default started_tr_joined_or_detached = false; auto rc = started_tr.set_routine(test_routine, reinterpret_cast< void* >(&routine_arg)); CHECK_EQUAL(ecl::err::ok, rc); rc = started_tr.start(); CHECK_EQUAL(ecl::err::ok, rc); std::this_thread::sleep_for(std::chrono::milliseconds(5)); CHECK_EQUAL(true, routine_arg.started); // Thread shouldn't complete by itself CHECK_EQUAL(false, routine_arg.completed); } void teardown() { if (!started_tr_joined_or_detached) { routine_arg.sem.signal(); auto rc = started_tr.join(); CHECK_EQUAL(ecl::err::ok, rc); CHECK_EQUAL(true, routine_arg.completed); } // Reset name and state routine_arg.started = false; routine_arg.completed = false; started_tr.set_name(""); } }; TEST(started_native_thread, basic) { // Thread in this test just starts and finishes. // See setup()/teardown() section } TEST(started_native_thread, get_name_test) { name_size = started_tr.get_name(name, sizeof(name)); CHECK_EQUAL(0, name_size); STRCMP_EQUAL("", name); } TEST(started_native_thread, set_name_test) { const char new_name[] = "cool_thread"; auto rc = started_tr.set_name(new_name); CHECK_EQUAL(ecl::err::ok, rc); name_size = started_tr.get_name(name, sizeof(name)); CHECK_EQUAL(sizeof(new_name) - 1, name_size); STRCMP_EQUAL(new_name, name); } TEST(started_native_thread, join_with_parameter) { routine_arg.sem.signal(); ecl::err thread_retval; auto rc = started_tr.join(thread_retval); CHECK_EQUAL(ecl::err::ok, rc); CHECK_EQUAL(true, routine_arg.completed); CHECK_EQUAL(routine_arg.required_retval, thread_retval); // Notify shutdown routine that thread already joined started_tr_joined_or_detached = true; } //------------------------------------------------------------------------------ // TODO: state of detached thread cannot be restored back to the initial state // more tests in detached mode will require additional routine that // will return new thread or allocate new thread in heap and delete it // after test finishes static ecl::native_thread detached_tr; TEST_GROUP(detached_native_thread) { void setup() { auto rc = detached_tr.set_routine(test_routine, reinterpret_cast< void* >(&routine_arg)); CHECK_EQUAL(ecl::err::ok, rc); rc = detached_tr.start(); CHECK_EQUAL(ecl::err::ok, rc); // TODO: might be useful to add here some delay CHECK_EQUAL(true, routine_arg.started); // Thread shouldn't complete by itself CHECK_EQUAL(false, routine_arg.completed); rc = detached_tr.detach(); CHECK_EQUAL(ecl::err::ok, rc); } void teardown() { // Reset state routine_arg.started = false; routine_arg.completed = false; } }; TEST(detached_native_thread, basic) { // Let thread go routine_arg.sem.signal(); // Some time is requried to let thread finish std::this_thread::sleep_for(std::chrono::milliseconds(100)); CHECK_EQUAL(true, routine_arg.completed); } //------------------------------------------------------------------------------ int main(int argc, char *argv[]) { return CommandLineTestRunner::RunAllTests(argc, argv); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "termgdbadapter.h" #include "debuggerstartparameters.h" #include "gdbmi.h" #include "gdbengine.h" #include "procinterrupt.h" #include "debuggerstringutils.h" #include "debuggercore.h" #include "shared/hostutils.h" #include <utils/qtcassert.h> #include <coreplugin/icore.h> #include <QtGui/QMessageBox> namespace Debugger { namespace Internal { #define CB(callback) \ static_cast<GdbEngine::AdapterCallback>(&TermGdbAdapter::callback), \ STRINGIFY(callback) /////////////////////////////////////////////////////////////////////// // // TermGdbAdapter // /////////////////////////////////////////////////////////////////////// TermGdbAdapter::TermGdbAdapter(GdbEngine *engine) : AbstractGdbAdapter(engine) { m_stubProc.setMode(Utils::ConsoleProcess::Debug); #ifdef Q_OS_UNIX m_stubProc.setSettings(Core::ICore::instance()->settings()); #endif connect(&m_stubProc, SIGNAL(processError(QString)), SLOT(stubError(QString))); connect(&m_stubProc, SIGNAL(processStarted()), SLOT(handleInferiorSetupOk())); connect(&m_stubProc, SIGNAL(wrapperStopped()), SLOT(stubExited())); } TermGdbAdapter::~TermGdbAdapter() { m_stubProc.disconnect(); // Avoid spurious state transitions from late exiting stub } AbstractGdbAdapter::DumperHandling TermGdbAdapter::dumperHandling() const { // LD_PRELOAD fails for System-Qt on Mac. #if defined(Q_OS_WIN) || defined(Q_OS_MAC) return DumperLoadedByGdb; #else return DumperLoadedByAdapter; // Handles loading itself via LD_PRELOAD #endif } void TermGdbAdapter::startAdapter() { QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state()); showMessage(_("TRYING TO START ADAPTER")); // Currently, adapters are not re-used // // We leave the console open, so recycle it now. // m_stubProc.blockSignals(true); // m_stubProc.stop(); // m_stubProc.blockSignals(false); if (!prepareCommand()) return; m_stubProc.setWorkingDirectory(startParameters().workingDirectory); // Set environment + dumper preload. m_stubProc.setEnvironment(startParameters().environment); // FIXME: Starting the stub implies starting the inferior. This is // fairly unclean as far as the state machine and error reporting go. if (!m_stubProc.start(startParameters().executable, startParameters().processArgs)) { // Error message for user is delivered via a signal. m_engine->handleAdapterStartFailed(QString(), QString()); return; } if (!m_engine->startGdb()) { m_stubProc.stop(); return; } } void TermGdbAdapter::handleInferiorSetupOk() { QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state()); m_engine->handleAdapterStarted(); } void TermGdbAdapter::setupInferior() { QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state()); const qint64 attachedPID = m_stubProc.applicationPID(); #ifdef Q_OS_WIN const qint64 attachedMainThreadID = m_stubProc.applicationMainThreadID(); showMessage(QString::fromLatin1("Attaching to %1 (%2)").arg(attachedPID).arg(attachedMainThreadID), LogMisc); #else showMessage(QString::fromLatin1("Attaching to %1").arg(attachedPID), LogMisc); #endif m_engine->notifyInferiorPid(attachedPID); m_engine->postCommand("attach " + QByteArray::number(attachedPID), CB(handleStubAttached)); } void TermGdbAdapter::handleStubAttached(const GdbResponse &response) { QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state()); #ifdef Q_OS_WIN QString errorMessage; #endif // Q_OS_WIN switch (response.resultClass) { case GdbResultDone: case GdbResultRunning: #ifdef Q_OS_WIN // Resume thread that was suspended by console stub process (see stub code). if (winResumeThread(m_stubProc.applicationMainThreadID(), &errorMessage)) { showMessage(QString::fromLatin1("Inferior attached, thread %1 resumed"). arg(m_stubProc.applicationMainThreadID()), LogMisc); } else { showMessage(QString::fromLatin1("Inferior attached, unable to resume thread %1: %2"). arg(m_stubProc.applicationMainThreadID()).arg(errorMessage), LogWarning); } #else showMessage(_("INFERIOR ATTACHED")); #endif // Q_OS_WIN m_engine->handleInferiorPrepared(); break; case GdbResultError: if (response.data.findChild("msg").data() == "ptrace: Operation not permitted.") { m_engine->notifyInferiorSetupFailed(DumperHelper::msgPtraceError(startParameters().startMode)); break; } m_engine->notifyInferiorSetupFailed(QString::fromLocal8Bit(response.data.findChild("msg").data())); break; default: m_engine->notifyInferiorSetupFailed(QString::fromLatin1("Invalid response %1").arg(response.resultClass)); break; } } void TermGdbAdapter::runEngine() { QTC_ASSERT(state() == EngineRunRequested, qDebug() << state()); m_engine->notifyEngineRunAndInferiorStopOk(); m_engine->continueInferiorInternal(); } void TermGdbAdapter::interruptInferior() { const qint64 attachedPID = m_engine->inferiorPid(); QTC_ASSERT(attachedPID > 0, return); if (!interruptProcess(attachedPID)) showMessage(_("CANNOT INTERRUPT %1").arg(attachedPID)); } void TermGdbAdapter::stubError(const QString &msg) { showMessageBox(QMessageBox::Critical, tr("Debugger Error"), msg); } void TermGdbAdapter::stubExited() { if (state() == EngineShutdownRequested || state() == DebuggerFinished) { showMessage(_("STUB EXITED EXPECTEDLY")); return; } showMessage(_("STUB EXITED")); m_engine->notifyEngineIll(); } void TermGdbAdapter::shutdownInferior() { m_engine->defaultInferiorShutdown("kill"); } void TermGdbAdapter::shutdownAdapter() { m_engine->notifyAdapterShutdownOk(); } } // namespace Internal } // namespace Debugger <commit_msg>changed mode of stub to Utils::ConsoleProcess::Suspend<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "termgdbadapter.h" #include "debuggerstartparameters.h" #include "gdbmi.h" #include "gdbengine.h" #include "procinterrupt.h" #include "debuggerstringutils.h" #include "debuggercore.h" #include "shared/hostutils.h" #include <utils/qtcassert.h> #include <coreplugin/icore.h> #include <QtGui/QMessageBox> namespace Debugger { namespace Internal { #define CB(callback) \ static_cast<GdbEngine::AdapterCallback>(&TermGdbAdapter::callback), \ STRINGIFY(callback) /////////////////////////////////////////////////////////////////////// // // TermGdbAdapter // /////////////////////////////////////////////////////////////////////// TermGdbAdapter::TermGdbAdapter(GdbEngine *engine) : AbstractGdbAdapter(engine) { #ifdef Q_OS_WIN // Windows up to xp needs a workaround for attaching to freshly started processes. see proc_stub_win if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA) { m_stubProc.setMode(Utils::ConsoleProcess::Suspend); } else { m_stubProc.setMode(Utils::ConsoleProcess::Debug); } #else m_stubProc.setMode(Utils::ConsoleProcess::Debug); m_stubProc.setSettings(Core::ICore::instance()->settings()); #endif connect(&m_stubProc, SIGNAL(processError(QString)), SLOT(stubError(QString))); connect(&m_stubProc, SIGNAL(processStarted()), SLOT(handleInferiorSetupOk())); connect(&m_stubProc, SIGNAL(wrapperStopped()), SLOT(stubExited())); } TermGdbAdapter::~TermGdbAdapter() { m_stubProc.disconnect(); // Avoid spurious state transitions from late exiting stub } AbstractGdbAdapter::DumperHandling TermGdbAdapter::dumperHandling() const { // LD_PRELOAD fails for System-Qt on Mac. #if defined(Q_OS_WIN) || defined(Q_OS_MAC) return DumperLoadedByGdb; #else return DumperLoadedByAdapter; // Handles loading itself via LD_PRELOAD #endif } void TermGdbAdapter::startAdapter() { QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state()); showMessage(_("TRYING TO START ADAPTER")); // Currently, adapters are not re-used // // We leave the console open, so recycle it now. // m_stubProc.blockSignals(true); // m_stubProc.stop(); // m_stubProc.blockSignals(false); if (!prepareCommand()) return; m_stubProc.setWorkingDirectory(startParameters().workingDirectory); // Set environment + dumper preload. m_stubProc.setEnvironment(startParameters().environment); // FIXME: Starting the stub implies starting the inferior. This is // fairly unclean as far as the state machine and error reporting go. if (!m_stubProc.start(startParameters().executable, startParameters().processArgs)) { // Error message for user is delivered via a signal. m_engine->handleAdapterStartFailed(QString(), QString()); return; } if (!m_engine->startGdb()) { m_stubProc.stop(); return; } } void TermGdbAdapter::handleInferiorSetupOk() { QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state()); m_engine->handleAdapterStarted(); } void TermGdbAdapter::setupInferior() { QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state()); const qint64 attachedPID = m_stubProc.applicationPID(); #ifdef Q_OS_WIN const qint64 attachedMainThreadID = m_stubProc.applicationMainThreadID(); showMessage(QString::fromLatin1("Attaching to %1 (%2)").arg(attachedPID).arg(attachedMainThreadID), LogMisc); #else showMessage(QString::fromLatin1("Attaching to %1").arg(attachedPID), LogMisc); #endif m_engine->notifyInferiorPid(attachedPID); m_engine->postCommand("attach " + QByteArray::number(attachedPID), CB(handleStubAttached)); } void TermGdbAdapter::handleStubAttached(const GdbResponse &response) { QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state()); #ifdef Q_OS_WIN QString errorMessage; #endif // Q_OS_WIN switch (response.resultClass) { case GdbResultDone: case GdbResultRunning: #ifdef Q_OS_WIN // Resume thread that was suspended by console stub process (see stub code). if (winResumeThread(m_stubProc.applicationMainThreadID(), &errorMessage)) { showMessage(QString::fromLatin1("Inferior attached, thread %1 resumed"). arg(m_stubProc.applicationMainThreadID()), LogMisc); } else { showMessage(QString::fromLatin1("Inferior attached, unable to resume thread %1: %2"). arg(m_stubProc.applicationMainThreadID()).arg(errorMessage), LogWarning); } #else showMessage(_("INFERIOR ATTACHED")); #endif // Q_OS_WIN m_engine->handleInferiorPrepared(); break; case GdbResultError: if (response.data.findChild("msg").data() == "ptrace: Operation not permitted.") { m_engine->notifyInferiorSetupFailed(DumperHelper::msgPtraceError(startParameters().startMode)); break; } m_engine->notifyInferiorSetupFailed(QString::fromLocal8Bit(response.data.findChild("msg").data())); break; default: m_engine->notifyInferiorSetupFailed(QString::fromLatin1("Invalid response %1").arg(response.resultClass)); break; } } void TermGdbAdapter::runEngine() { QTC_ASSERT(state() == EngineRunRequested, qDebug() << state()); m_engine->notifyEngineRunAndInferiorStopOk(); m_engine->continueInferiorInternal(); } void TermGdbAdapter::interruptInferior() { const qint64 attachedPID = m_engine->inferiorPid(); QTC_ASSERT(attachedPID > 0, return); if (!interruptProcess(attachedPID)) showMessage(_("CANNOT INTERRUPT %1").arg(attachedPID)); } void TermGdbAdapter::stubError(const QString &msg) { showMessageBox(QMessageBox::Critical, tr("Debugger Error"), msg); } void TermGdbAdapter::stubExited() { if (state() == EngineShutdownRequested || state() == DebuggerFinished) { showMessage(_("STUB EXITED EXPECTEDLY")); return; } showMessage(_("STUB EXITED")); m_engine->notifyEngineIll(); } void TermGdbAdapter::shutdownInferior() { m_engine->defaultInferiorShutdown("kill"); } void TermGdbAdapter::shutdownAdapter() { m_engine->notifyAdapterShutdownOk(); } } // namespace Internal } // namespace Debugger <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "winutils.h" #include "dbgwinutils.h" #include "debuggerdialogs.h" #include "breakpoint.h" #include <QtCore/QDebug> #include <QtCore/QString> #include <QtCore/QTextStream> // Enable Win API of XP SP1 and later #ifdef Q_OS_WIN # define _WIN32_WINNT 0x0502 # include <windows.h> # include <utils/winutils.h> # if !defined(PROCESS_SUSPEND_RESUME) // Check flag for MinGW # define PROCESS_SUSPEND_RESUME (0x0800) # endif // PROCESS_SUSPEND_RESUME #endif // Q_OS_WIN #include <tlhelp32.h> #include <psapi.h> #include <QtCore/QLibrary> namespace Debugger { namespace Internal { // Resolve QueryFullProcessImageNameW out of kernel32.dll due // to incomplete MinGW import libs and it not being present // on Windows XP. static inline BOOL queryFullProcessImageName(HANDLE h, DWORD flags, LPWSTR buffer, DWORD *size) { // Resolve required symbols from the kernel32.dll typedef BOOL (WINAPI *QueryFullProcessImageNameWProtoType) (HANDLE, DWORD, LPWSTR, PDWORD); static QueryFullProcessImageNameWProtoType queryFullProcessImageNameW = 0; if (!queryFullProcessImageNameW) { QLibrary kernel32Lib(QLatin1String("kernel32.dll"), 0); if (kernel32Lib.isLoaded() || kernel32Lib.load()) queryFullProcessImageNameW = (QueryFullProcessImageNameWProtoType)kernel32Lib.resolve("QueryFullProcessImageNameW"); } if (!queryFullProcessImageNameW) return FALSE; // Read out process return (*queryFullProcessImageNameW)(h, flags, buffer, size); } static inline QString imageName(DWORD processId) { QString rc; HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION , FALSE, processId); if (handle == INVALID_HANDLE_VALUE) return rc; WCHAR buffer[MAX_PATH]; DWORD bufSize = MAX_PATH; if (queryFullProcessImageName(handle, 0, buffer, &bufSize)) rc = QString::fromUtf16(reinterpret_cast<const ushort*>(buffer)); CloseHandle(handle); return rc; } QList<ProcData> winProcessList() { QList<ProcData> rc; PROCESSENTRY32 pe; pe.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) return rc; for (bool hasNext = Process32First(snapshot, &pe); hasNext; hasNext = Process32Next(snapshot, &pe)) { ProcData procData; procData.ppid = QString::number(pe.th32ProcessID); procData.name = QString::fromUtf16(reinterpret_cast<ushort*>(pe.szExeFile)); procData.image = imageName(pe.th32ProcessID); rc.push_back(procData); } CloseHandle(snapshot); return rc; } bool winResumeThread(unsigned long dwThreadId, QString *errorMessage) { bool ok = false; HANDLE handle = NULL; do { if (!dwThreadId) break; handle = OpenThread(SYNCHRONIZE |THREAD_QUERY_INFORMATION |THREAD_SUSPEND_RESUME, FALSE, dwThreadId); if (handle==NULL) { *errorMessage = QString::fromLatin1("Unable to open thread %1: %2"). arg(dwThreadId).arg(Utils::winErrorMessage(GetLastError())); break; } if (ResumeThread(handle) == DWORD(-1)) { *errorMessage = QString::fromLatin1("Unable to resume thread %1: %2"). arg(dwThreadId).arg(Utils::winErrorMessage(GetLastError())); break; } ok = true; } while (false); if (handle != NULL) CloseHandle(handle); return ok; } // Open the process and break into it bool winDebugBreakProcess(unsigned long pid, QString *errorMessage) { bool ok = false; HANDLE inferior = NULL; do { const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME ; inferior = OpenProcess(rights, FALSE, pid); if (inferior == NULL) { *errorMessage = QString::fromLatin1("Cannot open process %1: %2"). arg(pid).arg(Utils::winErrorMessage(GetLastError())); break; } if (!DebugBreakProcess(inferior)) { *errorMessage = QString::fromLatin1("DebugBreakProcess failed: %1").arg(Utils::winErrorMessage(GetLastError())); break; } ok = true; } while (false); if (inferior != NULL) CloseHandle(inferior); return ok; } unsigned long winGetCurrentProcessId() { return GetCurrentProcessId(); } // Helper for normalizing file names: // Map the device paths in a file name to back to drive letters // "/Device/HarddiskVolume1/file.cpp" -> "C:/file.cpp" static bool mapDeviceToDriveLetter(QString *s) { enum { bufSize = 512 }; // Retrieve drive letters and get their device names. // Do not cache as it may change due to removable/network drives. TCHAR driveLetters[bufSize]; if (!GetLogicalDriveStrings(bufSize-1, driveLetters)) return false; TCHAR driveName[MAX_PATH]; TCHAR szDrive[3] = TEXT(" :"); for (const TCHAR *driveLetter = driveLetters; *driveLetter; driveLetter++) { szDrive[0] = *driveLetter; // Look up each device name if (QueryDosDevice(szDrive, driveName, MAX_PATH)) { const QString deviceName = QString::fromWCharArray(driveName); if (s->startsWith(deviceName)) { s->replace(0, deviceName.size(), QString::fromWCharArray(szDrive)); return true; } } } return false; } bool isWinProcessBeingDebugged(unsigned long pid) { HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); if (processHandle == NULL) return false; BOOL debugged = FALSE; CheckRemoteDebuggerPresent(processHandle, &debugged); CloseHandle(processHandle); return debugged != FALSE; } // Simple exception formatting void formatWindowsException(unsigned long code, quint64 address, unsigned long flags, quint64 info1, quint64 info2, QTextStream &str) { str.setIntegerBase(16); str << "\nException at 0x" << address << ", code: 0x" << code << ": "; switch (code) { case winExceptionCppException: str << "C++ exception"; break; case winExceptionStartupCompleteTrap: str << "Startup complete"; break; case winExceptionDllNotFound: str << "DLL not found"; break; case winExceptionDllEntryPointNoFound: str << "DLL entry point not found"; break; case winExceptionDllInitFailed: str << "DLL failed to initialize"; break; case winExceptionMissingSystemFile: str << "System file is missing"; break; case winExceptionRpcServerUnavailable: str << "RPC server unavailable"; break; case winExceptionRpcServerInvalid: str << "Invalid RPC server"; break; case winExceptionWX86Breakpoint: str << "Win32 x86 emulation subsystem breakpoint hit"; break; case EXCEPTION_ACCESS_VIOLATION: { const bool writeOperation = info1; str << (writeOperation ? "write" : "read") << " access violation at: 0x" << info2; } break; case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: str << "arrary bounds exceeded"; break; case EXCEPTION_BREAKPOINT: str << "breakpoint"; break; case EXCEPTION_DATATYPE_MISALIGNMENT: str << "datatype misalignment"; break; case EXCEPTION_FLT_DENORMAL_OPERAND: str << "floating point exception"; break; case EXCEPTION_FLT_DIVIDE_BY_ZERO: str << "division by zero"; break; case EXCEPTION_FLT_INEXACT_RESULT: str << " floating-point operation cannot be represented exactly as a decimal fraction"; break; case EXCEPTION_FLT_INVALID_OPERATION: str << "invalid floating-point operation"; break; case EXCEPTION_FLT_OVERFLOW: str << "floating-point overflow"; break; case EXCEPTION_FLT_STACK_CHECK: str << "floating-point operation stack over/underflow"; break; case EXCEPTION_FLT_UNDERFLOW: str << "floating-point UNDERFLOW"; break; case EXCEPTION_ILLEGAL_INSTRUCTION: str << "invalid instruction"; break; case EXCEPTION_IN_PAGE_ERROR: str << "page in error"; break; case EXCEPTION_INT_DIVIDE_BY_ZERO: str << "integer division by zero"; break; case EXCEPTION_INT_OVERFLOW: str << "integer overflow"; break; case EXCEPTION_INVALID_DISPOSITION: str << "invalid disposition to exception dispatcher"; break; case EXCEPTION_NONCONTINUABLE_EXCEPTION: str << "attempt to continue execution after noncontinuable exception"; break; case EXCEPTION_PRIV_INSTRUCTION: str << "privileged instruction"; break; case EXCEPTION_SINGLE_STEP: str << "single step"; break; case EXCEPTION_STACK_OVERFLOW: str << "stack_overflow"; break; } str << ", flags=0x" << flags; if (flags == EXCEPTION_NONCONTINUABLE) { str << " (execution cannot be continued)"; } str.setIntegerBase(10); } bool isDebuggerWinException(long code) { return code ==EXCEPTION_BREAKPOINT || code == EXCEPTION_SINGLE_STEP; } bool isFatalWinException(long code) { switch (code) { case EXCEPTION_BREAKPOINT: case EXCEPTION_SINGLE_STEP: case winExceptionStartupCompleteTrap: // Mysterious exception at start of application case winExceptionRpcServerUnavailable: case winExceptionRpcServerInvalid: case winExceptionDllNotFound: case winExceptionDllEntryPointNoFound: case winExceptionCppException: return false; default: break; } return true; } } // namespace Internal } // namespace Debugger <commit_msg>Removed unused function<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "winutils.h" #include "dbgwinutils.h" #include "debuggerdialogs.h" #include "breakpoint.h" #include <QtCore/QDebug> #include <QtCore/QString> #include <QtCore/QTextStream> // Enable Win API of XP SP1 and later #ifdef Q_OS_WIN # define _WIN32_WINNT 0x0502 # include <windows.h> # include <utils/winutils.h> # if !defined(PROCESS_SUSPEND_RESUME) // Check flag for MinGW # define PROCESS_SUSPEND_RESUME (0x0800) # endif // PROCESS_SUSPEND_RESUME #endif // Q_OS_WIN #include <tlhelp32.h> #include <psapi.h> #include <QtCore/QLibrary> namespace Debugger { namespace Internal { // Resolve QueryFullProcessImageNameW out of kernel32.dll due // to incomplete MinGW import libs and it not being present // on Windows XP. static inline BOOL queryFullProcessImageName(HANDLE h, DWORD flags, LPWSTR buffer, DWORD *size) { // Resolve required symbols from the kernel32.dll typedef BOOL (WINAPI *QueryFullProcessImageNameWProtoType) (HANDLE, DWORD, LPWSTR, PDWORD); static QueryFullProcessImageNameWProtoType queryFullProcessImageNameW = 0; if (!queryFullProcessImageNameW) { QLibrary kernel32Lib(QLatin1String("kernel32.dll"), 0); if (kernel32Lib.isLoaded() || kernel32Lib.load()) queryFullProcessImageNameW = (QueryFullProcessImageNameWProtoType)kernel32Lib.resolve("QueryFullProcessImageNameW"); } if (!queryFullProcessImageNameW) return FALSE; // Read out process return (*queryFullProcessImageNameW)(h, flags, buffer, size); } static inline QString imageName(DWORD processId) { QString rc; HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION , FALSE, processId); if (handle == INVALID_HANDLE_VALUE) return rc; WCHAR buffer[MAX_PATH]; DWORD bufSize = MAX_PATH; if (queryFullProcessImageName(handle, 0, buffer, &bufSize)) rc = QString::fromUtf16(reinterpret_cast<const ushort*>(buffer)); CloseHandle(handle); return rc; } QList<ProcData> winProcessList() { QList<ProcData> rc; PROCESSENTRY32 pe; pe.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) return rc; for (bool hasNext = Process32First(snapshot, &pe); hasNext; hasNext = Process32Next(snapshot, &pe)) { ProcData procData; procData.ppid = QString::number(pe.th32ProcessID); procData.name = QString::fromUtf16(reinterpret_cast<ushort*>(pe.szExeFile)); procData.image = imageName(pe.th32ProcessID); rc.push_back(procData); } CloseHandle(snapshot); return rc; } bool winResumeThread(unsigned long dwThreadId, QString *errorMessage) { bool ok = false; HANDLE handle = NULL; do { if (!dwThreadId) break; handle = OpenThread(SYNCHRONIZE |THREAD_QUERY_INFORMATION |THREAD_SUSPEND_RESUME, FALSE, dwThreadId); if (handle==NULL) { *errorMessage = QString::fromLatin1("Unable to open thread %1: %2"). arg(dwThreadId).arg(Utils::winErrorMessage(GetLastError())); break; } if (ResumeThread(handle) == DWORD(-1)) { *errorMessage = QString::fromLatin1("Unable to resume thread %1: %2"). arg(dwThreadId).arg(Utils::winErrorMessage(GetLastError())); break; } ok = true; } while (false); if (handle != NULL) CloseHandle(handle); return ok; } // Open the process and break into it bool winDebugBreakProcess(unsigned long pid, QString *errorMessage) { bool ok = false; HANDLE inferior = NULL; do { const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME ; inferior = OpenProcess(rights, FALSE, pid); if (inferior == NULL) { *errorMessage = QString::fromLatin1("Cannot open process %1: %2"). arg(pid).arg(Utils::winErrorMessage(GetLastError())); break; } if (!DebugBreakProcess(inferior)) { *errorMessage = QString::fromLatin1("DebugBreakProcess failed: %1").arg(Utils::winErrorMessage(GetLastError())); break; } ok = true; } while (false); if (inferior != NULL) CloseHandle(inferior); return ok; } unsigned long winGetCurrentProcessId() { return GetCurrentProcessId(); } bool isWinProcessBeingDebugged(unsigned long pid) { HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); if (processHandle == NULL) return false; BOOL debugged = FALSE; CheckRemoteDebuggerPresent(processHandle, &debugged); CloseHandle(processHandle); return debugged != FALSE; } // Simple exception formatting void formatWindowsException(unsigned long code, quint64 address, unsigned long flags, quint64 info1, quint64 info2, QTextStream &str) { str.setIntegerBase(16); str << "\nException at 0x" << address << ", code: 0x" << code << ": "; switch (code) { case winExceptionCppException: str << "C++ exception"; break; case winExceptionStartupCompleteTrap: str << "Startup complete"; break; case winExceptionDllNotFound: str << "DLL not found"; break; case winExceptionDllEntryPointNoFound: str << "DLL entry point not found"; break; case winExceptionDllInitFailed: str << "DLL failed to initialize"; break; case winExceptionMissingSystemFile: str << "System file is missing"; break; case winExceptionRpcServerUnavailable: str << "RPC server unavailable"; break; case winExceptionRpcServerInvalid: str << "Invalid RPC server"; break; case winExceptionWX86Breakpoint: str << "Win32 x86 emulation subsystem breakpoint hit"; break; case EXCEPTION_ACCESS_VIOLATION: { const bool writeOperation = info1; str << (writeOperation ? "write" : "read") << " access violation at: 0x" << info2; } break; case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: str << "arrary bounds exceeded"; break; case EXCEPTION_BREAKPOINT: str << "breakpoint"; break; case EXCEPTION_DATATYPE_MISALIGNMENT: str << "datatype misalignment"; break; case EXCEPTION_FLT_DENORMAL_OPERAND: str << "floating point exception"; break; case EXCEPTION_FLT_DIVIDE_BY_ZERO: str << "division by zero"; break; case EXCEPTION_FLT_INEXACT_RESULT: str << " floating-point operation cannot be represented exactly as a decimal fraction"; break; case EXCEPTION_FLT_INVALID_OPERATION: str << "invalid floating-point operation"; break; case EXCEPTION_FLT_OVERFLOW: str << "floating-point overflow"; break; case EXCEPTION_FLT_STACK_CHECK: str << "floating-point operation stack over/underflow"; break; case EXCEPTION_FLT_UNDERFLOW: str << "floating-point UNDERFLOW"; break; case EXCEPTION_ILLEGAL_INSTRUCTION: str << "invalid instruction"; break; case EXCEPTION_IN_PAGE_ERROR: str << "page in error"; break; case EXCEPTION_INT_DIVIDE_BY_ZERO: str << "integer division by zero"; break; case EXCEPTION_INT_OVERFLOW: str << "integer overflow"; break; case EXCEPTION_INVALID_DISPOSITION: str << "invalid disposition to exception dispatcher"; break; case EXCEPTION_NONCONTINUABLE_EXCEPTION: str << "attempt to continue execution after noncontinuable exception"; break; case EXCEPTION_PRIV_INSTRUCTION: str << "privileged instruction"; break; case EXCEPTION_SINGLE_STEP: str << "single step"; break; case EXCEPTION_STACK_OVERFLOW: str << "stack_overflow"; break; } str << ", flags=0x" << flags; if (flags == EXCEPTION_NONCONTINUABLE) { str << " (execution cannot be continued)"; } str.setIntegerBase(10); } bool isDebuggerWinException(long code) { return code ==EXCEPTION_BREAKPOINT || code == EXCEPTION_SINGLE_STEP; } bool isFatalWinException(long code) { switch (code) { case EXCEPTION_BREAKPOINT: case EXCEPTION_SINGLE_STEP: case winExceptionStartupCompleteTrap: // Mysterious exception at start of application case winExceptionRpcServerUnavailable: case winExceptionRpcServerInvalid: case winExceptionDllNotFound: case winExceptionDllEntryPointNoFound: case winExceptionCppException: return false; default: break; } return true; } } // namespace Internal } // namespace Debugger <|endoftext|>