text
stringlengths
54
60.6k
<commit_before>// // Created by salmon on 17-10-11. // #include "simpla/SIMPLA_config.h" #include <simpla/application/SPInit.h> #include <simpla/geometry/BoxUtilities.h> #include <simpla/geometry/Cube.h> #include <simpla/geometry/csCartesian.h> #include <simpla/mesh/CoRectMesh.h> #include <simpla/mesh/EBMesh.h> #include <simpla/mesh/RectMesh.h> #include <simpla/predefine/engine/SimpleTimeIntegrator.h> #include <simpla/predefine/physics/Maxwell.h> #include <simpla/predefine/physics/PML.h> #include <simpla/scheme/FVM.h> #include <simpla/utilities/Logo.h> #include <simpla/utilities/parse_command_line.h> namespace simpla { using SimpleMaxwell = domain::Maxwell<engine::Domain<geometry::csCartesian, scheme::FVM, mesh::CoRectMesh>>; using SimplePML = domain::PML<engine::Domain<geometry::csCartesian, scheme::FVM, mesh::CoRectMesh>>; } // namespace simpla { using namespace simpla; using namespace simpla::engine; int main(int argc, char **argv) { size_type num_of_step = 10; size_type checkpoint_interval = 1; simpla::parse_cmd_line( // argc, argv, [&](std::string const &opt, std::string const &value) -> int { if (false) { } else if (opt == "n") { num_of_step = static_cast<size_type>(std::atoi(value.c_str())); } else if (opt == "checkpoint") { checkpoint_interval = static_cast<size_type>(std::atoi(value.c_str())); } return CONTINUE; }); simpla::Initialize(argc, argv); auto scenario = SimpleTimeIntegrator::New(); scenario->SetName("MultiDomain"); box_type center_box{{-15, -25, -20}, {15, 25, 20}}; box_type bounding_box{{-20, -25, -20}, {20, 25, 20}}; scenario->GetAtlas()->SetOrigin({0, 0, 0}); scenario->GetAtlas()->SetGridWidth({1, 1, 1}); scenario->GetAtlas()->SetPeriodicDimensions({0, 1, 1}); scenario->GetAtlas()->NewChart<simpla::geometry::csCartesian>(); auto center = scenario->NewDomain<SimpleMaxwell>("Center"); center->SetBoundary(geometry::Cube::New(box_type{{-15, -25, -20}, {15, 25, 20}})); center->PostInitialCondition.Connect([=](DomainBase *self, Real time_now) { if (auto d = dynamic_cast<SimpleMaxwell *>(self)) { d->B = [&](point_type const &x) { return point_type{std::sin(2 * PI * x[1] / 50) * std::sin(2 * PI * x[2] / 40), std::sin(2 * PI * x[0] / 30) * std::sin(2 * PI * x[2] / 40), std::sin(2 * PI * x[0] / 30) * std::sin(2 * PI * x[1] / 50)}; }; } }); scenario->NewDomain<SimpleMaxwell>("boundary0") ->SetBoundary(geometry::Cube::New(box_type{{-20, -25, -20}, {-15, 25, 20}})); scenario->NewDomain<SimpleMaxwell>("boundary1") ->SetBoundary(geometry::Cube::New(box_type{{15, -25, -20}, {20, 25, 20}})); // auto pml = scenario->NewDomain<SimplePML>("Boundary"); // pml->SetBoundingBox(bounding_box); // pml->SetCenterBox(center_box); // scenario->SetTimeEnd(1.0e-8); scenario->SetMaxStep(num_of_step); scenario->SetUp(); if (auto atlas = scenario->GetAtlas()) { scenario->GetAtlas()->Decompose({3, 3, 3}); auto c_box = center->GetBoundingBox(); auto box_list = geometry::HaloBoxDecompose( atlas->GetIndexBox(), std::make_tuple(std::get<1>(atlas->GetChart()->invert_local_coordinates(std::get<0>(c_box))), std::get<1>(atlas->GetChart()->invert_local_coordinates(std::get<1>(c_box))))); for (auto const &b : box_list) { atlas->AddPatch(b); } } scenario->ConfigureAttribute<size_type>("E", "CheckPoint", checkpoint_interval); scenario->ConfigureAttribute<size_type>("B", "CheckPoint", checkpoint_interval); // scenario->ConfigureAttribute<size_type>("a0", "CheckPoint", 1); // scenario->ConfigureAttribute<size_type>("a1", "CheckPoint", 1); // scenario->ConfigureAttribute<size_type>("a2", "CheckPoint", 1); // scenario->ConfigureAttribute<size_type>("s0", "CheckPoint", 1); // scenario->ConfigureAttribute<size_type>("s1", "CheckPoint", 1); // scenario->ConfigureAttribute<size_type>("s2", "CheckPoint", 1); VERBOSE << "Scenario: " << *scenario->Serialize(); TheStart(); scenario->Run(); TheEnd(); scenario->TearDown(); simpla::Finalize(); }<commit_msg>MultiDomain success;PML fail<commit_after>// // Created by salmon on 17-10-11. // #include "simpla/SIMPLA_config.h" #include <simpla/application/SPInit.h> #include <simpla/geometry/BoxUtilities.h> #include <simpla/geometry/Cube.h> #include <simpla/geometry/csCartesian.h> #include <simpla/mesh/CoRectMesh.h> #include <simpla/mesh/EBMesh.h> #include <simpla/mesh/RectMesh.h> #include <simpla/predefine/engine/SimpleTimeIntegrator.h> #include <simpla/predefine/physics/Maxwell.h> #include <simpla/predefine/physics/PML.h> #include <simpla/scheme/FVM.h> #include <simpla/utilities/Logo.h> #include <simpla/utilities/parse_command_line.h> namespace simpla { using SimpleMaxwell = domain::Maxwell<engine::Domain<geometry::csCartesian, scheme::FVM, mesh::CoRectMesh>>; using SimplePML = domain::PML<engine::Domain<geometry::csCartesian, scheme::FVM, mesh::CoRectMesh>>; } // namespace simpla { using namespace simpla; using namespace simpla::engine; int main(int argc, char **argv) { size_type num_of_step = 10; size_type checkpoint_interval = 1; simpla::parse_cmd_line( // argc, argv, [&](std::string const &opt, std::string const &value) -> int { if (false) { } else if (opt == "n") { num_of_step = static_cast<size_type>(std::atoi(value.c_str())); } else if (opt == "checkpoint") { checkpoint_interval = static_cast<size_type>(std::atoi(value.c_str())); } return CONTINUE; }); simpla::Initialize(argc, argv); auto scenario = SimpleTimeIntegrator::New(); scenario->SetName("MultiDomain"); scenario->GetAtlas()->SetOrigin({0, 0, 0}); scenario->GetAtlas()->SetGridWidth({1, 1, 1}); scenario->GetAtlas()->SetPeriodicDimensions({1, 1, 1}); scenario->GetAtlas()->NewChart<simpla::geometry::csCartesian>(); auto center = scenario->NewDomain<SimpleMaxwell>("Center"); center->SetBoundary(geometry::Cube::New(box_type{{-15, -25, -20}, {15, 25, 20}})); center->PostInitialCondition.Connect([=](DomainBase *self, Real time_now) { if (auto d = dynamic_cast<SimpleMaxwell *>(self)) { d->B = [&](point_type const &x) { return point_type{std::sin(2 * PI * x[1] / 50) * std::sin(2 * PI * x[2] / 40), std::sin(2 * PI * x[0] / 30) * std::sin(2 * PI * x[2] / 40), std::sin(2 * PI * x[0] / 30) * std::sin(2 * PI * x[1] / 50)}; }; } }); // scenario->NewDomain<SimpleMaxwell>("boundary0") // ->SetBoundary(geometry::Cube::New(box_type{{-20, -25, -20}, {-15, 25, 20}})); // scenario->NewDomain<SimpleMaxwell>("boundary1") // ->SetBoundary(geometry::Cube::New(box_type{{15, -25, -20}, {20, 25, 20}})); auto pml = scenario->NewDomain<SimplePML>("PML"); pml->SetBoundingBox(box_type{{-20, -25, -20}, {20, 25, 20}}); pml->SetCenterBox(center->GetBoundingBox()); scenario->SetTimeEnd(1.0e-8); scenario->SetMaxStep(num_of_step); scenario->SetUp(); if (auto atlas = scenario->GetAtlas()) { scenario->GetAtlas()->Decompose({3, 3, 3}); auto c_box = center->GetBoundingBox(); auto box_list = geometry::HaloBoxDecompose( atlas->GetIndexBox(), std::make_tuple(std::get<1>(atlas->GetChart()->invert_local_coordinates(std::get<0>(c_box))), std::get<1>(atlas->GetChart()->invert_local_coordinates(std::get<1>(c_box))))); for (auto const &b : box_list) { atlas->AddPatch(b); } } scenario->ConfigureAttribute<size_type>("E", "CheckPoint", checkpoint_interval); scenario->ConfigureAttribute<size_type>("B", "CheckPoint", checkpoint_interval); // scenario->ConfigureAttribute<size_type>("a0", "CheckPoint", 1); // scenario->ConfigureAttribute<size_type>("a1", "CheckPoint", 1); // scenario->ConfigureAttribute<size_type>("a2", "CheckPoint", 1); // scenario->ConfigureAttribute<size_type>("s0", "CheckPoint", 1); // scenario->ConfigureAttribute<size_type>("s1", "CheckPoint", 1); // scenario->ConfigureAttribute<size_type>("s2", "CheckPoint", 1); VERBOSE << "Scenario: " << *scenario->Serialize(); TheStart(); scenario->Run(); TheEnd(); scenario->TearDown(); simpla::Finalize(); }<|endoftext|>
<commit_before>/** * \file logging.hh * \brief logging **/ #ifndef LOGGING_HH_INCLUDED #define LOGGING_HH_INCLUDED #include <fstream> #include <ostream> #include <sstream> #include <ctime> #include <iomanip> #include <map> #include <assert.h> #include "misc.hh" /** \brief handles all logging **/ class Logging { public: enum LogFlags{ LOG_NONE = 1, LOG_ERR = 2, LOG_INFO = 4, LOG_DEBUG = 8, LOG_CONSOLE = 16, LOG_FILE = 32 }; //! only for logging to a single file which should then be executabla by matlab class MatlabLogStream { public: MatlabLogStream( LogFlags loglevel, int& logflags, std::ofstream& logFile ) : matlabLogFile_( logFile ), loglevel_(loglevel), logflags_(logflags), suspended_logflags_(logflags) {} ~MatlabLogStream(){} template < typename T > MatlabLogStream& operator << ( T in ) { if ( logflags_ & loglevel_ ) buffer_ << in; return *this; } MatlabLogStream& operator << ( MatlabLogStream& ( *pf )(MatlabLogStream&) ) { if ( logflags_ & loglevel_ ) buffer_ << pf; return *this; } MatlabLogStream& operator << ( std::ostream& ( *pf )(std::ostream &) ) { if ( logflags_ & loglevel_ ) { if ( pf == (std::ostream& ( * )(std::ostream&))std::endl ) { //flush buffer into stream buffer_ << "\n"; Flush(); } else { buffer_ << pf; } } return *this; } void Flush() { matlabLogFile_ << buffer_.str(); matlabLogFile_.flush(); buffer_.flush(); buffer_.str("");// clear the buffer } void Suspend() { //don't accidentally invalidate flags if already suspended if ( !is_suspended_ ) { suspended_logflags_ = logflags_; logflags_ = 1; } is_suspended_ = true; } void Resume() { if ( is_suspended_ ) logflags_ = suspended_logflags_; is_suspended_ = false; } private: std::stringstream buffer_; std::ofstream& matlabLogFile_; LogFlags loglevel_; int& logflags_; int suspended_logflags_; bool is_suspended_; }; class LogStream //: virtual public std::ostream { public: typedef int PriorityType; static const PriorityType default_suspend_priority = 0; protected: LogFlags loglevel_; int& logflags_; int suspended_logflags_; std::stringstream buffer_; std::ofstream& logfile_; std::ofstream& logfileWoTime_; bool is_suspended_; PriorityType suspend_priority_; public: LogStream( LogFlags loglevel, int& logflags, std::ofstream& file, std::ofstream& fileWoTime ) : loglevel_(loglevel), logflags_(logflags), suspended_logflags_(logflags), logfile_(file), logfileWoTime_( fileWoTime ), is_suspended_(false), suspend_priority_( default_suspend_priority ) {} ~LogStream() { Flush(); } template < typename T > LogStream& operator << ( T in ) { SetColor(); if ( logflags_ & loglevel_ ) buffer_ << in; UnsetColor(); return *this; } void Suspend( PriorityType priority = default_suspend_priority ) { //the suspend_priority_ mechanism provides a way to silence streams from 'higher' modules suspend_priority_ = std::max( priority, suspend_priority_ ); { //don't accidentally invalidate flags if already suspended if ( !is_suspended_ ) { suspended_logflags_ = logflags_; logflags_ = 1; } is_suspended_ = true; } } void Resume( PriorityType priority = default_suspend_priority ) { if ( priority >= suspend_priority_ ) { if ( is_suspended_ ) logflags_ = suspended_logflags_; is_suspended_ = false; suspend_priority_ = default_suspend_priority; } } void Flush() { if ( logflags_ & loglevel_ ) { //flush buffer into stream if ( ( logflags_ & LOG_CONSOLE ) != 0 ) { std::cout << buffer_.str();// << std::endl; std::cout .flush(); } if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_ << "\n" << TimeString() << buffer_.str() << std::endl; logfileWoTime_ << buffer_.str();// << std::endl; logfile_.flush(); logfileWoTime_.flush(); } buffer_.flush(); buffer_.str("");// clear the buffer } } void SetColor() { // if ( logflags_ & LOG_INFO ) { // buffer_ << "\033[21;31m"; // } } void UnsetColor() { // buffer_ << "\033[0m"; } //template < class Class > LogStream& operator << ( LogStream& ( *pf )(LogStream&) ) { if ( logflags_ & loglevel_ ) buffer_ << pf; return *this; } LogStream& operator << ( std::ostream& ( *pf )(std::ostream &) ) { SetColor(); if ( logflags_ & loglevel_ ) { if ( pf == (std::ostream& ( * )(std::ostream&))std::endl ) { //flush buffer into stream buffer_ << "\n"; Flush(); } else buffer_ << pf; } UnsetColor(); return *this; } template < class Class,typename Pointer > void Log( Pointer pf, Class& c ) { if ( logflags_ & loglevel_ ) { (c.*pf)( buffer_ ); } } }; protected: Logging( ) { streamIDs_.push_back( LOG_ERR ); streamIDs_.push_back( LOG_DEBUG ); streamIDs_.push_back( LOG_INFO ); } ~Logging() { IdVecCIter it = streamIDs_.end(); for ( ; it != streamIDs_.begin(); --it ) { delete streammap_[*it]; streammap_[*it] = 0; } if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_ << '\n' << TimeString() << ": LOG END" << std::endl; logfileWoTime_ << std::endl; logfile_.close(); logfileWoTime_.close(); } // delete the MatlabLogStream matlabLogStreamPtr->Flush(); matlabLogFile_.close(); delete matlabLogStreamPtr; matlabLogStreamPtr = 0; } public: /** \brief setup loglevel, logfilename \param logflags any OR'd combination of flags \param logfile filename for log, can contain paths, but creation will fail if dir is non-existant **/ void Create (unsigned int logflags = LOG_FILE | LOG_CONSOLE | LOG_ERR, std::string logfile = "dune_stokes", std::string logdir = std::string() ) { logflags_ = logflags; //if we get a logdir from parameters append path seperator, othwersie leave empty //enables us to use logdir unconditionally further down if ( !logdir.empty() ) logdir += "/"; filename_ = logdir + logfile + "_time.log"; Stuff::testCreateDirectory( filename_ ); //could assert this if i figure out why errno is != EEXIST filenameWoTime_ = logdir + logfile + ".log"; if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_.open ( filename_.c_str() ); assert( logfile_.is_open() ); logfileWoTime_.open ( filenameWoTime_.c_str() ); assert( logfileWoTime_.is_open() ); } IdVecCIter it = streamIDs_.begin(); for ( ; it != streamIDs_.end(); ++it ) { flagmap_[*it] = logflags; streammap_[*it] = new LogStream( *it, flagmap_[*it], logfile_, logfileWoTime_ ); } // create the MatlabLogStream std::string matlabLogFileName = logdir + logfile + "_matlab.m"; Stuff::testCreateDirectory( matlabLogFileName ); //could assert this if i figure out why errno is != EEXIST matlabLogFile_.open( matlabLogFileName.c_str() ); assert( matlabLogFile_.is_open() ); matlabLogStreamPtr = new MatlabLogStream( LOG_FILE, logflags_, matlabLogFile_ ); } void SetPrefix( std::string prefix ) { /// begin dtor IdVecCIter it = streamIDs_.end(); for ( ; it != streamIDs_.begin(); --it ) { delete streammap_[*it]; streammap_[*it]=0; } if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_ << '\n' << TimeString() << ": LOG END" << std::endl; logfileWoTime_ << std::endl; logfile_.close(); logfileWoTime_.close(); } // delete the MatlabLogStream matlabLogStreamPtr->Flush(); matlabLogFile_.close(); delete matlabLogStreamPtr; matlabLogStreamPtr = 0; /// end dtor Create ( logflags_, prefix ); } void SetStreamFlags( LogFlags stream, int flags ) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); //this might result in logging to diff targtes, so we flush the current targets flagmap_[stream] = flags; } int GetStreamFlags( LogFlags stream ) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); return flagmap_[stream]; } /** \name Log funcs for member-function pointers * \{ */ template < typename Pointer, class Class > void LogDebug( Pointer pf, Class& c ) { if ( ( logflags_ & LOG_DEBUG ) ) Log( pf, c, LOG_DEBUG ); } template < class Class,typename Pointer > void LogInfo( Pointer pf , Class& c ) { if ( ( logflags_ & LOG_INFO ) ) Log( pf, c, LOG_INFO ); } template < typename Pointer, class Class > void LogErr( Pointer pf, Class& c ) { if ( ( logflags_ & LOG_ERR ) ) Log( pf, c, LOG_ERR ); } template < typename Pointer, class Class > void Log( void ( Class::*pf )(std::ostream&) const, Class& c, LogFlags stream) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); if ( ( flagmap_[stream] & LOG_CONSOLE ) != 0 ) (c.*pf)( std::cout ); if ( ( flagmap_[stream] & LOG_FILE ) != 0 ) (c.*pf)( logfile_ ); } template < class Class,typename Pointer > void Log( Pointer pf, Class& c, LogFlags stream) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); if ( ( flagmap_[stream] & LOG_CONSOLE ) != 0 ) (c.*pf)( std::cout ); if ( ( flagmap_[stream] & LOG_FILE ) != 0 ) { (c.*pf)( logfile_ ); (c.*pf)( logfileWoTime_ ); } } /** \} */ /** \name Log funcs for basic types/classes * \{ */ template < class Class > void LogDebug( Class c ) { if ( ( logflags_ & LOG_DEBUG ) ) Log( c, LOG_DEBUG ); } template < class Class > void LogInfo( Class c ) { if ( ( logflags_ & LOG_INFO ) ) Log( c, LOG_INFO ); } template < class Class > void LogErr( Class c ) { if ( ( logflags_ & LOG_ERR ) ) Log( c, LOG_ERR ); } template < class Class > void Log( Class c, LogFlags stream ) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); if ( ( flagmap_[stream] & LOG_CONSOLE ) != 0 ) std::cout << c; if ( ( flagmap_[stream] & LOG_FILE ) != 0 ) { logfile_ << c; logfileWoTime_ << c; } } /** \} */ LogStream& GetStream(int stream) { assert( streammap_[(LogFlags)stream] ); return *streammap_[(LogFlags)stream]; } LogStream& Err() { return GetStream( LOG_ERR ); } LogStream& Info() { return GetStream( LOG_INFO ); } LogStream& Dbg() { return GetStream( LOG_DEBUG ); } MatlabLogStream& Matlab() { return *matlabLogStreamPtr; } static std::string TimeString() { const time_t cur_time = time( NULL ); return ctime ( &cur_time ); } int AddStream( int flags ) { // assert( streamIDs_.find( streamID ) == streamIDs_.end() ); static int streamID_int = 16; streamID_int <<= 2; LogFlags streamID = (LogFlags) streamID_int; streamIDs_.push_back( streamID ); flagmap_[streamID] = flags | streamID; streammap_[streamID] = new LogStream( streamID, flagmap_[streamID], logfile_, logfileWoTime_ ); return streamID_int; } void Resume( LogStream::PriorityType prio = LogStream::default_suspend_priority ) { for ( StreamMap::iterator it = streammap_.begin(); it != streammap_.end(); ++it ) { it->second->Resume( prio ); } } void Suspend( LogStream::PriorityType prio = LogStream::default_suspend_priority ) { for ( StreamMap::iterator it = streammap_.begin(); it != streammap_.end(); ++it ) { it->second->Suspend( prio ); } } private: std::string filename_; std::string filenameWoTime_; std::ofstream logfile_; std::ofstream logfileWoTime_; std::ofstream matlabLogFile_; typedef std::map<LogFlags,int> FlagMap; FlagMap flagmap_; typedef std::map<LogFlags,LogStream*> StreamMap; StreamMap streammap_; typedef std::vector<LogFlags> IdVec; typedef std::vector<LogFlags>::const_iterator IdVecCIter; IdVec streamIDs_; int logflags_; MatlabLogStream* matlabLogStreamPtr; friend Logging& Logger (); }; ///global Logging instance Logging& Logger () { static Logging log; return log; } #endif <commit_msg>automatic resume/suspend guards for Logger<commit_after>/** * \file logging.hh * \brief logging **/ #ifndef LOGGING_HH_INCLUDED #define LOGGING_HH_INCLUDED #include <fstream> #include <ostream> #include <sstream> #include <ctime> #include <iomanip> #include <map> #include <assert.h> #include "misc.hh" class Logging; Logging& Logger (); /** \brief handles all logging **/ class Logging { public: enum LogFlags{ LOG_NONE = 1, LOG_ERR = 2, LOG_INFO = 4, LOG_DEBUG = 8, LOG_CONSOLE = 16, LOG_FILE = 32 }; //! only for logging to a single file which should then be executabla by matlab class MatlabLogStream { public: MatlabLogStream( LogFlags loglevel, int& logflags, std::ofstream& logFile ) : matlabLogFile_( logFile ), loglevel_(loglevel), logflags_(logflags), suspended_logflags_(logflags) {} ~MatlabLogStream(){} template < typename T > MatlabLogStream& operator << ( T in ) { if ( logflags_ & loglevel_ ) buffer_ << in; return *this; } MatlabLogStream& operator << ( MatlabLogStream& ( *pf )(MatlabLogStream&) ) { if ( logflags_ & loglevel_ ) buffer_ << pf; return *this; } MatlabLogStream& operator << ( std::ostream& ( *pf )(std::ostream &) ) { if ( logflags_ & loglevel_ ) { if ( pf == (std::ostream& ( * )(std::ostream&))std::endl ) { //flush buffer into stream buffer_ << "\n"; Flush(); } else { buffer_ << pf; } } return *this; } void Flush() { matlabLogFile_ << buffer_.str(); matlabLogFile_.flush(); buffer_.flush(); buffer_.str("");// clear the buffer } void Suspend() { //don't accidentally invalidate flags if already suspended if ( !is_suspended_ ) { suspended_logflags_ = logflags_; logflags_ = 1; } is_suspended_ = true; } void Resume() { if ( is_suspended_ ) logflags_ = suspended_logflags_; is_suspended_ = false; } private: std::stringstream buffer_; std::ofstream& matlabLogFile_; LogFlags loglevel_; int& logflags_; int suspended_logflags_; bool is_suspended_; }; class LogStream //: virtual public std::ostream { public: typedef int PriorityType; static const PriorityType default_suspend_priority = 0; protected: LogFlags loglevel_; int& logflags_; int suspended_logflags_; std::stringstream buffer_; std::ofstream& logfile_; std::ofstream& logfileWoTime_; bool is_suspended_; PriorityType suspend_priority_; public: LogStream( LogFlags loglevel, int& logflags, std::ofstream& file, std::ofstream& fileWoTime ) : loglevel_(loglevel), logflags_(logflags), suspended_logflags_(logflags), logfile_(file), logfileWoTime_( fileWoTime ), is_suspended_(false), suspend_priority_( default_suspend_priority ) {} ~LogStream() { Flush(); } template < typename T > LogStream& operator << ( T in ) { SetColor(); if ( logflags_ & loglevel_ ) buffer_ << in; UnsetColor(); return *this; } void Suspend( PriorityType priority = default_suspend_priority ) { //the suspend_priority_ mechanism provides a way to silence streams from 'higher' modules suspend_priority_ = std::max( priority, suspend_priority_ ); { //don't accidentally invalidate flags if already suspended if ( !is_suspended_ ) { suspended_logflags_ = logflags_; logflags_ = 1; } is_suspended_ = true; } } void Resume( PriorityType priority = default_suspend_priority ) { if ( priority >= suspend_priority_ ) { if ( is_suspended_ ) logflags_ = suspended_logflags_; is_suspended_ = false; suspend_priority_ = default_suspend_priority; } } void Flush() { if ( logflags_ & loglevel_ ) { //flush buffer into stream if ( ( logflags_ & LOG_CONSOLE ) != 0 ) { std::cout << buffer_.str();// << std::endl; std::cout .flush(); } if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_ << "\n" << TimeString() << buffer_.str() << std::endl; logfileWoTime_ << buffer_.str();// << std::endl; logfile_.flush(); logfileWoTime_.flush(); } buffer_.flush(); buffer_.str("");// clear the buffer } } void SetColor() { // if ( logflags_ & LOG_INFO ) { // buffer_ << "\033[21;31m"; // } } void UnsetColor() { // buffer_ << "\033[0m"; } //template < class Class > LogStream& operator << ( LogStream& ( *pf )(LogStream&) ) { if ( logflags_ & loglevel_ ) buffer_ << pf; return *this; } LogStream& operator << ( std::ostream& ( *pf )(std::ostream &) ) { SetColor(); if ( logflags_ & loglevel_ ) { if ( pf == (std::ostream& ( * )(std::ostream&))std::endl ) { //flush buffer into stream buffer_ << "\n"; Flush(); } else buffer_ << pf; } UnsetColor(); return *this; } template < class Class,typename Pointer > void Log( Pointer pf, Class& c ) { if ( logflags_ & loglevel_ ) { (c.*pf)( buffer_ ); } } }; protected: Logging( ) { streamIDs_.push_back( LOG_ERR ); streamIDs_.push_back( LOG_DEBUG ); streamIDs_.push_back( LOG_INFO ); } ~Logging() { IdVecCIter it = streamIDs_.end(); for ( ; it != streamIDs_.begin(); --it ) { delete streammap_[*it]; streammap_[*it] = 0; } if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_ << '\n' << TimeString() << ": LOG END" << std::endl; logfileWoTime_ << std::endl; logfile_.close(); logfileWoTime_.close(); } // delete the MatlabLogStream matlabLogStreamPtr->Flush(); matlabLogFile_.close(); delete matlabLogStreamPtr; matlabLogStreamPtr = 0; } public: /** \brief setup loglevel, logfilename \param logflags any OR'd combination of flags \param logfile filename for log, can contain paths, but creation will fail if dir is non-existant **/ void Create (unsigned int logflags = LOG_FILE | LOG_CONSOLE | LOG_ERR, std::string logfile = "dune_stokes", std::string logdir = std::string() ) { logflags_ = logflags; //if we get a logdir from parameters append path seperator, othwersie leave empty //enables us to use logdir unconditionally further down if ( !logdir.empty() ) logdir += "/"; filename_ = logdir + logfile + "_time.log"; Stuff::testCreateDirectory( filename_ ); //could assert this if i figure out why errno is != EEXIST filenameWoTime_ = logdir + logfile + ".log"; if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_.open ( filename_.c_str() ); assert( logfile_.is_open() ); logfileWoTime_.open ( filenameWoTime_.c_str() ); assert( logfileWoTime_.is_open() ); } IdVecCIter it = streamIDs_.begin(); for ( ; it != streamIDs_.end(); ++it ) { flagmap_[*it] = logflags; streammap_[*it] = new LogStream( *it, flagmap_[*it], logfile_, logfileWoTime_ ); } // create the MatlabLogStream std::string matlabLogFileName = logdir + logfile + "_matlab.m"; Stuff::testCreateDirectory( matlabLogFileName ); //could assert this if i figure out why errno is != EEXIST matlabLogFile_.open( matlabLogFileName.c_str() ); assert( matlabLogFile_.is_open() ); matlabLogStreamPtr = new MatlabLogStream( LOG_FILE, logflags_, matlabLogFile_ ); } void SetPrefix( std::string prefix ) { /// begin dtor IdVecCIter it = streamIDs_.end(); for ( ; it != streamIDs_.begin(); --it ) { delete streammap_[*it]; streammap_[*it]=0; } if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_ << '\n' << TimeString() << ": LOG END" << std::endl; logfileWoTime_ << std::endl; logfile_.close(); logfileWoTime_.close(); } // delete the MatlabLogStream matlabLogStreamPtr->Flush(); matlabLogFile_.close(); delete matlabLogStreamPtr; matlabLogStreamPtr = 0; /// end dtor Create ( logflags_, prefix ); } void SetStreamFlags( LogFlags stream, int flags ) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); //this might result in logging to diff targtes, so we flush the current targets flagmap_[stream] = flags; } int GetStreamFlags( LogFlags stream ) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); return flagmap_[stream]; } /** \name Log funcs for member-function pointers * \{ */ template < typename Pointer, class Class > void LogDebug( Pointer pf, Class& c ) { if ( ( logflags_ & LOG_DEBUG ) ) Log( pf, c, LOG_DEBUG ); } template < class Class,typename Pointer > void LogInfo( Pointer pf , Class& c ) { if ( ( logflags_ & LOG_INFO ) ) Log( pf, c, LOG_INFO ); } template < typename Pointer, class Class > void LogErr( Pointer pf, Class& c ) { if ( ( logflags_ & LOG_ERR ) ) Log( pf, c, LOG_ERR ); } template < typename Pointer, class Class > void Log( void ( Class::*pf )(std::ostream&) const, Class& c, LogFlags stream) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); if ( ( flagmap_[stream] & LOG_CONSOLE ) != 0 ) (c.*pf)( std::cout ); if ( ( flagmap_[stream] & LOG_FILE ) != 0 ) (c.*pf)( logfile_ ); } template < class Class,typename Pointer > void Log( Pointer pf, Class& c, LogFlags stream) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); if ( ( flagmap_[stream] & LOG_CONSOLE ) != 0 ) (c.*pf)( std::cout ); if ( ( flagmap_[stream] & LOG_FILE ) != 0 ) { (c.*pf)( logfile_ ); (c.*pf)( logfileWoTime_ ); } } /** \} */ /** \name Log funcs for basic types/classes * \{ */ template < class Class > void LogDebug( Class c ) { if ( ( logflags_ & LOG_DEBUG ) ) Log( c, LOG_DEBUG ); } template < class Class > void LogInfo( Class c ) { if ( ( logflags_ & LOG_INFO ) ) Log( c, LOG_INFO ); } template < class Class > void LogErr( Class c ) { if ( ( logflags_ & LOG_ERR ) ) Log( c, LOG_ERR ); } template < class Class > void Log( Class c, LogFlags stream ) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); if ( ( flagmap_[stream] & LOG_CONSOLE ) != 0 ) std::cout << c; if ( ( flagmap_[stream] & LOG_FILE ) != 0 ) { logfile_ << c; logfileWoTime_ << c; } } /** \} */ LogStream& GetStream(int stream) { assert( streammap_[(LogFlags)stream] ); return *streammap_[(LogFlags)stream]; } LogStream& Err() { return GetStream( LOG_ERR ); } LogStream& Info() { return GetStream( LOG_INFO ); } LogStream& Dbg() { return GetStream( LOG_DEBUG ); } MatlabLogStream& Matlab() { return *matlabLogStreamPtr; } static std::string TimeString() { const time_t cur_time = time( NULL ); return ctime ( &cur_time ); } int AddStream( int flags ) { // assert( streamIDs_.find( streamID ) == streamIDs_.end() ); static int streamID_int = 16; streamID_int <<= 2; LogFlags streamID = (LogFlags) streamID_int; streamIDs_.push_back( streamID ); flagmap_[streamID] = flags | streamID; streammap_[streamID] = new LogStream( streamID, flagmap_[streamID], logfile_, logfileWoTime_ ); return streamID_int; } void Resume( LogStream::PriorityType prio = LogStream::default_suspend_priority ) { for ( StreamMap::iterator it = streammap_.begin(); it != streammap_.end(); ++it ) { it->second->Resume( prio ); } } void Suspend( LogStream::PriorityType prio = LogStream::default_suspend_priority ) { for ( StreamMap::iterator it = streammap_.begin(); it != streammap_.end(); ++it ) { it->second->Suspend( prio ); } } struct SuspendLocal { LogStream::PriorityType prio_; SuspendLocal( LogStream::PriorityType prio = LogStream::default_suspend_priority ) :prio_(prio) { Logger().Suspend( prio_ ); } ~SuspendLocal() { Logger().Resume( prio_ ); } }; struct ResumeLocal { LogStream::PriorityType prio_; ResumeLocal( LogStream::PriorityType prio = LogStream::default_suspend_priority ) :prio_(prio) { Logger().Resume( prio_ ); } ~ResumeLocal() { Logger().Suspend( prio_ ); } }; private: std::string filename_; std::string filenameWoTime_; std::ofstream logfile_; std::ofstream logfileWoTime_; std::ofstream matlabLogFile_; typedef std::map<LogFlags,int> FlagMap; FlagMap flagmap_; typedef std::map<LogFlags,LogStream*> StreamMap; StreamMap streammap_; typedef std::vector<LogFlags> IdVec; typedef std::vector<LogFlags>::const_iterator IdVecCIter; IdVec streamIDs_; int logflags_; MatlabLogStream* matlabLogStreamPtr; friend Logging& Logger (); }; ///global Logging instance Logging& Logger () { static Logging log; return log; } #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** 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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "importmanagerview.h" #include "importswidget.h" #include <rewritingexception.h> namespace QmlDesigner { ImportManagerView::ImportManagerView(QObject *parent) : AbstractView(parent), m_importsWidget(0) { } ImportManagerView::~ImportManagerView() { } bool ImportManagerView::hasWidget() const { return true; } WidgetInfo ImportManagerView::widgetInfo() { if (m_importsWidget == 0) { m_importsWidget = new ImportsWidget; connect(m_importsWidget, SIGNAL(removeImport(Import)), this, SLOT(removeImport(Import))); connect(m_importsWidget, SIGNAL(addImport(Import)), this, SLOT(addImport(Import))); if (model()) m_importsWidget->setImports(model()->imports()); } return createWidgetInfo(m_importsWidget, 0, "ImportManager", WidgetInfo::LeftPane, 1); } void ImportManagerView::modelAttached(Model *model) { AbstractView::modelAttached(model); if (m_importsWidget) { m_importsWidget->setImports(model->imports()); m_importsWidget->setPossibleImports(model->possibleImports()); m_importsWidget->setUsedImports(model->usedImports()); } } void ImportManagerView::modelAboutToBeDetached(Model *model) { if (m_importsWidget) { m_importsWidget->removeImports(); m_importsWidget->removePossibleImports(); m_importsWidget->removeUsedImports(); } AbstractView::modelAboutToBeDetached(model); } void ImportManagerView::nodeCreated(const ModelNode &/*createdNode*/) { if (m_importsWidget) m_importsWidget->setUsedImports(model()->usedImports()); } void ImportManagerView::nodeAboutToBeRemoved(const ModelNode &/*removedNode*/) { if (m_importsWidget) m_importsWidget->setUsedImports(model()->usedImports()); } void ImportManagerView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::nodeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::nodeIdChanged(const ModelNode &/*node*/, const QString &/*newId*/, const QString &/*oldId*/) { } void ImportManagerView::propertiesAboutToBeRemoved(const QList<AbstractProperty> &/*propertyList*/) { } void ImportManagerView::propertiesRemoved(const QList<AbstractProperty> &/*propertyList*/) { } void ImportManagerView::variantPropertiesChanged(const QList<VariantProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::bindingPropertiesChanged(const QList<BindingProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::rootNodeTypeChanged(const QString &/*type*/, int /*majorVersion*/, int /*minorVersion*/) { } void ImportManagerView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &/*propertyList*/) { } void ImportManagerView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/) { } void ImportManagerView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/) { } void ImportManagerView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/) { } void ImportManagerView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/) { } void ImportManagerView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/) { } void ImportManagerView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/) { } void ImportManagerView::nodeSourceChanged(const ModelNode &/*modelNode*/, const QString &/*newNodeSource*/) { } void ImportManagerView::rewriterBeginTransaction() { } void ImportManagerView::rewriterEndTransaction() { } void ImportManagerView::currentStateChanged(const ModelNode &/*node*/) { } void ImportManagerView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/) { } void ImportManagerView::fileUrlChanged(const QUrl &/*oldUrl*/, const QUrl &/*newUrl*/) { } void ImportManagerView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/) { } void ImportManagerView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/) { if (m_importsWidget) { m_importsWidget->setImports(model()->imports()); m_importsWidget->setPossibleImports(model()->possibleImports()); m_importsWidget->setUsedImports(model()->usedImports()); } } void ImportManagerView::auxiliaryDataChanged(const ModelNode &/*node*/, const PropertyName &/*name*/, const QVariant &/*data*/) { } void ImportManagerView::customNotification(const AbstractView * /*view*/, const QString &/*identifier*/, const QList<ModelNode> &/*nodeList*/, const QList<QVariant> &/*data*/) { } void ImportManagerView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/) { } void ImportManagerView::removeImport(const Import &import) { try { if (model()) model()->changeImports(QList<Import>(), QList<Import>() << import); } catch (RewritingException &e) { e.showException(); } } void ImportManagerView::addImport(const Import &import) { try { if (model()) model()->changeImports(QList<Import>() << import, QList<Import>()); } catch (RewritingException &e) { e.showException(); } } } // namespace QmlDesigner <commit_msg>Fix for import management<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** 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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "importmanagerview.h" #include "importswidget.h" #include <rewritingexception.h> #include <qmldesignerplugin.h> namespace QmlDesigner { ImportManagerView::ImportManagerView(QObject *parent) : AbstractView(parent), m_importsWidget(0) { } ImportManagerView::~ImportManagerView() { } bool ImportManagerView::hasWidget() const { return true; } WidgetInfo ImportManagerView::widgetInfo() { if (m_importsWidget == 0) { m_importsWidget = new ImportsWidget; connect(m_importsWidget, SIGNAL(removeImport(Import)), this, SLOT(removeImport(Import))); connect(m_importsWidget, SIGNAL(addImport(Import)), this, SLOT(addImport(Import))); if (model()) m_importsWidget->setImports(model()->imports()); } return createWidgetInfo(m_importsWidget, 0, "ImportManager", WidgetInfo::LeftPane, 1); } void ImportManagerView::modelAttached(Model *model) { AbstractView::modelAttached(model); if (m_importsWidget) { m_importsWidget->setImports(model->imports()); m_importsWidget->setPossibleImports(model->possibleImports()); m_importsWidget->setUsedImports(model->usedImports()); } } void ImportManagerView::modelAboutToBeDetached(Model *model) { if (m_importsWidget) { m_importsWidget->removeImports(); m_importsWidget->removePossibleImports(); m_importsWidget->removeUsedImports(); } AbstractView::modelAboutToBeDetached(model); } void ImportManagerView::nodeCreated(const ModelNode &/*createdNode*/) { if (m_importsWidget) m_importsWidget->setUsedImports(model()->usedImports()); } void ImportManagerView::nodeAboutToBeRemoved(const ModelNode &/*removedNode*/) { if (m_importsWidget) m_importsWidget->setUsedImports(model()->usedImports()); } void ImportManagerView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::nodeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::nodeIdChanged(const ModelNode &/*node*/, const QString &/*newId*/, const QString &/*oldId*/) { } void ImportManagerView::propertiesAboutToBeRemoved(const QList<AbstractProperty> &/*propertyList*/) { } void ImportManagerView::propertiesRemoved(const QList<AbstractProperty> &/*propertyList*/) { } void ImportManagerView::variantPropertiesChanged(const QList<VariantProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::bindingPropertiesChanged(const QList<BindingProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) { } void ImportManagerView::rootNodeTypeChanged(const QString &/*type*/, int /*majorVersion*/, int /*minorVersion*/) { } void ImportManagerView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &/*propertyList*/) { } void ImportManagerView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/) { } void ImportManagerView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/) { } void ImportManagerView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/) { } void ImportManagerView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/) { } void ImportManagerView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/) { } void ImportManagerView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/) { } void ImportManagerView::nodeSourceChanged(const ModelNode &/*modelNode*/, const QString &/*newNodeSource*/) { } void ImportManagerView::rewriterBeginTransaction() { } void ImportManagerView::rewriterEndTransaction() { } void ImportManagerView::currentStateChanged(const ModelNode &/*node*/) { } void ImportManagerView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/) { } void ImportManagerView::fileUrlChanged(const QUrl &/*oldUrl*/, const QUrl &/*newUrl*/) { } void ImportManagerView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/) { } void ImportManagerView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/) { if (m_importsWidget) { m_importsWidget->setImports(model()->imports()); m_importsWidget->setPossibleImports(model()->possibleImports()); m_importsWidget->setUsedImports(model()->usedImports()); } } void ImportManagerView::auxiliaryDataChanged(const ModelNode &/*node*/, const PropertyName &/*name*/, const QVariant &/*data*/) { } void ImportManagerView::customNotification(const AbstractView * /*view*/, const QString &/*identifier*/, const QList<ModelNode> &/*nodeList*/, const QList<QVariant> &/*data*/) { } void ImportManagerView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/) { } void ImportManagerView::removeImport(const Import &import) { try { if (model()) model()->changeImports(QList<Import>(), QList<Import>() << import); } catch (RewritingException &e) { e.showException(); } } void ImportManagerView::addImport(const Import &import) { try { if (model()) model()->changeImports(QList<Import>() << import, QList<Import>()); } catch (RewritingException &e) { e.showException(); } QmlDesignerPlugin::instance()->currentDesignDocument()->updateSubcomponentManager(); } } // namespace QmlDesigner <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2287 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1346311 by johtaylo@johtaylo-jtincrementor-increment on 2016/11/27 03:00:04<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2288 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/********************************************************************************* * Copyright (c) 2013 David D. Marshall <ddmarsha@calpoly.edu> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Rob McDonald - initial code and implementation ********************************************************************************/ #ifndef eli_geom_intersect_intersect_surface_surface_hpp #define eli_geom_intersect_intersect_surface_surface_hpp #include <cmath> #include <vector> #include <list> #include <algorithm> #include "eli/code_eli.hpp" #include "eli/mutil/nls/newton_raphson_method.hpp" #include "eli/geom/point/distance.hpp" #include "eli/geom/curve/piecewise.hpp" #include "eli/geom/intersect/minimum_distance_bounding_box.hpp" namespace eli { namespace geom { namespace intersect { namespace internal { template <typename surface__> struct surf_surf_g_functor { const surface__ *s1; const surface__ *s2; typename surface__::point_type pt; typedef typename Eigen::Matrix<typename surface__::data_type, 4, 1> vec; vec operator()(const vec &x) const { typename surface__::data_type u1(x[0]), v1(x[1]); typename surface__::data_type u2(x[2]), v2(x[3]); vec rtn; typename surface__::data_type u1min, u1max, v1min, v1max; typename surface__::data_type u2min, u2max, v2min, v2max; s1->get_parameter_min(u1min,v1min); s1->get_parameter_max(u1max,v1max); s2->get_parameter_min(u2min,v2min); s2->get_parameter_max(u2max,v2max); u1=std::min(std::max(u1, u1min), u1max); v1=std::min(std::max(v1, v1min), v1max); u2=std::min(std::max(u2, u2min), u2max); v2=std::min(std::max(v2, v2min), v2max); typename surface__::point_type p1, p2, pave, disp, tvec; p1=s1->f(u1,v1); p2=s2->f(u2,v2); pave=(p1+p2)*0.5; disp=p2-p1; tvec=(s1->f_u(u1,v1).cross(s1->f_v(u1,v1))).cross(s2->f_u(u2,v2).cross(s2->f_v(u2,v2))); rtn(0)=disp(0); rtn(1)=disp(1); rtn(2)=disp(2); rtn(3)=tvec.dot(pave-pt); return rtn; } }; template <typename surface__> struct surf_surf_gp_functor { const surface__ *s1; const surface__ *s2; typename surface__::point_type pt; typedef typename Eigen::Matrix<typename surface__::data_type, 4, 1> vec; typedef typename Eigen::Matrix<typename surface__::data_type, 4, 4> mat; mat operator()(const vec &x) const { typename surface__::data_type u1(x[0]), v1(x[1]); typename surface__::data_type u2(x[2]), v2(x[3]); mat rtn; typename surface__::data_type u1min, u1max, v1min, v1max; typename surface__::data_type u2min, u2max, v2min, v2max; s1->get_parameter_min(u1min,v1min); s1->get_parameter_max(u1max,v1max); s2->get_parameter_min(u2min,v2min); s2->get_parameter_max(u2max,v2max); u1=std::min(std::max(u1, u1min), u1max); v1=std::min(std::max(v1, v1min), v1max); u2=std::min(std::max(u2, u2min), u2max); v2=std::min(std::max(v2, v2min), v2max); typename surface__::point_type S1u, S1v, S1uu, S1uv, S1vv; typename surface__::point_type S2u, S2v, S2uu, S2uv, S2vv; typename surface__::point_type p1, p2, pave, tvec, dist; p1=s1->f(u1,v1); p2=s2->f(u2,v2); pave=(p1+p2)*0.5; dist=pave-pt; S1u=s1->f_u(u1, v1); S1v=s1->f_v(u1, v1); S1uu=s1->f_uu(u1, v1); S1uv=s1->f_uv(u1, v1); S1vv=s1->f_vv(u1, v1); S2u=s2->f_u(u2, v2); S2v=s2->f_v(u2, v2); S2uu=s2->f_uu(u2, v2); S2uv=s2->f_uv(u2, v2); S2vv=s2->f_vv(u2, v2); tvec=(S1u.cross(S1v)).cross(S2u.cross(S2v)); rtn(0,0)=-S1u(0); rtn(0,1)=-S1v(0); rtn(0,2)=S2u(0); rtn(0,3)=S2v(0); rtn(1,0)=-S1u(1); rtn(1,1)=-S1v(1); rtn(1,2)=S2u(1); rtn(1,3)=S2v(1); rtn(2,0)=-S1u(2); rtn(2,1)=-S1v(2); rtn(2,2)=S2u(2); rtn(2,3)=S2v(2); // tvec.dot(dist); rtn(3,0)= dist.dot( ( S1uu.cross(S1v)+S1u.cross(S1uv) ).cross(S2u.cross(S2v)) ) + tvec.dot( S1u * 0.5 ); rtn(3,1)= dist.dot( ( S1uv.cross(S1v)+S1u.cross(S1vv) ).cross(S2u.cross(S2v)) ) + tvec.dot( S1v * 0.5 ); rtn(3,2)= dist.dot( (S1u.cross(S1v)).cross( S2uu.cross(S2v)+S2u.cross(S2uv) ) ) + tvec.dot( S2u * 0.5 ); rtn(3,3)= dist.dot( (S1u.cross(S1v)).cross( S2uv.cross(S2v)+S2u.cross(S2vv) ) ) + tvec.dot( S2v * 0.5 ); // TODO: What to do if matrix becomes singular? return rtn; } }; } template<typename surface__> typename surface__::index_type intersect(typename surface__::data_type &u1, typename surface__::data_type &v1, typename surface__::data_type &u2, typename surface__::data_type &v2, typename surface__::data_type &dist, const surface__ &s1in, const surface__ &s2in, const typename surface__::point_type &pt, const typename surface__::data_type &u01, const typename surface__::data_type &v01, const typename surface__::data_type &u02, const typename surface__::data_type &v02 ) { typedef eli::mutil::nls::newton_raphson_system_method<typename surface__::data_type, 4, 1> nonlinear_solver_type; nonlinear_solver_type nrm; internal::surf_surf_g_functor<surface__> g; internal::surf_surf_gp_functor<surface__> gp; typename surface__::data_type dist0; typename surface__::tolerance_type tol; typename surface__::data_type u1min, u1max, v1min, v1max; typename surface__::data_type u2min, u2max, v2min, v2max; surface__ s1 = s1in; surface__ s2 = s2in; // Shift surfaces to be centered at initial intersection point. This forces all coordinates to be close to zero // thereby increasing available precision for the calculations. s1.translate( -pt ); s2.translate( -pt ); typename surface__::point_type p0; p0 << 0.0, 0.0, 0.0; s1.get_parameter_min(u1min,v1min); s1.get_parameter_max(u1max,v1max); s2.get_parameter_min(u2min,v2min); s2.get_parameter_max(u2max,v2max); typename surface__::point_type p1, p2; p1=s1.f(u01,v01); p2=s2.f(u02,v02); // setup the functors g.s1=&s1; g.s2=&s2; g.pt=p0; gp.s1=&s1; gp.s2=&s2; gp.pt=p0; // setup the solver nrm.set_absolute_f_tolerance(tol.get_absolute_tolerance()); nrm.set_max_iteration(20); nrm.set_norm_type(nonlinear_solver_type::max_norm); if (s1.open_u()) { nrm.set_lower_condition(0, u1min, nonlinear_solver_type::IRC_EXCLUSIVE); nrm.set_upper_condition(0, u1max, nonlinear_solver_type::IRC_EXCLUSIVE); } else { nrm.set_periodic_condition(0, u1min, u1max); } if (s1.open_v()) { nrm.set_lower_condition(1, v1min, nonlinear_solver_type::IRC_EXCLUSIVE); nrm.set_upper_condition(1, v1max, nonlinear_solver_type::IRC_EXCLUSIVE); } else { nrm.set_periodic_condition(1, v1min, v1max); } if (s2.open_u()) { nrm.set_lower_condition(2, u2min, nonlinear_solver_type::IRC_EXCLUSIVE); nrm.set_upper_condition(2, u2max, nonlinear_solver_type::IRC_EXCLUSIVE); } else { nrm.set_periodic_condition(2, u2min, u2max); } if (s2.open_v()) { nrm.set_lower_condition(3, v2min, nonlinear_solver_type::IRC_EXCLUSIVE); nrm.set_upper_condition(3, v2max, nonlinear_solver_type::IRC_EXCLUSIVE); } else { nrm.set_periodic_condition(3, v2min, v2max); } // set the initial guess typename nonlinear_solver_type::solution_matrix xinit, rhs, ans; xinit(0)=u01; xinit(1)=v01; xinit(2)=u02; xinit(3)=v02; nrm.set_initial_guess(xinit); rhs.setZero(); dist0=eli::geom::point::distance(p1, p2); // find the root typename surface__::index_type ret = nrm.find_root(ans, g, gp, rhs); if ( ret == nrm.converged ) { u1=ans(0); v1=ans(1); u2=ans(2); v2=ans(3); dist = eli::geom::point::distance(s1.f(u1, v1), s2.f(u2,v2)); // if( dist > 1e-6 ) // { // printf("d0: %g d: %g\n", dist0, dist ); // printf(" u01: %f u1: %f\n", u01, u1 ); // printf(" v01: %f v1: %f\n", v01, v1 ); // printf(" u02: %f u2: %f\n", u02, u2 ); // printf(" v02: %f v2: %f\n", v02, v2 ); // } if (dist<=dist0) { return ret; } ret = 3; // Converged, but worse answer than initial guess. } // couldn't find better answer so return initial guess u1=u01; v1=v01; u2=u02; v2=v02; dist=dist0; return ret; } } } } #endif <commit_msg>Introduce importance scale to point nearness in surface-surface intersect.<commit_after>/********************************************************************************* * Copyright (c) 2013 David D. Marshall <ddmarsha@calpoly.edu> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Rob McDonald - initial code and implementation ********************************************************************************/ #ifndef eli_geom_intersect_intersect_surface_surface_hpp #define eli_geom_intersect_intersect_surface_surface_hpp #include <cmath> #include <vector> #include <list> #include <algorithm> #include "eli/code_eli.hpp" #include "eli/mutil/nls/newton_raphson_method.hpp" #include "eli/geom/point/distance.hpp" #include "eli/geom/curve/piecewise.hpp" #include "eli/geom/intersect/minimum_distance_bounding_box.hpp" namespace eli { namespace geom { namespace intersect { namespace internal { template <typename surface__> struct surf_surf_g_functor { const surface__ *s1; const surface__ *s2; typename surface__::point_type pt; typename surface__::data_type k; typedef typename Eigen::Matrix<typename surface__::data_type, 4, 1> vec; vec operator()(const vec &x) const { typename surface__::data_type u1(x[0]), v1(x[1]); typename surface__::data_type u2(x[2]), v2(x[3]); vec rtn; typename surface__::data_type u1min, u1max, v1min, v1max; typename surface__::data_type u2min, u2max, v2min, v2max; s1->get_parameter_min(u1min,v1min); s1->get_parameter_max(u1max,v1max); s2->get_parameter_min(u2min,v2min); s2->get_parameter_max(u2max,v2max); u1=std::min(std::max(u1, u1min), u1max); v1=std::min(std::max(v1, v1min), v1max); u2=std::min(std::max(u2, u2min), u2max); v2=std::min(std::max(v2, v2min), v2max); typename surface__::point_type p1, p2, pave, disp, tvec; p1=s1->f(u1,v1); p2=s2->f(u2,v2); pave=(p1+p2)*0.5; disp=p2-p1; tvec=(s1->f_u(u1,v1).cross(s1->f_v(u1,v1))).cross(s2->f_u(u2,v2).cross(s2->f_v(u2,v2))); rtn(0)=disp(0); rtn(1)=disp(1); rtn(2)=disp(2); rtn(3)=k*tvec.dot(pave-pt); return rtn; } }; template <typename surface__> struct surf_surf_gp_functor { const surface__ *s1; const surface__ *s2; typename surface__::point_type pt; typename surface__::data_type k; typedef typename Eigen::Matrix<typename surface__::data_type, 4, 1> vec; typedef typename Eigen::Matrix<typename surface__::data_type, 4, 4> mat; mat operator()(const vec &x) const { typename surface__::data_type u1(x[0]), v1(x[1]); typename surface__::data_type u2(x[2]), v2(x[3]); mat rtn; typename surface__::data_type u1min, u1max, v1min, v1max; typename surface__::data_type u2min, u2max, v2min, v2max; s1->get_parameter_min(u1min,v1min); s1->get_parameter_max(u1max,v1max); s2->get_parameter_min(u2min,v2min); s2->get_parameter_max(u2max,v2max); u1=std::min(std::max(u1, u1min), u1max); v1=std::min(std::max(v1, v1min), v1max); u2=std::min(std::max(u2, u2min), u2max); v2=std::min(std::max(v2, v2min), v2max); typename surface__::point_type S1u, S1v, S1uu, S1uv, S1vv; typename surface__::point_type S2u, S2v, S2uu, S2uv, S2vv; typename surface__::point_type p1, p2, pave, tvec, dist; p1=s1->f(u1,v1); p2=s2->f(u2,v2); pave=(p1+p2)*0.5; dist=pave-pt; S1u=s1->f_u(u1, v1); S1v=s1->f_v(u1, v1); S1uu=s1->f_uu(u1, v1); S1uv=s1->f_uv(u1, v1); S1vv=s1->f_vv(u1, v1); S2u=s2->f_u(u2, v2); S2v=s2->f_v(u2, v2); S2uu=s2->f_uu(u2, v2); S2uv=s2->f_uv(u2, v2); S2vv=s2->f_vv(u2, v2); tvec=(S1u.cross(S1v)).cross(S2u.cross(S2v)); rtn(0,0)=-S1u(0); rtn(0,1)=-S1v(0); rtn(0,2)=S2u(0); rtn(0,3)=S2v(0); rtn(1,0)=-S1u(1); rtn(1,1)=-S1v(1); rtn(1,2)=S2u(1); rtn(1,3)=S2v(1); rtn(2,0)=-S1u(2); rtn(2,1)=-S1v(2); rtn(2,2)=S2u(2); rtn(2,3)=S2v(2); // tvec.dot(dist); rtn(3,0)= k*(dist.dot( ( S1uu.cross(S1v)+S1u.cross(S1uv) ).cross(S2u.cross(S2v)) ) + tvec.dot( S1u * 0.5 )); rtn(3,1)= k*(dist.dot( ( S1uv.cross(S1v)+S1u.cross(S1vv) ).cross(S2u.cross(S2v)) ) + tvec.dot( S1v * 0.5 )); rtn(3,2)= k*(dist.dot( (S1u.cross(S1v)).cross( S2uu.cross(S2v)+S2u.cross(S2uv) ) ) + tvec.dot( S2u * 0.5 )); rtn(3,3)= k*(dist.dot( (S1u.cross(S1v)).cross( S2uv.cross(S2v)+S2u.cross(S2vv) ) ) + tvec.dot( S2v * 0.5 )); // TODO: What to do if matrix becomes singular? return rtn; } }; } template<typename surface__> typename surface__::index_type intersect(typename surface__::data_type &u1, typename surface__::data_type &v1, typename surface__::data_type &u2, typename surface__::data_type &v2, typename surface__::data_type &dist, const surface__ &s1in, const surface__ &s2in, const typename surface__::point_type &pt, const typename surface__::data_type &u01, const typename surface__::data_type &v01, const typename surface__::data_type &u02, const typename surface__::data_type &v02 ) { typedef eli::mutil::nls::newton_raphson_system_method<typename surface__::data_type, 4, 1> nonlinear_solver_type; nonlinear_solver_type nrm; internal::surf_surf_g_functor<surface__> g; internal::surf_surf_gp_functor<surface__> gp; typename surface__::data_type dist0; typename surface__::tolerance_type tol; typename surface__::data_type u1min, u1max, v1min, v1max; typename surface__::data_type u2min, u2max, v2min, v2max; surface__ s1 = s1in; surface__ s2 = s2in; // Shift surfaces to be centered at initial intersection point. This forces all coordinates to be close to zero // thereby increasing available precision for the calculations. s1.translate( -pt ); s2.translate( -pt ); typename surface__::point_type p0; p0 << 0.0, 0.0, 0.0; s1.get_parameter_min(u1min,v1min); s1.get_parameter_max(u1max,v1max); s2.get_parameter_min(u2min,v2min); s2.get_parameter_max(u2max,v2max); typename surface__::point_type p1, p2; p1=s1.f(u01,v01); p2=s2.f(u02,v02); // Relative importance of nearness to base point. typename surface__::data_type k = 1.0e-3; // setup the functors g.s1=&s1; g.s2=&s2; g.pt=p0; g.k=k; gp.s1=&s1; gp.s2=&s2; gp.pt=p0; gp.k=k; // setup the solver nrm.set_absolute_f_tolerance(tol.get_absolute_tolerance()); nrm.set_max_iteration(20); nrm.set_norm_type(nonlinear_solver_type::max_norm); if (s1.open_u()) { nrm.set_lower_condition(0, u1min, nonlinear_solver_type::IRC_EXCLUSIVE); nrm.set_upper_condition(0, u1max, nonlinear_solver_type::IRC_EXCLUSIVE); } else { nrm.set_periodic_condition(0, u1min, u1max); } if (s1.open_v()) { nrm.set_lower_condition(1, v1min, nonlinear_solver_type::IRC_EXCLUSIVE); nrm.set_upper_condition(1, v1max, nonlinear_solver_type::IRC_EXCLUSIVE); } else { nrm.set_periodic_condition(1, v1min, v1max); } if (s2.open_u()) { nrm.set_lower_condition(2, u2min, nonlinear_solver_type::IRC_EXCLUSIVE); nrm.set_upper_condition(2, u2max, nonlinear_solver_type::IRC_EXCLUSIVE); } else { nrm.set_periodic_condition(2, u2min, u2max); } if (s2.open_v()) { nrm.set_lower_condition(3, v2min, nonlinear_solver_type::IRC_EXCLUSIVE); nrm.set_upper_condition(3, v2max, nonlinear_solver_type::IRC_EXCLUSIVE); } else { nrm.set_periodic_condition(3, v2min, v2max); } // set the initial guess typename nonlinear_solver_type::solution_matrix xinit, rhs, ans; xinit(0)=u01; xinit(1)=v01; xinit(2)=u02; xinit(3)=v02; nrm.set_initial_guess(xinit); rhs.setZero(); dist0=eli::geom::point::distance(p1, p2); // find the root typename surface__::index_type ret = nrm.find_root(ans, g, gp, rhs); if ( ret == nrm.converged ) { u1=ans(0); v1=ans(1); u2=ans(2); v2=ans(3); dist = eli::geom::point::distance(s1.f(u1, v1), s2.f(u2,v2)); // if( dist > 1e-6 ) // { // printf("d0: %g d: %g\n", dist0, dist ); // printf(" u01: %f u1: %f\n", u01, u1 ); // printf(" v01: %f v1: %f\n", v01, v1 ); // printf(" u02: %f u2: %f\n", u02, u2 ); // printf(" v02: %f v2: %f\n", v02, v2 ); // } if (dist<=dist0) { return ret; } ret = 3; // Converged, but worse answer than initial guess. } // couldn't find better answer so return initial guess u1=u01; v1=v01; u2=u02; v2=v02; dist=dist0; return ret; } } } } #endif <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2056 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1244798 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/03/08 03:00:10<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2057 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2726 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1599289 by chui@ocl-promo-incrementor on 2018/08/29 02:57:14<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2727 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreGLES2Support.h" #include "OgreLogManager.h" namespace Ogre { void GLES2Support::setConfigOption(const String &name, const String &value) { ConfigOptionMap::iterator it = mOptions.find(name); if (it == mOptions.end()) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Option named " + name + " does not exist.", "GLESSupport::setConfigOption"); } else { it->second.currentValue = value; } } ConfigOptionMap& GLES2Support::getConfigOptions(void) { return mOptions; } void GLES2Support::initialiseExtensions(void) { // Set version string const GLubyte* pcVer = glGetString(GL_VERSION); assert(pcVer && "Problems getting GL version string using glGetString"); String tmpStr = (const char*)pcVer; LogManager::getSingleton().logMessage("GL_VERSION = " + tmpStr); mVersion = tmpStr.substr(0, tmpStr.find(" ")); // Get vendor const GLubyte* pcVendor = glGetString(GL_VENDOR); tmpStr = (const char*)pcVendor; LogManager::getSingleton().logMessage("GL_VENDOR = " + tmpStr); mVendor = tmpStr.substr(0, tmpStr.find(" ")); // Get renderer const GLubyte* pcRenderer = glGetString(GL_RENDERER); tmpStr = (const char*)pcRenderer; LogManager::getSingleton().logMessage("GL_RENDERER = " + tmpStr); // Set extension list std::stringstream ext; String str; const GLubyte* pcExt = glGetString(GL_EXTENSIONS); LogManager::getSingleton().logMessage("GL_EXTENSIONS = " + String((const char*)pcExt)); assert(pcExt && "Problems getting GL extension string using glGetString"); ext << pcExt; while (ext >> str) { printf("EXT: %s\n", str.c_str()); extensionList.insert(str); } } bool GLES2Support::checkExtension(const String& ext) const { if(extensionList.find(ext) == extensionList.end()) return false; return true; } } <commit_msg>Change a printf to logMessage<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreGLES2Support.h" #include "OgreLogManager.h" namespace Ogre { void GLES2Support::setConfigOption(const String &name, const String &value) { ConfigOptionMap::iterator it = mOptions.find(name); if (it == mOptions.end()) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Option named " + name + " does not exist.", "GLESSupport::setConfigOption"); } else { it->second.currentValue = value; } } ConfigOptionMap& GLES2Support::getConfigOptions(void) { return mOptions; } void GLES2Support::initialiseExtensions(void) { // Set version string const GLubyte* pcVer = glGetString(GL_VERSION); assert(pcVer && "Problems getting GL version string using glGetString"); String tmpStr = (const char*)pcVer; LogManager::getSingleton().logMessage("GL_VERSION = " + tmpStr); mVersion = tmpStr.substr(0, tmpStr.find(" ")); // Get vendor const GLubyte* pcVendor = glGetString(GL_VENDOR); tmpStr = (const char*)pcVendor; LogManager::getSingleton().logMessage("GL_VENDOR = " + tmpStr); mVendor = tmpStr.substr(0, tmpStr.find(" ")); // Get renderer const GLubyte* pcRenderer = glGetString(GL_RENDERER); tmpStr = (const char*)pcRenderer; LogManager::getSingleton().logMessage("GL_RENDERER = " + tmpStr); // Set extension list std::stringstream ext; String str; const GLubyte* pcExt = glGetString(GL_EXTENSIONS); LogManager::getSingleton().logMessage("GL_EXTENSIONS = " + String((const char*)pcExt)); assert(pcExt && "Problems getting GL extension string using glGetString"); ext << pcExt; while (ext >> str) { LogManager::getSingleton().logMessage("EXT:" + str); extensionList.insert(str); } } bool GLES2Support::checkExtension(const String& ext) const { if(extensionList.find(ext) == extensionList.end()) return false; return true; } } <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2409 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1403149 by johtaylo@johtaylo-jtincrementor-increment on 2017/04/27 03:00:04<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2410 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/object_store.h" #include "vm/dart_entry.h" #include "vm/exceptions.h" #include "vm/isolate.h" #include "vm/object.h" #include "vm/raw_object.h" #include "vm/resolver.h" #include "vm/symbols.h" #include "vm/visitor.h" namespace dart { ObjectStore::ObjectStore() { #define INIT_FIELD(Type, name) name##_ = Type::null(); OBJECT_STORE_FIELD_LIST(INIT_FIELD, INIT_FIELD) #undef INIT_FIELD for (RawObject** current = from(); current <= to(); current++) { ASSERT(*current == Object::null()); } } ObjectStore::~ObjectStore() {} void ObjectStore::VisitObjectPointers(ObjectPointerVisitor* visitor) { ASSERT(visitor != NULL); visitor->VisitPointers(from(), to()); } void ObjectStore::Init(Isolate* isolate) { ASSERT(isolate->object_store() == NULL); ObjectStore* store = new ObjectStore(); isolate->set_object_store(store); } #ifndef PRODUCT void ObjectStore::PrintToJSONObject(JSONObject* jsobj) { if (!FLAG_support_service) { return; } jsobj->AddProperty("type", "_ObjectStore"); { JSONObject fields(jsobj, "fields"); Object& value = Object::Handle(); #define PRINT_OBJECT_STORE_FIELD(type, name) \ value = name##_; \ fields.AddProperty(#name "_", value); OBJECT_STORE_FIELD_LIST(PRINT_OBJECT_STORE_FIELD, PRINT_OBJECT_STORE_FIELD); #undef PRINT_OBJECT_STORE_FIELD } } #endif // !PRODUCT RawError* ObjectStore::PreallocateObjects() { Thread* thread = Thread::Current(); Isolate* isolate = thread->isolate(); Zone* zone = thread->zone(); ASSERT(isolate != NULL && isolate->object_store() == this); if (this->stack_overflow() != Instance::null()) { ASSERT(this->out_of_memory() != Instance::null()); ASSERT(this->preallocated_stack_trace() != StackTrace::null()); return Error::null(); } ASSERT(this->stack_overflow() == Instance::null()); ASSERT(this->out_of_memory() == Instance::null()); ASSERT(this->preallocated_stack_trace() == StackTrace::null()); this->pending_deferred_loads_ = GrowableObjectArray::New(); this->closure_functions_ = GrowableObjectArray::New(); this->resume_capabilities_ = GrowableObjectArray::New(); this->exit_listeners_ = GrowableObjectArray::New(); this->error_listeners_ = GrowableObjectArray::New(); Object& result = Object::Handle(); const Library& library = Library::Handle(Library::CoreLibrary()); result = DartLibraryCalls::InstanceCreate(library, Symbols::StackOverflowError(), Symbols::Dot(), Object::empty_array()); if (result.IsError()) { return Error::Cast(result).raw(); } set_stack_overflow(Instance::Cast(result)); result = DartLibraryCalls::InstanceCreate(library, Symbols::OutOfMemoryError(), Symbols::Dot(), Object::empty_array()); if (result.IsError()) { return Error::Cast(result).raw(); } set_out_of_memory(Instance::Cast(result)); // Allocate pre-allocated unhandled exception object initialized with the // pre-allocated OutOfMemoryError. const UnhandledException& unhandled_exception = UnhandledException::Handle(UnhandledException::New( Instance::Cast(result), StackTrace::Handle(zone))); set_preallocated_unhandled_exception(unhandled_exception); const Array& code_array = Array::Handle( zone, Array::New(StackTrace::kPreallocatedStackdepth, Heap::kOld)); const Array& pc_offset_array = Array::Handle( zone, Array::New(StackTrace::kPreallocatedStackdepth, Heap::kOld)); const StackTrace& stack_trace = StackTrace::Handle(zone, StackTrace::New(code_array, pc_offset_array)); // Expansion of inlined functions requires additional memory at run time, // avoid it. stack_trace.set_expand_inlined(false); set_preallocated_stack_trace(stack_trace); return Error::null(); } RawFunction* ObjectStore::PrivateObjectLookup(const String& name) { const Library& core_lib = Library::Handle(core_library()); const String& mangled = String::ZoneHandle(core_lib.PrivateName(name)); const Class& cls = Class::Handle(object_class()); const Function& result = Function::Handle(cls.LookupDynamicFunction(mangled)); ASSERT(!result.IsNull()); return result.raw(); } void ObjectStore::InitKnownObjects() { #ifdef DART_PRECOMPILED_RUNTIME // These objects are only needed for code generation. return; #else Thread* thread = Thread::Current(); Zone* zone = thread->zone(); Isolate* isolate = thread->isolate(); ASSERT(isolate != NULL && isolate->object_store() == this); const Library& async_lib = Library::Handle(async_library()); ASSERT(!async_lib.IsNull()); Class& cls = Class::Handle(zone); cls = async_lib.LookupClass(Symbols::Future()); ASSERT(!cls.IsNull()); set_future_class(cls); cls = async_lib.LookupClass(Symbols::Completer()); ASSERT(!cls.IsNull()); set_completer_class(cls); cls = async_lib.LookupClass(Symbols::StreamIterator()); ASSERT(!cls.IsNull()); set_stream_iterator_class(cls); String& function_name = String::Handle(zone); Function& function = Function::Handle(zone); function_name ^= async_lib.PrivateName(Symbols::SetAsyncThreadStackTrace()); ASSERT(!function_name.IsNull()); function ^= Resolver::ResolveStatic(async_lib, Object::null_string(), function_name, 0, 1, Object::null_array()); ASSERT(!function.IsNull()); set_async_set_thread_stack_trace(function); function_name ^= async_lib.PrivateName(Symbols::ClearAsyncThreadStackTrace()); ASSERT(!function_name.IsNull()); function ^= Resolver::ResolveStatic(async_lib, Object::null_string(), function_name, 0, 0, Object::null_array()); ASSERT(!function.IsNull()); set_async_clear_thread_stack_trace(function); function_name ^= async_lib.PrivateName(Symbols::AsyncStarMoveNextHelper()); ASSERT(!function_name.IsNull()); function ^= Resolver::ResolveStatic(async_lib, Object::null_string(), function_name, 0, 1, Object::null_array()); ASSERT(!function.IsNull()); set_async_star_move_next_helper(function); function_name ^= async_lib.PrivateName(Symbols::_CompleteOnAsyncReturn()); ASSERT(!function_name.IsNull()); function ^= Resolver::ResolveStatic(async_lib, Object::null_string(), function_name, 0, 2, Object::null_array()); ASSERT(!function.IsNull()); set_complete_on_async_return(function); if (FLAG_async_debugger) { // Disable debugging and inlining the _CompleteOnAsyncReturn function. function.set_is_debuggable(false); function.set_is_inlinable(false); } cls = async_lib.LookupClassAllowPrivate(Symbols::_AsyncStarStreamController()); ASSERT(!cls.IsNull()); set_async_star_stream_controller(cls); if (FLAG_async_debugger) { // Disable debugging and inlining of all functions on the // _AsyncStarStreamController class. const Array& functions = Array::Handle(cls.functions()); for (intptr_t i = 0; i < functions.Length(); i++) { function ^= functions.At(i); if (function.IsNull()) { break; } function.set_is_debuggable(false); function.set_is_inlinable(false); } } const Library& internal_lib = Library::Handle(_internal_library()); cls = internal_lib.LookupClass(Symbols::Symbol()); set_symbol_class(cls); const Library& core_lib = Library::Handle(core_library()); cls = core_lib.LookupClassAllowPrivate(Symbols::_CompileTimeError()); ASSERT(!cls.IsNull()); set_compiletime_error_class(cls); // Cache the core private functions used for fast instance of checks. simple_instance_of_function_ = PrivateObjectLookup(Symbols::_simpleInstanceOf()); simple_instance_of_true_function_ = PrivateObjectLookup(Symbols::_simpleInstanceOfTrue()); simple_instance_of_false_function_ = PrivateObjectLookup(Symbols::_simpleInstanceOfFalse()); #endif } } // namespace dart <commit_msg>[VM] Do not invoke the empty StackOverflowError/OutOfMemoryError constructors<commit_after>// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/object_store.h" #include "vm/dart_entry.h" #include "vm/exceptions.h" #include "vm/isolate.h" #include "vm/object.h" #include "vm/raw_object.h" #include "vm/resolver.h" #include "vm/symbols.h" #include "vm/visitor.h" namespace dart { ObjectStore::ObjectStore() { #define INIT_FIELD(Type, name) name##_ = Type::null(); OBJECT_STORE_FIELD_LIST(INIT_FIELD, INIT_FIELD) #undef INIT_FIELD for (RawObject** current = from(); current <= to(); current++) { ASSERT(*current == Object::null()); } } ObjectStore::~ObjectStore() {} void ObjectStore::VisitObjectPointers(ObjectPointerVisitor* visitor) { ASSERT(visitor != NULL); visitor->VisitPointers(from(), to()); } void ObjectStore::Init(Isolate* isolate) { ASSERT(isolate->object_store() == NULL); ObjectStore* store = new ObjectStore(); isolate->set_object_store(store); } #ifndef PRODUCT void ObjectStore::PrintToJSONObject(JSONObject* jsobj) { if (!FLAG_support_service) { return; } jsobj->AddProperty("type", "_ObjectStore"); { JSONObject fields(jsobj, "fields"); Object& value = Object::Handle(); #define PRINT_OBJECT_STORE_FIELD(type, name) \ value = name##_; \ fields.AddProperty(#name "_", value); OBJECT_STORE_FIELD_LIST(PRINT_OBJECT_STORE_FIELD, PRINT_OBJECT_STORE_FIELD); #undef PRINT_OBJECT_STORE_FIELD } } #endif // !PRODUCT static RawInstance* AllocateObjectByClassName(const Library& library, const String& class_name) { const Class& cls = Class::Handle(library.LookupClassAllowPrivate(class_name)); ASSERT(!cls.IsNull()); return Instance::New(cls); } RawError* ObjectStore::PreallocateObjects() { Thread* thread = Thread::Current(); Isolate* isolate = thread->isolate(); Zone* zone = thread->zone(); ASSERT(isolate != NULL && isolate->object_store() == this); if (this->stack_overflow() != Instance::null()) { ASSERT(this->out_of_memory() != Instance::null()); ASSERT(this->preallocated_stack_trace() != StackTrace::null()); return Error::null(); } ASSERT(this->stack_overflow() == Instance::null()); ASSERT(this->out_of_memory() == Instance::null()); ASSERT(this->preallocated_stack_trace() == StackTrace::null()); this->pending_deferred_loads_ = GrowableObjectArray::New(); this->closure_functions_ = GrowableObjectArray::New(); this->resume_capabilities_ = GrowableObjectArray::New(); this->exit_listeners_ = GrowableObjectArray::New(); this->error_listeners_ = GrowableObjectArray::New(); Object& result = Object::Handle(); const Library& library = Library::Handle(Library::CoreLibrary()); result = AllocateObjectByClassName(library, Symbols::StackOverflowError()); if (result.IsError()) { return Error::Cast(result).raw(); } set_stack_overflow(Instance::Cast(result)); result = AllocateObjectByClassName(library, Symbols::OutOfMemoryError()); if (result.IsError()) { return Error::Cast(result).raw(); } set_out_of_memory(Instance::Cast(result)); // Allocate pre-allocated unhandled exception object initialized with the // pre-allocated OutOfMemoryError. const UnhandledException& unhandled_exception = UnhandledException::Handle(UnhandledException::New( Instance::Cast(result), StackTrace::Handle(zone))); set_preallocated_unhandled_exception(unhandled_exception); const Array& code_array = Array::Handle( zone, Array::New(StackTrace::kPreallocatedStackdepth, Heap::kOld)); const Array& pc_offset_array = Array::Handle( zone, Array::New(StackTrace::kPreallocatedStackdepth, Heap::kOld)); const StackTrace& stack_trace = StackTrace::Handle(zone, StackTrace::New(code_array, pc_offset_array)); // Expansion of inlined functions requires additional memory at run time, // avoid it. stack_trace.set_expand_inlined(false); set_preallocated_stack_trace(stack_trace); return Error::null(); } RawFunction* ObjectStore::PrivateObjectLookup(const String& name) { const Library& core_lib = Library::Handle(core_library()); const String& mangled = String::ZoneHandle(core_lib.PrivateName(name)); const Class& cls = Class::Handle(object_class()); const Function& result = Function::Handle(cls.LookupDynamicFunction(mangled)); ASSERT(!result.IsNull()); return result.raw(); } void ObjectStore::InitKnownObjects() { #ifdef DART_PRECOMPILED_RUNTIME // These objects are only needed for code generation. return; #else Thread* thread = Thread::Current(); Zone* zone = thread->zone(); Isolate* isolate = thread->isolate(); ASSERT(isolate != NULL && isolate->object_store() == this); const Library& async_lib = Library::Handle(async_library()); ASSERT(!async_lib.IsNull()); Class& cls = Class::Handle(zone); cls = async_lib.LookupClass(Symbols::Future()); ASSERT(!cls.IsNull()); set_future_class(cls); cls = async_lib.LookupClass(Symbols::Completer()); ASSERT(!cls.IsNull()); set_completer_class(cls); cls = async_lib.LookupClass(Symbols::StreamIterator()); ASSERT(!cls.IsNull()); set_stream_iterator_class(cls); String& function_name = String::Handle(zone); Function& function = Function::Handle(zone); function_name ^= async_lib.PrivateName(Symbols::SetAsyncThreadStackTrace()); ASSERT(!function_name.IsNull()); function ^= Resolver::ResolveStatic(async_lib, Object::null_string(), function_name, 0, 1, Object::null_array()); ASSERT(!function.IsNull()); set_async_set_thread_stack_trace(function); function_name ^= async_lib.PrivateName(Symbols::ClearAsyncThreadStackTrace()); ASSERT(!function_name.IsNull()); function ^= Resolver::ResolveStatic(async_lib, Object::null_string(), function_name, 0, 0, Object::null_array()); ASSERT(!function.IsNull()); set_async_clear_thread_stack_trace(function); function_name ^= async_lib.PrivateName(Symbols::AsyncStarMoveNextHelper()); ASSERT(!function_name.IsNull()); function ^= Resolver::ResolveStatic(async_lib, Object::null_string(), function_name, 0, 1, Object::null_array()); ASSERT(!function.IsNull()); set_async_star_move_next_helper(function); function_name ^= async_lib.PrivateName(Symbols::_CompleteOnAsyncReturn()); ASSERT(!function_name.IsNull()); function ^= Resolver::ResolveStatic(async_lib, Object::null_string(), function_name, 0, 2, Object::null_array()); ASSERT(!function.IsNull()); set_complete_on_async_return(function); if (FLAG_async_debugger) { // Disable debugging and inlining the _CompleteOnAsyncReturn function. function.set_is_debuggable(false); function.set_is_inlinable(false); } cls = async_lib.LookupClassAllowPrivate(Symbols::_AsyncStarStreamController()); ASSERT(!cls.IsNull()); set_async_star_stream_controller(cls); if (FLAG_async_debugger) { // Disable debugging and inlining of all functions on the // _AsyncStarStreamController class. const Array& functions = Array::Handle(cls.functions()); for (intptr_t i = 0; i < functions.Length(); i++) { function ^= functions.At(i); if (function.IsNull()) { break; } function.set_is_debuggable(false); function.set_is_inlinable(false); } } const Library& internal_lib = Library::Handle(_internal_library()); cls = internal_lib.LookupClass(Symbols::Symbol()); set_symbol_class(cls); const Library& core_lib = Library::Handle(core_library()); cls = core_lib.LookupClassAllowPrivate(Symbols::_CompileTimeError()); ASSERT(!cls.IsNull()); set_compiletime_error_class(cls); // Cache the core private functions used for fast instance of checks. simple_instance_of_function_ = PrivateObjectLookup(Symbols::_simpleInstanceOf()); simple_instance_of_true_function_ = PrivateObjectLookup(Symbols::_simpleInstanceOfTrue()); simple_instance_of_false_function_ = PrivateObjectLookup(Symbols::_simpleInstanceOfFalse()); #endif } } // namespace dart <|endoftext|>
<commit_before>#include "encoder.h" EncodeToPngBufferWorker::EncodeToPngBufferWorker( unsigned char * pixbuf, size_t width, size_t height, int compression, bool interlaced, NanCallback * callback ): NanAsyncWorker(callback), _pixbuf(pixbuf), _width(width), _height(height), _compression(compression), _interlaced(interlaced), _pngbuf(NULL), _pngbufsize(0) {} EncodeToPngBufferWorker::~EncodeToPngBufferWorker() {} void EncodeToPngBufferWorker::Execute () { unsigned int rowBytes = _width * 3; // TODO: 3 channels per pixel is currently hard coded int interlaceType; int compLevel; switch (_compression) { case 0: // no compression compLevel = Z_NO_COMPRESSION; break; case 1: // fast compression compLevel = Z_BEST_SPEED; break; case 2: // high compression compLevel = Z_BEST_COMPRESSION; break; default: compLevel = Z_DEFAULT_COMPRESSION; break; } if (_interlaced) { interlaceType = PNG_INTERLACE_ADAM7; } else { interlaceType = PNG_INTERLACE_NONE; } png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { SetErrorMessage("Out of memory"); return; } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, (png_infopp) NULL); SetErrorMessage("Out of memory"); return; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); SetErrorMessage("PNG compression error"); return; } unsigned char ** rowPnts = (unsigned char **) malloc( _height * sizeof(unsigned char *) ); if (!rowPnts) { png_destroy_write_struct(&png_ptr, &info_ptr); SetErrorMessage("Out of memory"); return; } for (unsigned int r = 0; r < _height; r++) { rowPnts[r] = (unsigned char *) malloc(rowBytes * sizeof(unsigned char)); if (!rowPnts[r]) { // free previous allocations for (unsigned int p = 0 ; p < r ; p++) free(rowPnts[p]); free(rowPnts); png_destroy_write_struct(&png_ptr, &info_ptr); SetErrorMessage("Out of memory"); return; } } png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB, interlaceType, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_set_compression_level(png_ptr, compLevel); pngWriteCbData buffinf = {(unsigned char *) _pngbuf, 0}; png_set_write_fn(png_ptr, (voidp) &buffinf, pngWriteCB, NULL); CImg<unsigned char> tmpimg(_pixbuf, _width, _height, 1, 3, true); cimg_forXY(tmpimg, x, y) { unsigned char r = tmpimg.atXYZC(x, y, 0, 0), g = tmpimg.atXYZC(x, y, 0, 1), b = tmpimg.atXYZC(x, y, 0, 2); rowPnts[y][3 * x] = r; rowPnts[y][3 * x + 1] = g; rowPnts[y][3 * x + 2] = b; } png_set_rows(png_ptr, info_ptr, rowPnts); png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); _pngbufsize = buffinf.buffsize; png_destroy_write_struct(&png_ptr, &info_ptr); for (unsigned int r = 0; r < _height; r++) free(rowPnts[r]); free(rowPnts); return; } void pngWriteCB(png_structp png_ptr, png_bytep data, png_size_t length) { pngWriteCbData * buffinf = (pngWriteCbData *) png_get_io_ptr(png_ptr); size_t size = buffinf->buffsize + length; if (buffinf->buff) { buffinf->buff = (unsigned char *) realloc(buffinf->buff, size * sizeof(unsigned char)); } else { buffinf->buff = (unsigned char *) malloc(size * sizeof(unsigned char)); } if (!buffinf->buff) { png_error(png_ptr, "Out of memory"); return; } memcpy(buffinf->buff + buffinf->buffsize, data, length); buffinf->buffsize += length; } void EncodeToPngBufferWorker::HandleOKCallback () { NanScope(); Local<Value> argv[] = { NanNull(), NanBufferUse( _pngbuf, _pngbufsize ) }; callback->Call(2, argv); } <commit_msg>fixes png encoding bug<commit_after>#include "encoder.h" EncodeToPngBufferWorker::EncodeToPngBufferWorker( unsigned char * pixbuf, size_t width, size_t height, int compression, bool interlaced, NanCallback * callback ): NanAsyncWorker(callback), _pixbuf(pixbuf), _width(width), _height(height), _compression(compression), _interlaced(interlaced), _pngbuf(NULL), _pngbufsize(0) {} EncodeToPngBufferWorker::~EncodeToPngBufferWorker() {} void EncodeToPngBufferWorker::Execute () { unsigned int rowBytes = _width * 3; // TODO: 3 channels per pixel is currently hard coded int interlaceType; int compLevel; switch (_compression) { case 0: // no compression compLevel = Z_NO_COMPRESSION; break; case 1: // fast compression compLevel = Z_BEST_SPEED; break; case 2: // high compression compLevel = Z_BEST_COMPRESSION; break; default: compLevel = Z_DEFAULT_COMPRESSION; break; } if (_interlaced) { interlaceType = PNG_INTERLACE_ADAM7; } else { interlaceType = PNG_INTERLACE_NONE; } png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { SetErrorMessage("Out of memory"); return; } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, (png_infopp) NULL); SetErrorMessage("Out of memory"); return; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); SetErrorMessage("PNG compression error"); return; } unsigned char ** rowPnts = (unsigned char **) malloc( _height * sizeof(unsigned char *) ); if (!rowPnts) { png_destroy_write_struct(&png_ptr, &info_ptr); SetErrorMessage("Out of memory"); return; } for (unsigned int r = 0; r < _height; r++) { rowPnts[r] = (unsigned char *) malloc(rowBytes * sizeof(unsigned char)); if (!rowPnts[r]) { // free previous allocations for (unsigned int p = 0 ; p < r ; p++) free(rowPnts[p]); free(rowPnts); png_destroy_write_struct(&png_ptr, &info_ptr); SetErrorMessage("Out of memory"); return; } } png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB, interlaceType, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_set_compression_level(png_ptr, compLevel); pngWriteCbData buffinf = {NULL, 0}; png_set_write_fn(png_ptr, (voidp) &buffinf, pngWriteCB, NULL); CImg<unsigned char> tmpimg(_pixbuf, _width, _height, 1, 3, true); cimg_forXY(tmpimg, x, y) { unsigned char r = tmpimg.atXYZC(x, y, 0, 0), g = tmpimg.atXYZC(x, y, 0, 1), b = tmpimg.atXYZC(x, y, 0, 2); rowPnts[y][3 * x] = r; rowPnts[y][3 * x + 1] = g; rowPnts[y][3 * x + 2] = b; } png_set_rows(png_ptr, info_ptr, rowPnts); png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); png_destroy_write_struct(&png_ptr, &info_ptr); for (unsigned int r = 0; r < _height; r++) free(rowPnts[r]); free(rowPnts); _pngbuf = (char *) buffinf.buff; _pngbufsize = buffinf.buffsize; return; } void EncodeToPngBufferWorker::HandleOKCallback () { NanScope(); Local<Value> argv[] = { NanNull(), NanBufferUse( _pngbuf, _pngbufsize ) }; callback->Call(2, argv); } void pngWriteCB(png_structp png_ptr, png_bytep data, png_size_t length) { pngWriteCbData * buffinf = (pngWriteCbData *) png_get_io_ptr(png_ptr); size_t size = buffinf->buffsize + length; if (buffinf->buff) { buffinf->buff = (unsigned char *) realloc(buffinf->buff, size * sizeof(unsigned char)); } else { buffinf->buff = (unsigned char *) malloc(size * sizeof(unsigned char)); } if (!buffinf->buff) { png_error(png_ptr, "Out of memory"); return; } memcpy(buffinf->buff + buffinf->buffsize, data, length); buffinf->buffsize += length; } <|endoftext|>
<commit_before>/** * @file * @brief Example of using new and delete operators * @date 12.07.12 * @author Ilia Vaprol */ #include <framework/example/self.h> #include <new> #include <cstdio> // TEST: include all C++ headers #include <cassert> #include <cctype> #include <cerrno> #include <cmath> #include <csetjmp> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <exception> #include <new> #include <typeinfo> // END TEST EMBOX_EXAMPLE(run); class Hello { public: Hello() { std::printf(">> [obj %p] Hello() without any arguments\n", this); } explicit Hello(const char* str) { std::printf(">> [obj %p] Hello() with one argument: '%s`\n", this, str); } ~Hello() { std::printf(">> [obj %p] ~Hello()\n", this); } }; static int run(int argc, char **argv) { // stack { std::puts("Hello without any arguments -- on stack"); Hello hello; } { std::puts("Hello with one argument -- on stack"); Hello hello("foo"); } // operator new(size_t, void*) { std::puts("Hello without any arguments -- via operator new(sz, ptr)"); char storage[sizeof(Hello)]; Hello *hello_ptr = new(&storage[0]) Hello; hello_ptr->~Hello(); } { std::puts("Hello with one argument -- via operator new(sz, ptr)"); char storage[sizeof(Hello)]; Hello *hello_ptr = new(&storage[0]) Hello("bar"); hello_ptr->~Hello(); } // operator new(size_t) { std::puts("Hello without any arguments -- via operator new(sz)"); Hello *hello_ptr = new Hello(); delete hello_ptr; } { std::puts("Hello with one argument -- via operator new(sz)"); Hello *hello_ptr = new Hello("baz"); delete hello_ptr; } // operator new(size_t, const nothrow_t&) { std::puts("Hello without any arguments -- via operator new(sz, nothrow)"); Hello *hello_ptr = new(std::nothrow) Hello(); delete hello_ptr; } { std::puts("Hello with one argument -- via operator new(sz, nothrow)"); Hello *hello_ptr = new(std::nothrow) Hello("qux"); delete hello_ptr; } return 0; } <commit_msg>example of failing C++ compilation/linking<commit_after>/** * @file * @brief Example of using new and delete operators * @date 12.07.12 * @author Ilia Vaprol */ #include <framework/example/self.h> #include <new> #include <cstdio> // TEST: include all C++ headers #include <cassert> #include <cctype> #include <cerrno> #include <cmath> #include <csetjmp> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <exception> #include <new> #include <typeinfo> // END TEST EMBOX_EXAMPLE(run); class Base { private: virtual void testPureVirtual(void) = 0; }; class Hello : private Base { private: void testPureVirtual(void); public: Hello() { std::printf(">> [obj %p] Hello() without any arguments\n", this); } explicit Hello(const char* str) { std::printf(">> [obj %p] Hello() with one argument: '%s`\n", this, str); } ~Hello() { std::printf(">> [obj %p] ~Hello()\n", this); } }; void Hello::testPureVirtual(void) { assert(true); } static int run(int argc, char **argv) { // stack { std::puts("Hello without any arguments -- on stack"); Hello hello; } { std::puts("Hello with one argument -- on stack"); Hello hello("foo"); } // operator new(size_t, void*) { std::puts("Hello without any arguments -- via operator new(sz, ptr)"); char storage[sizeof(Hello)]; Hello *hello_ptr = new(&storage[0]) Hello; hello_ptr->~Hello(); } { std::puts("Hello with one argument -- via operator new(sz, ptr)"); char storage[sizeof(Hello)]; Hello *hello_ptr = new(&storage[0]) Hello("bar"); hello_ptr->~Hello(); } // operator new(size_t) { std::puts("Hello without any arguments -- via operator new(sz)"); Hello *hello_ptr = new Hello(); delete hello_ptr; } { std::puts("Hello with one argument -- via operator new(sz)"); Hello *hello_ptr = new Hello("baz"); delete hello_ptr; } // operator new(size_t, const nothrow_t&) { std::puts("Hello without any arguments -- via operator new(sz, nothrow)"); Hello *hello_ptr = new(std::nothrow) Hello(); delete hello_ptr; } { std::puts("Hello with one argument -- via operator new(sz, nothrow)"); Hello *hello_ptr = new(std::nothrow) Hello("qux"); delete hello_ptr; } return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2014 Potential Ventures Ltd * 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 Potential Ventures Ltd not 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 POTENTIAL VENTURES LTD 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 "VhpiImpl.h" #include <vector> extern "C" { static VhpiCbHdl *sim_init_cb; static VhpiCbHdl *sim_finish_cb; static VhpiImpl *vhpi_table; } const char * VhpiImpl::format_to_string(int format) { switch (format) { case vhpiBinStrVal: return "vhpiBinStrVal"; case vhpiOctStrVal: return "vhpiOctStrVal"; case vhpiDecStrVal: return "vhpiDecStrVal"; case vhpiHexStrVal: return "vhpiHexStrVal"; case vhpiEnumVal: return "vhpiEnumVal"; case vhpiIntVal: return "vhpiIntVal"; case vhpiLogicVal: return "vhpiLogicVal"; case vhpiRealVal: return "vhpiRealVal"; case vhpiStrVal: return "vhpiStrVal"; case vhpiCharVal: return "vhpiCharVal"; case vhpiTimeVal: return "vhpiTimeVal"; case vhpiPhysVal: return "vhpiPhysVal"; case vhpiObjTypeVal: return "vhpiObjTypeVal"; case vhpiPtrVal: return "vhpiPtrVal"; case vhpiEnumVecVal: return "vhpiEnumVecVal"; default: return "unknown"; } } const char *VhpiImpl::reason_to_string(int reason) { switch (reason) { case vhpiCbValueChange: return "vhpiCbValueChange"; case vhpiCbStartOfNextCycle: return "vhpiCbStartOfNextCycle"; case vhpiCbStartOfPostponed: return "vhpiCbStartOfPostponed"; case vhpiCbEndOfTimeStep: return "vhpiCbEndOfTimeStep"; case vhpiCbNextTimeStep: return "vhpiCbNextTimeStep"; case vhpiCbAfterDelay: return "vhpiCbAfterDelay"; case vhpiCbStartOfSimulation: return "vhpiCbStartOfSimulation"; case vhpiCbEndOfSimulation: return "vhpiCbEndOfSimulation"; case vhpiCbEndOfProcesses: return "vhpiCbEndOfProcesses"; case vhpiCbLastKnownDeltaCycle: return "vhpiCbLastKnownDeltaCycle"; default: return "unknown"; } } void VhpiImpl::get_sim_time(uint32_t *high, uint32_t *low) { vhpiTimeT vhpi_time_s; vhpi_get_time(&vhpi_time_s, NULL); check_vhpi_error(); *high = vhpi_time_s.high; *low = vhpi_time_s.low; } GpiObjHdl *VhpiImpl::create_gpi_obj_from_handle(vhpiHandleT new_hdl, std::string &name) { vhpiIntT type; GpiObjHdl *new_obj = NULL; if (vhpiVerilog == (type = vhpi_get(vhpiKindP, new_hdl))) { LOG_DEBUG("vhpiVerilog returned from vhpi_get(vhpiType, ...)") return NULL; } /* What sort of isntance is this ?*/ switch (type) { case vhpiPortDeclK: case vhpiSigDeclK: case vhpiIndexedNameK: new_obj = new VhpiSignalObjHdl(this, new_hdl); break; case vhpiForGenerateK: case vhpiCompInstStmtK: new_obj = new GpiObjHdl(this, new_hdl); break; default: LOG_WARN("Not able to map type %d to object."); return NULL; } new_obj->initialise(name); return new_obj; } GpiObjHdl *VhpiImpl::native_check_create(std::string &name, GpiObjHdl *parent) { vhpiHandleT new_hdl; std::vector<char> writable(name.begin(), name.end()); writable.push_back('\0'); new_hdl = vhpi_handle_by_name(&writable[0], NULL); if (new_hdl == NULL) { LOG_DEBUG("Unable to query vhpi_handle_by_name %s", name.c_str()); return NULL; } GpiObjHdl* new_obj = create_gpi_obj_from_handle(new_hdl, name); if (new_obj == NULL) { vhpi_release_handle(new_hdl); LOG_DEBUG("Unable to fetch object %s", name.c_str()); return NULL; } return new_obj; } GpiObjHdl *VhpiImpl::native_check_create(uint32_t index, GpiObjHdl *parent) { GpiObjHdl *parent_hdl = sim_to_hdl<GpiObjHdl*>(parent); vhpiHandleT vpi_hdl = parent_hdl->get_handle<vhpiHandleT>(); vhpiHandleT new_hdl; new_hdl = vhpi_handle_by_index(vhpiIndexedNames, vpi_hdl, index); if (new_hdl == NULL) { LOG_DEBUG("Unable to query vhpi_handle_by_index %s", index); return NULL; } std::string name = vhpi_get_str(vhpiNameP, new_hdl); GpiObjHdl* new_obj = create_gpi_obj_from_handle(new_hdl, name); if (new_obj == NULL) { vhpi_release_handle(new_hdl); LOG_DEBUG("Could not fetch object below entity (%s) at index (%d)", parent->get_name_str(), index); return NULL; } return new_obj; } GpiObjHdl *VhpiImpl::get_root_handle(const char* name) { FENTER vhpiHandleT root; vhpiHandleT dut; GpiObjHdl *rv; std::string root_name = name; root = vhpi_handle(vhpiRootInst, NULL); check_vhpi_error(); if (!root) { LOG_ERROR("VHPI: Attempting to get the root handle failed"); FEXIT return NULL; } if (name) dut = vhpi_handle_by_name(name, NULL); else dut = vhpi_handle(vhpiDesignUnit, root); check_vhpi_error(); if (!dut) { LOG_ERROR("VHPI: Attempting to get the DUT handle failed"); FEXIT return NULL; } const char *found = vhpi_get_str(vhpiNameP, dut); check_vhpi_error(); if (name != NULL && strcmp(name, found)) { LOG_WARN("VHPI: Root '%s' doesn't match requested toplevel %s", found, name); FEXIT return NULL; } rv = new GpiObjHdl(this, root); rv->initialise(root_name); FEXIT return rv; } GpiCbHdl *VhpiImpl::register_timed_callback(uint64_t time_ps) { VhpiTimedCbHdl *hdl = new VhpiTimedCbHdl(this, time_ps); if (hdl->arm_callback()) { delete(hdl); hdl = NULL; } return hdl; } GpiCbHdl *VhpiImpl::register_readwrite_callback(void) { if (m_read_write.arm_callback()) return NULL; return &m_read_write; } GpiCbHdl *VhpiImpl::register_readonly_callback(void) { if (m_read_only.arm_callback()) return NULL; return &m_read_only; } GpiCbHdl *VhpiImpl::register_nexttime_callback(void) { if (m_next_phase.arm_callback()) return NULL; return &m_next_phase; } int VhpiImpl::deregister_callback(GpiCbHdl *gpi_hdl) { gpi_hdl->cleanup_callback(); return 0; } void VhpiImpl::sim_end(void) { sim_finish_cb->set_call_state(GPI_DELETE); vhpi_control(vhpiFinish); check_vhpi_error(); } extern "C" { // Main entry point for callbacks from simulator void handle_vhpi_callback(const vhpiCbDataT *cb_data) { VhpiCbHdl *cb_hdl = (VhpiCbHdl*)cb_data->user_data; if (!cb_hdl) LOG_CRITICAL("VHPI: Callback data corrupted"); gpi_cb_state_e old_state = cb_hdl->get_call_state(); if (old_state == GPI_PRIMED) { cb_hdl->set_call_state(GPI_CALL); cb_hdl->run_callback(); gpi_cb_state_e new_state = cb_hdl->get_call_state(); /* We have re-primed in the handler */ if (new_state != GPI_PRIMED) if (cb_hdl->cleanup_callback()) { delete cb_hdl; } } return; }; static void register_initial_callback(void) { FENTER sim_init_cb = new VhpiStartupCbHdl(vhpi_table); sim_init_cb->arm_callback(); FEXIT } static void register_final_callback(void) { FENTER sim_finish_cb = new VhpiShutdownCbHdl(vhpi_table); sim_finish_cb->arm_callback(); FEXIT } static void register_embed(void) { vhpi_table = new VhpiImpl("VHPI"); gpi_register_impl(vhpi_table); gpi_load_extra_libs(); } // pre-defined VHPI registration table void (*vhpi_startup_routines[])(void) = { register_embed, register_initial_callback, register_final_callback, 0 }; // For non-VPI compliant applications that cannot find vlog_startup_routines void vhpi_startup_routines_bootstrap(void) { void (*routine)(void); int i; routine = vhpi_startup_routines[0]; for (i = 0, routine = vhpi_startup_routines[i]; routine; routine = vhpi_startup_routines[++i]) { routine(); } } } GPI_ENTRY_POINT(vhpi, register_embed) <commit_msg>vhpi : seems we can just drop vhpiIfGenerateK into this case and things just work<commit_after>/****************************************************************************** * Copyright (c) 2014 Potential Ventures Ltd * 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 Potential Ventures Ltd not 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 POTENTIAL VENTURES LTD 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 "VhpiImpl.h" #include <vector> extern "C" { static VhpiCbHdl *sim_init_cb; static VhpiCbHdl *sim_finish_cb; static VhpiImpl *vhpi_table; } const char * VhpiImpl::format_to_string(int format) { switch (format) { case vhpiBinStrVal: return "vhpiBinStrVal"; case vhpiOctStrVal: return "vhpiOctStrVal"; case vhpiDecStrVal: return "vhpiDecStrVal"; case vhpiHexStrVal: return "vhpiHexStrVal"; case vhpiEnumVal: return "vhpiEnumVal"; case vhpiIntVal: return "vhpiIntVal"; case vhpiLogicVal: return "vhpiLogicVal"; case vhpiRealVal: return "vhpiRealVal"; case vhpiStrVal: return "vhpiStrVal"; case vhpiCharVal: return "vhpiCharVal"; case vhpiTimeVal: return "vhpiTimeVal"; case vhpiPhysVal: return "vhpiPhysVal"; case vhpiObjTypeVal: return "vhpiObjTypeVal"; case vhpiPtrVal: return "vhpiPtrVal"; case vhpiEnumVecVal: return "vhpiEnumVecVal"; default: return "unknown"; } } const char *VhpiImpl::reason_to_string(int reason) { switch (reason) { case vhpiCbValueChange: return "vhpiCbValueChange"; case vhpiCbStartOfNextCycle: return "vhpiCbStartOfNextCycle"; case vhpiCbStartOfPostponed: return "vhpiCbStartOfPostponed"; case vhpiCbEndOfTimeStep: return "vhpiCbEndOfTimeStep"; case vhpiCbNextTimeStep: return "vhpiCbNextTimeStep"; case vhpiCbAfterDelay: return "vhpiCbAfterDelay"; case vhpiCbStartOfSimulation: return "vhpiCbStartOfSimulation"; case vhpiCbEndOfSimulation: return "vhpiCbEndOfSimulation"; case vhpiCbEndOfProcesses: return "vhpiCbEndOfProcesses"; case vhpiCbLastKnownDeltaCycle: return "vhpiCbLastKnownDeltaCycle"; default: return "unknown"; } } void VhpiImpl::get_sim_time(uint32_t *high, uint32_t *low) { vhpiTimeT vhpi_time_s; vhpi_get_time(&vhpi_time_s, NULL); check_vhpi_error(); *high = vhpi_time_s.high; *low = vhpi_time_s.low; } GpiObjHdl *VhpiImpl::create_gpi_obj_from_handle(vhpiHandleT new_hdl, std::string &name) { vhpiIntT type; GpiObjHdl *new_obj = NULL; if (vhpiVerilog == (type = vhpi_get(vhpiKindP, new_hdl))) { LOG_DEBUG("vhpiVerilog returned from vhpi_get(vhpiType, ...)") return NULL; } /* What sort of isntance is this ?*/ switch (type) { case vhpiPortDeclK: case vhpiSigDeclK: case vhpiIndexedNameK: new_obj = new VhpiSignalObjHdl(this, new_hdl); break; case vhpiForGenerateK: case vhpiIfGenerateK: case vhpiCompInstStmtK: new_obj = new GpiObjHdl(this, new_hdl); break; default: LOG_WARN("Not able to map type %d to object."); return NULL; } new_obj->initialise(name); return new_obj; } GpiObjHdl *VhpiImpl::native_check_create(std::string &name, GpiObjHdl *parent) { vhpiHandleT new_hdl; std::vector<char> writable(name.begin(), name.end()); writable.push_back('\0'); new_hdl = vhpi_handle_by_name(&writable[0], NULL); if (new_hdl == NULL) { LOG_DEBUG("Unable to query vhpi_handle_by_name %s", name.c_str()); return NULL; } GpiObjHdl* new_obj = create_gpi_obj_from_handle(new_hdl, name); if (new_obj == NULL) { vhpi_release_handle(new_hdl); LOG_DEBUG("Unable to fetch object %s", name.c_str()); return NULL; } return new_obj; } GpiObjHdl *VhpiImpl::native_check_create(uint32_t index, GpiObjHdl *parent) { GpiObjHdl *parent_hdl = sim_to_hdl<GpiObjHdl*>(parent); vhpiHandleT vpi_hdl = parent_hdl->get_handle<vhpiHandleT>(); vhpiHandleT new_hdl; new_hdl = vhpi_handle_by_index(vhpiIndexedNames, vpi_hdl, index); if (new_hdl == NULL) { LOG_DEBUG("Unable to query vhpi_handle_by_index %s", index); return NULL; } std::string name = vhpi_get_str(vhpiNameP, new_hdl); GpiObjHdl* new_obj = create_gpi_obj_from_handle(new_hdl, name); if (new_obj == NULL) { vhpi_release_handle(new_hdl); LOG_DEBUG("Could not fetch object below entity (%s) at index (%d)", parent->get_name_str(), index); return NULL; } return new_obj; } GpiObjHdl *VhpiImpl::get_root_handle(const char* name) { FENTER vhpiHandleT root; vhpiHandleT dut; GpiObjHdl *rv; std::string root_name = name; root = vhpi_handle(vhpiRootInst, NULL); check_vhpi_error(); if (!root) { LOG_ERROR("VHPI: Attempting to get the root handle failed"); FEXIT return NULL; } if (name) dut = vhpi_handle_by_name(name, NULL); else dut = vhpi_handle(vhpiDesignUnit, root); check_vhpi_error(); if (!dut) { LOG_ERROR("VHPI: Attempting to get the DUT handle failed"); FEXIT return NULL; } const char *found = vhpi_get_str(vhpiNameP, dut); check_vhpi_error(); if (name != NULL && strcmp(name, found)) { LOG_WARN("VHPI: Root '%s' doesn't match requested toplevel %s", found, name); FEXIT return NULL; } rv = new GpiObjHdl(this, root); rv->initialise(root_name); FEXIT return rv; } GpiCbHdl *VhpiImpl::register_timed_callback(uint64_t time_ps) { VhpiTimedCbHdl *hdl = new VhpiTimedCbHdl(this, time_ps); if (hdl->arm_callback()) { delete(hdl); hdl = NULL; } return hdl; } GpiCbHdl *VhpiImpl::register_readwrite_callback(void) { if (m_read_write.arm_callback()) return NULL; return &m_read_write; } GpiCbHdl *VhpiImpl::register_readonly_callback(void) { if (m_read_only.arm_callback()) return NULL; return &m_read_only; } GpiCbHdl *VhpiImpl::register_nexttime_callback(void) { if (m_next_phase.arm_callback()) return NULL; return &m_next_phase; } int VhpiImpl::deregister_callback(GpiCbHdl *gpi_hdl) { gpi_hdl->cleanup_callback(); return 0; } void VhpiImpl::sim_end(void) { sim_finish_cb->set_call_state(GPI_DELETE); vhpi_control(vhpiFinish); check_vhpi_error(); } extern "C" { // Main entry point for callbacks from simulator void handle_vhpi_callback(const vhpiCbDataT *cb_data) { VhpiCbHdl *cb_hdl = (VhpiCbHdl*)cb_data->user_data; if (!cb_hdl) LOG_CRITICAL("VHPI: Callback data corrupted"); gpi_cb_state_e old_state = cb_hdl->get_call_state(); if (old_state == GPI_PRIMED) { cb_hdl->set_call_state(GPI_CALL); cb_hdl->run_callback(); gpi_cb_state_e new_state = cb_hdl->get_call_state(); /* We have re-primed in the handler */ if (new_state != GPI_PRIMED) if (cb_hdl->cleanup_callback()) { delete cb_hdl; } } return; }; static void register_initial_callback(void) { FENTER sim_init_cb = new VhpiStartupCbHdl(vhpi_table); sim_init_cb->arm_callback(); FEXIT } static void register_final_callback(void) { FENTER sim_finish_cb = new VhpiShutdownCbHdl(vhpi_table); sim_finish_cb->arm_callback(); FEXIT } static void register_embed(void) { vhpi_table = new VhpiImpl("VHPI"); gpi_register_impl(vhpi_table); gpi_load_extra_libs(); } // pre-defined VHPI registration table void (*vhpi_startup_routines[])(void) = { register_embed, register_initial_callback, register_final_callback, 0 }; // For non-VPI compliant applications that cannot find vlog_startup_routines void vhpi_startup_routines_bootstrap(void) { void (*routine)(void); int i; routine = vhpi_startup_routines[0]; for (i = 0, routine = vhpi_startup_routines[i]; routine; routine = vhpi_startup_routines[++i]) { routine(); } } } GPI_ENTRY_POINT(vhpi, register_embed) <|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun 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 <fclaw2d_global.h> #include <fclaw2d_forestclaw.h> #include <fclaw2d_partition.h> #include <fclaw2d_exchange.h> #include <fclaw2d_physical_bc.h> #include <fclaw2d_regrid.h> #include <fclaw2d_clawpatch.h> #ifdef __cplusplus extern "C" { #if 0 } #endif #endif /* ----------------------------------------------------------------- Initial grid ----------------------------------------------------------------- */ static void cb_initialize (fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { fclaw2d_vtable_t vt; fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE; fclaw2d_patch_data_new(domain,this_patch); fclaw2d_clawpatch_build(domain,this_patch, this_block_idx, this_patch_idx, (void*) &build_mode); vt = fclaw2d_get_vtable(domain); vt.patch_initialize(domain,this_patch,this_block_idx,this_patch_idx); } /* ----------------------------------------------------------------- Public interface ----------------------------------------------------------------- */ void fclaw2d_initialize (fclaw2d_domain_t **domain) { int i; double t; char basename[BUFSIZ]; const fclaw2d_vtable_t vt = fclaw2d_get_vtable(*domain); const amr_options_t *gparms = get_domain_parms(*domain); fclaw2d_domain_data_t* ddata = fclaw2d_domain_get_data(*domain); /* This mapping context is needed by fortran mapping functions */ fclaw2d_map_context_t *cont = fclaw2d_domain_get_map_context(*domain); SET_CONTEXT(&cont); int minlevel = gparms->minlevel; int maxlevel = gparms->maxlevel; // This is where the timing starts. ddata->is_latest_domain = 1; for (i = 0; i < FCLAW2D_TIMER_COUNT; ++i) { fclaw2d_timer_init (&ddata->timers[i]); } /* set specific refinement strategy */ fclaw2d_domain_set_refinement (*domain, gparms->smooth_refine, gparms->smooth_refine_level, gparms->coarsen_delay); /* start timing */ fclaw2d_domain_barrier (*domain); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_WALLTIME]); if (vt.problem_setup != NULL) { vt.problem_setup(*domain); } /* Get an initial domain */ fclaw2d_domain_setup(NULL,*domain); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]); fclaw2d_domain_iterate_level(*domain, minlevel, cb_initialize, (void *) NULL); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]); fclaw_bool time_interp = fclaw_false; t = fclaw2d_domain_get_time(*domain); fclaw2d_set_physical_bc(*domain,minlevel,t,time_interp); // VTK output during amrinit if (gparms->vtkout & 1) { // into timer fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_OUTPUT]); // output snprintf (basename, BUFSIZ, "%s_init_level_%02d", gparms->prefix, minlevel); fclaw2d_output_write_vtk (*domain, basename); // out of timer fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_OUTPUT]); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]); } // Refine as needed, one level at a time. if (minlevel < maxlevel) { int level = minlevel; int domain_init = 1; fclaw_bool have_new_refinement = 1; while (level < maxlevel && have_new_refinement) { fclaw2d_domain_iterate_level(*domain, level, cb_fclaw2d_regrid_tag4refinement, (void *) &domain_init); // Construct new domain based on tagged patches. fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain); have_new_refinement = new_domain != NULL; // Domain data may go out of scope now. ddata = NULL; if (have_new_refinement) { fclaw2d_domain_setup(*domain,new_domain); ddata = fclaw2d_domain_get_data(new_domain); // Re-initialize new grids fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]); fclaw2d_domain_iterate_adapted(*domain, new_domain, cb_fclaw2d_regrid_repopulate, (void *) &domain_init); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]); // Set boundary need ghost cell values so they are available // for using at tagging criteria, if necessary. int new_level = level+1; time_interp = fclaw_false; t = fclaw2d_domain_get_time(new_domain); fclaw2d_set_physical_bc(new_domain,new_level,t,time_interp); // free all memory associated with old domain fclaw2d_domain_reset(domain); *domain = new_domain; new_domain = NULL; // VTK output during amrinit if (gparms->vtkout & 1) { // into timer ddata = fclaw2d_domain_get_data (*domain); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_OUTPUT]); // output snprintf (basename, BUFSIZ, "%s_init_level_%02d_adapt", gparms->prefix, level); fclaw2d_output_write_vtk (*domain, basename); /* out of timer */ fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_OUTPUT]); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]); ddata = NULL; } /* Repartition domain to new processors. Do I need this here?*/ fclaw2d_partition_domain(domain, level); /* Set up ghost patches */ fclaw2d_exchange_setup(*domain); level++; } } } else { /* minlevel == maxlevel; no refining necessary. We have an initial partition, so we don't need to partition a new domaoin. */ fclaw2d_exchange_setup(*domain); } /* Print global minimum and maximum levels */ fclaw_global_infof("Global minlevel %d maxlevel %d\n", (*domain)->global_minlevel, (*domain)->global_maxlevel); /* Stop timer */ ddata = fclaw2d_domain_get_data(*domain); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]); } #ifdef __cplusplus #if 0 { #endif } #endif <commit_msg>fix problem if minlevel < maxlevel, but no refinement past minlevel is indicated<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun 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 <fclaw2d_global.h> #include <fclaw2d_forestclaw.h> #include <fclaw2d_partition.h> #include <fclaw2d_exchange.h> #include <fclaw2d_physical_bc.h> #include <fclaw2d_regrid.h> #include <fclaw2d_clawpatch.h> #ifdef __cplusplus extern "C" { #if 0 } #endif #endif /* ----------------------------------------------------------------- Initial grid ----------------------------------------------------------------- */ static void cb_initialize (fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { fclaw2d_vtable_t vt; fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE; fclaw2d_patch_data_new(domain,this_patch); fclaw2d_clawpatch_build(domain,this_patch, this_block_idx, this_patch_idx, (void*) &build_mode); vt = fclaw2d_get_vtable(domain); vt.patch_initialize(domain,this_patch,this_block_idx,this_patch_idx); } /* ----------------------------------------------------------------- Public interface ----------------------------------------------------------------- */ void fclaw2d_initialize (fclaw2d_domain_t **domain) { int i; double t; char basename[BUFSIZ]; const fclaw2d_vtable_t vt = fclaw2d_get_vtable(*domain); const amr_options_t *gparms = get_domain_parms(*domain); fclaw2d_domain_data_t* ddata = fclaw2d_domain_get_data(*domain); /* This mapping context is needed by fortran mapping functions */ fclaw2d_map_context_t *cont = fclaw2d_domain_get_map_context(*domain); SET_CONTEXT(&cont); int minlevel = gparms->minlevel; int maxlevel = gparms->maxlevel; // This is where the timing starts. ddata->is_latest_domain = 1; for (i = 0; i < FCLAW2D_TIMER_COUNT; ++i) { fclaw2d_timer_init (&ddata->timers[i]); } /* set specific refinement strategy */ fclaw2d_domain_set_refinement (*domain, gparms->smooth_refine, gparms->smooth_refine_level, gparms->coarsen_delay); /* start timing */ fclaw2d_domain_barrier (*domain); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_WALLTIME]); if (vt.problem_setup != NULL) { vt.problem_setup(*domain); } /* Get an initial domain */ fclaw2d_domain_setup(NULL,*domain); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]); fclaw2d_domain_iterate_level(*domain, minlevel, cb_initialize, (void *) NULL); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]); fclaw_bool time_interp = fclaw_false; t = fclaw2d_domain_get_time(*domain); fclaw2d_set_physical_bc(*domain,minlevel,t,time_interp); // VTK output during amrinit if (gparms->vtkout & 1) { // into timer fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_OUTPUT]); // output snprintf (basename, BUFSIZ, "%s_init_level_%02d", gparms->prefix, minlevel); fclaw2d_output_write_vtk (*domain, basename); // out of timer fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_OUTPUT]); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]); } // Refine as needed, one level at a time. if (minlevel < maxlevel) { int domain_init = 1; for (int level = minlevel; level < maxlevel; level++) { fclaw2d_domain_iterate_level(*domain, level, cb_fclaw2d_regrid_tag4refinement, (void *) &domain_init); // Construct new domain based on tagged patches. fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain); int have_new_refinement = new_domain != NULL; // Domain data may go out of scope now. ddata = NULL; if (have_new_refinement) { fclaw2d_domain_setup(*domain,new_domain); ddata = fclaw2d_domain_get_data(new_domain); // Re-initialize new grids fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]); fclaw2d_domain_iterate_adapted(*domain, new_domain, cb_fclaw2d_regrid_repopulate, (void *) &domain_init); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]); // Set boundary need ghost cell values so they are available // for using at tagging criteria, if necessary. int new_level = level+1; time_interp = fclaw_false; t = fclaw2d_domain_get_time(new_domain); fclaw2d_set_physical_bc(new_domain,new_level,t,time_interp); // free all memory associated with old domain fclaw2d_domain_reset(domain); *domain = new_domain; new_domain = NULL; // VTK output during amrinit if (gparms->vtkout & 1) { // into timer ddata = fclaw2d_domain_get_data (*domain); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_OUTPUT]); // output snprintf (basename, BUFSIZ, "%s_init_level_%02d_adapt", gparms->prefix, level); fclaw2d_output_write_vtk (*domain, basename); /* out of timer */ fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_OUTPUT]); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]); ddata = NULL; } /* Repartition domain to new processors. Do I need this here?*/ fclaw2d_partition_domain(domain, level); /* Set up ghost patches */ fclaw2d_exchange_setup(*domain); } else { /* minlevel == maxlevel; no refining necessary. We have an initial partition, so we don't need to partition a new domaoin. */ fclaw2d_exchange_setup(*domain); break; } } } /* Print global minimum and maximum levels */ fclaw_global_infof("Global minlevel %d maxlevel %d\n", (*domain)->global_minlevel, (*domain)->global_maxlevel); /* Stop timer */ ddata = fclaw2d_domain_get_data(*domain); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]); } #ifdef __cplusplus #if 0 { #endif } #endif <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQTSSAWidget.cpp,v $ // $Revision: 1.15 $ // $Name: $ // $Author: nsimus $ // $Date: 2010/06/28 11:59:44 $ // End CVS Header // Copyright (C) 2010 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // 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. #include "CQTSSAWidget.h" #include "copasi.h" //#include <q3table.h> #include <qcombobox.h> //#include <q3header.h> #include <qtabwidget.h> #include "CQTSSAResultSubWidget.h" #include "CQTSSAResultWidget.h" #include "CQTaskBtnWidget.h" #include "CQTaskHeaderWidget.h" #include "CProgressBar.h" #include "CQValidator.h" #include "CQMessageBox.h" #include "qtUtilities.h" #include "tssanalysis/CTSSATask.h" #include "tssanalysis/CTSSAProblem.h" #include "model/CModel.h" #include "report/CKeyFactory.h" #include "utilities/CCopasiException.h" #include "tssanalysis/CCSPMethod.h" #include "tssanalysis/CILDMMethod.h" #include "tssanalysis/CILDMModifiedMethod.h" #include "report/CCopasiRootContainer.h" /* * Constructs a CQTSSAWidget which is a child of 'parent', with the * name 'name'.' */ CQTSSAWidget::CQTSSAWidget(QWidget* parent, const char* name) : TaskWidget(parent, name) { setupUi(this); init(); } /* * Destroys the object and frees any allocated resources */ CQTSSAWidget::~CQTSSAWidget() { destroy(); // no need to delete child widgets, Qt does it all for us } /* * Sets the strings of the subwidgets using the current * language. */ void CQTSSAWidget::languageChange() { retranslateUi(this); } CTSSAMethod* pTSSMethod; CILDMMethod *pILDM_Method; CILDMModifiedMethod *pILDMModiMethod; CQTSSAResultSubWidget* pTSSResultSubWidget; CTSSATask * pCTSSATask; class mpTSSResultSubWidget; class QTabWidget; void CQTSSAWidget::init() { mpTSSAProblem = NULL; mpHeaderWidget->setTaskName("Time Scale Separation Analysis"); vboxLayout->insertWidget(0, mpHeaderWidget); // header vboxLayout->insertSpacing(1, 14); // space between header and body vboxLayout->addWidget(mpBtnWidget); // 'footer' addMethodSelectionBox(CTSSATask::ValidMethods, 0); addMethodParameterTable(1); mpValidatorDuration = new CQValidatorDouble(mpEditDuration); mpEditDuration->setValidator(mpValidatorDuration); mpValidatorIntervalSize = new CQValidatorDouble(mpEditIntervalSize); mpValidatorIntervalSize->setRange(0, DBL_MAX); mpEditIntervalSize->setValidator(mpValidatorIntervalSize); } void CQTSSAWidget::destroy() { pdelete(mpTSSAProblem); } void CQTSSAWidget::slotDuration() { try { mpTSSAProblem->setDuration(mpEditDuration->text().toDouble()); } catch (...) { CQMessageBox::information(this, QString("Information"), FROM_UTF8(CCopasiMessage::getAllMessageText()), QMessageBox::Ok, QMessageBox::Ok); } mpEditIntervalSize->setText(QString::number(mpTSSAProblem->getStepSize())); mpValidatorIntervalSize->revalidate(); mpEditIntervals->setText(QString::number(mpTSSAProblem->getStepNumber())); checkTimeSeries(); } void CQTSSAWidget::slotIntervalSize() { try { mpTSSAProblem->setStepSize(mpEditIntervalSize->text().toDouble()); } catch (...) { CQMessageBox::information(this, QString("Information"), FROM_UTF8(CCopasiMessage::getAllMessageText()), QMessageBox::Ok, QMessageBox::Ok); } mpEditIntervalSize->setText(QString::number(mpTSSAProblem->getStepSize())); mpValidatorIntervalSize->revalidate(); mpEditIntervals->setText(QString::number(mpTSSAProblem->getStepNumber())); checkTimeSeries(); } void CQTSSAWidget::slotIntervals() { try { mpTSSAProblem->setStepNumber(mpEditIntervals->text().toULong()); } catch (...) { CQMessageBox::information(this, QString("Information"), FROM_UTF8(CCopasiMessage::getAllMessageText()), QMessageBox::Ok, QMessageBox::Ok); } mpEditIntervalSize->setText(QString::number(mpTSSAProblem->getStepSize())); mpValidatorIntervalSize->revalidate(); checkTimeSeries(); } bool CQTSSAWidget::saveTask() { CTSSATask * pTask = dynamic_cast< CTSSATask * >(mpTask); if (!pTask) return false; saveCommon(); saveMethod(); CTSSAProblem* tssaproblem = dynamic_cast<CTSSAProblem *>(pTask->getProblem()); assert(tssaproblem); //numbers if (tssaproblem->getStepSize() != mpEditIntervalSize->text().toDouble()) { tssaproblem->setStepSize(mpEditIntervalSize->text().toDouble()); mChanged = true; } else if (tssaproblem->getStepNumber() != mpEditIntervals->text().toULong()) { tssaproblem->setStepNumber(mpEditIntervals->text().toLong()); mChanged = true; } if (tssaproblem->getDuration() != mpEditDuration->text().toDouble()) { tssaproblem->setDuration(mpEditDuration->text().toDouble()); mChanged = true; } if (tssaproblem->timeSeriesRequested() != mpCheckSave->isChecked()) { tssaproblem->setTimeSeriesRequested(mpCheckSave->isChecked()); mChanged = true; } mpValidatorDuration->saved(); mpValidatorIntervalSize->saved(); return true; } bool CQTSSAWidget::loadTask() { CTSSATask * pTask = dynamic_cast< CTSSATask * >(mpTask); if (!pTask) return false; loadCommon(); loadMethod(); CTSSAProblem* tssaproblem = dynamic_cast<CTSSAProblem *>(pTask->getProblem()); assert(tssaproblem); pdelete(mpTSSAProblem); mpTSSAProblem = new CTSSAProblem(*tssaproblem); //numbers mpEditIntervalSize->setText(QString::number(tssaproblem->getStepSize())); mpEditIntervals->setText(QString::number(tssaproblem->getStepNumber())); mpEditDuration->setText(QString::number(tssaproblem->getDuration())); //store time series checkbox mpCheckSave->setChecked(tssaproblem->timeSeriesRequested()); checkTimeSeries(); mpValidatorDuration->saved(); mpValidatorIntervalSize->saved(); return true; } CCopasiMethod * CQTSSAWidget::createMethod(const CCopasiMethod::SubType & type) { return CTSSAMethod::createTSSAMethod(type); } bool CQTSSAWidget::runTask() { assert(CCopasiRootContainer::getDatamodelList()->size() > 0); pCTSSATask = dynamic_cast<CTSSATask *>((*(*CCopasiRootContainer::getDatamodelList())[0]->getTaskList())["Time Scale Separation Analysis"]); if (!pCTSSATask) return false; pTSSMethod = dynamic_cast<CTSSAMethod*>(pCTSSATask->getMethod()); if (!pTSSMethod) pTSSMethod->emptyVectors(); checkTimeSeries(); if (!commonBeforeRunTask()) return false; bool success = true; if (!commonRunTask()) success = false; return success; } bool CQTSSAWidget::taskFinishedEvent() { bool success = true; // We need to load the result here as this is the only place where // we know that it is correct. CQTSSAResultWidget * pResult = dynamic_cast< CQTSSAResultWidget * >(mpListView->findWidgetFromId(271)); if (pResult == NULL) return false; success &= pResult->loadFromBackend(); pTSSResultSubWidget = pResult->getSubWidget(); if (!pTSSResultSubWidget) return false; pTSSResultSubWidget->discardOldResults(); if (success) { pTSSResultSubWidget->displayResult(); mpListView->switchToOtherWidget(271, ""); //change to the results window } return success; } void CQTSSAWidget::checkTimeSeries() { assert(CCopasiRootContainer::getDatamodelList()->size() > 0); if (mpEditIntervals->text().toLong() *(*CCopasiRootContainer::getDatamodelList())[0]->getModel()->getStateTemplate().getNumVariable() > TSSAMAX) { mpCheckSave->setChecked(false); mpCheckSave->setEnabled(false); } else { mpCheckSave->setEnabled(true); } } <commit_msg>some changes<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQTSSAWidget.cpp,v $ // $Revision: 1.16 $ // $Name: $ // $Author: nsimus $ // $Date: 2010/07/05 13:25:08 $ // End CVS Header // Copyright (C) 2010 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // 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. #include "CQTSSAWidget.h" #include "copasi.h" //#include <q3table.h> #include <qcombobox.h> //#include <q3header.h> #include <qtabwidget.h> #include "CQTSSAResultSubWidget.h" #include "CQTSSAResultWidget.h" #include "CQTaskBtnWidget.h" #include "CQTaskHeaderWidget.h" #include "CProgressBar.h" #include "CQValidator.h" #include "CQMessageBox.h" #include "qtUtilities.h" #include "tssanalysis/CTSSATask.h" #include "tssanalysis/CTSSAProblem.h" #include "model/CModel.h" #include "report/CKeyFactory.h" #include "utilities/CCopasiException.h" #include "tssanalysis/CCSPMethod.h" #include "tssanalysis/CILDMMethod.h" #include "tssanalysis/CILDMModifiedMethod.h" #include "report/CCopasiRootContainer.h" /* * Constructs a CQTSSAWidget which is a child of 'parent', with the * name 'name'.' */ CQTSSAWidget::CQTSSAWidget(QWidget* parent, const char* name) : TaskWidget(parent, name) { setupUi(this); init(); } /* * Destroys the object and frees any allocated resources */ CQTSSAWidget::~CQTSSAWidget() { destroy(); // no need to delete child widgets, Qt does it all for us } /* * Sets the strings of the subwidgets using the current * language. */ void CQTSSAWidget::languageChange() { retranslateUi(this); } CTSSAMethod* pTSSMethod; CILDMMethod *pILDM_Method; CILDMModifiedMethod *pILDMModiMethod; CQTSSAResultSubWidget* pTSSResultSubWidget; CTSSATask * pCTSSATask; class mpTSSResultSubWidget; class QTabWidget; void CQTSSAWidget::init() { mpTSSAProblem = NULL; mpHeaderWidget->setTaskName("Time Scale Separation Analysis"); vboxLayout->insertWidget(0, mpHeaderWidget); // header vboxLayout->insertSpacing(1, 14); // space between header and body vboxLayout->addWidget(mpBtnWidget); // 'footer' addMethodSelectionBox(CTSSATask::ValidMethods, 0); addMethodParameterTable(1); mpValidatorDuration = new CQValidatorDouble(mpEditDuration); mpEditDuration->setValidator(mpValidatorDuration); mpValidatorIntervalSize = new CQValidatorDouble(mpEditIntervalSize); mpValidatorIntervalSize->setRange(0, DBL_MAX); mpEditIntervalSize->setValidator(mpValidatorIntervalSize); } void CQTSSAWidget::destroy() { pdelete(mpTSSAProblem); } void CQTSSAWidget::slotDuration() { try { mpTSSAProblem->setDuration(mpEditDuration->text().toDouble()); } catch (...) { CQMessageBox::information(this, QString("Information"), FROM_UTF8(CCopasiMessage::getAllMessageText()), QMessageBox::Ok, QMessageBox::Ok); } mpEditIntervalSize->setText(QString::number(mpTSSAProblem->getStepSize())); mpValidatorIntervalSize->revalidate(); mpEditIntervals->setText(QString::number(mpTSSAProblem->getStepNumber())); checkTimeSeries(); } void CQTSSAWidget::slotIntervalSize() { try { mpTSSAProblem->setStepSize(mpEditIntervalSize->text().toDouble()); } catch (...) { CQMessageBox::information(this, QString("Information"), FROM_UTF8(CCopasiMessage::getAllMessageText()), QMessageBox::Ok, QMessageBox::Ok); } mpEditIntervalSize->setText(QString::number(mpTSSAProblem->getStepSize())); mpValidatorIntervalSize->revalidate(); mpEditIntervals->setText(QString::number(mpTSSAProblem->getStepNumber())); checkTimeSeries(); } void CQTSSAWidget::slotIntervals() { try { mpTSSAProblem->setStepNumber(mpEditIntervals->text().toULong()); } catch (...) { CQMessageBox::information(this, QString("Information"), FROM_UTF8(CCopasiMessage::getAllMessageText()), QMessageBox::Ok, QMessageBox::Ok); } mpEditIntervalSize->setText(QString::number(mpTSSAProblem->getStepSize())); mpValidatorIntervalSize->revalidate(); checkTimeSeries(); } bool CQTSSAWidget::saveTask() { CTSSATask * pTask = dynamic_cast< CTSSATask * >(mpTask); if (!pTask) return false; saveCommon(); saveMethod(); CTSSAProblem* tssaproblem = dynamic_cast<CTSSAProblem *>(pTask->getProblem()); assert(tssaproblem); //numbers if (tssaproblem->getStepSize() != mpEditIntervalSize->text().toDouble()) { tssaproblem->setStepSize(mpEditIntervalSize->text().toDouble()); mChanged = true; } else if (tssaproblem->getStepNumber() != mpEditIntervals->text().toULong()) { tssaproblem->setStepNumber(mpEditIntervals->text().toLong()); mChanged = true; } if (tssaproblem->getDuration() != mpEditDuration->text().toDouble()) { tssaproblem->setDuration(mpEditDuration->text().toDouble()); mChanged = true; } if (tssaproblem->timeSeriesRequested() != mpCheckSave->isChecked()) { tssaproblem->setTimeSeriesRequested(mpCheckSave->isChecked()); mChanged = true; } mpValidatorDuration->saved(); mpValidatorIntervalSize->saved(); return true; } bool CQTSSAWidget::loadTask() { CTSSATask * pTask = dynamic_cast< CTSSATask * >(mpTask); if (!pTask) return false; loadCommon(); loadMethod(); CTSSAProblem* tssaproblem = dynamic_cast<CTSSAProblem *>(pTask->getProblem()); assert(tssaproblem); pdelete(mpTSSAProblem); mpTSSAProblem = new CTSSAProblem(*tssaproblem); //numbers mpEditIntervalSize->setText(QString::number(tssaproblem->getStepSize())); mpEditIntervals->setText(QString::number(tssaproblem->getStepNumber())); mpEditDuration->setText(QString::number(tssaproblem->getDuration())); //store time series checkbox mpCheckSave->setChecked(tssaproblem->timeSeriesRequested()); checkTimeSeries(); mpValidatorDuration->saved(); mpValidatorIntervalSize->saved(); return true; } CCopasiMethod * CQTSSAWidget::createMethod(const CCopasiMethod::SubType & type) { return CTSSAMethod::createTSSAMethod(type); } bool CQTSSAWidget::runTask() { assert(CCopasiRootContainer::getDatamodelList()->size() > 0); pCTSSATask = dynamic_cast<CTSSATask *>((*(*CCopasiRootContainer::getDatamodelList())[0]->getTaskList())["Time Scale Separation Analysis"]); if (!pCTSSATask) return false; pTSSMethod = dynamic_cast<CTSSAMethod*>(pCTSSATask->getMethod()); if (!pTSSMethod) pTSSMethod->emptyVectors(); checkTimeSeries(); if (!commonBeforeRunTask()) return false; bool success = true; if (!commonRunTask()) success = false; return success; } bool CQTSSAWidget::taskFinishedEvent() { bool success = true; // We need to load the result here as this is the only place where // we know that it is correct. CQTSSAResultWidget * pResult = dynamic_cast< CQTSSAResultWidget * >(mpListView->findWidgetFromId(271)); if (pResult == NULL) { return false; } success &= pResult->loadFromBackend(); pTSSResultSubWidget = pResult->getSubWidget(); if (!pTSSResultSubWidget) return false; pTSSResultSubWidget->discardOldResults(); if (success) { pTSSResultSubWidget->displayResult(); mpListView->switchToOtherWidget(271, ""); //change to the results window } return success; } void CQTSSAWidget::checkTimeSeries() { assert(CCopasiRootContainer::getDatamodelList()->size() > 0); if (mpEditIntervals->text().toLong() *(*CCopasiRootContainer::getDatamodelList())[0]->getModel()->getStateTemplate().getNumVariable() > TSSAMAX) { mpCheckSave->setChecked(false); mpCheckSave->setEnabled(false); } else { mpCheckSave->setEnabled(true); } } <|endoftext|>
<commit_before>/** * Clever programming language * Copyright (c) 2011-2012 Clever Team * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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 <cstdlib> #include "compiler/cstring.h" #include "compiler/compiler.h" #include "compiler/scope.h" #include "compiler/value.h" #include "interpreter/location.hh" namespace clever { /** * Compiler initialization phase */ void Compiler::init() { m_scope = new Scope; m_scope_pool = (Scope**) calloc(10, sizeof(Scope*)); m_value_pool = (Value**) calloc(10, sizeof(Value*)); if (!m_scope_pool || !m_value_pool) { error("Out of memory!"); } m_scope_pool[m_scope_id++] = m_scope; m_value_pool[m_value_id++] = NULL; } /** * Compiler termination phase */ void Compiler::end() { m_ir.push_back(IR(OP_RETURN, 0)); } /** * Displays an error message and exits */ void Compiler::error(const char* msg) const { std::cout << "Compile error: " << msg << std::endl; exit(1); } /** * Displays an error message */ void Compiler::error(const std::string& message, const location& loc) const { if (loc.begin.filename) { std::cerr << "Compile error: " << message << " on " << *loc.begin.filename << " line " << loc.begin.line << "\n"; } else { std::cerr << "Compile error: " << message << " on line " << loc.begin.line << "\n"; } exit(1); } /** * Displays a formatted error message and abort the compilation */ void Compiler::errorf(const location& loc, const char* format, ...) const { std::ostringstream out; va_list args; va_start(args, format); vsprintf(out, format, args); va_end(args); error(out.str(), loc); } /** * Frees all resource used by the compiler */ void Compiler::shutdown() { CLEVER_SAFE_DELETE(g_cstring_tbl); CLEVER_SAFE_DELETE(m_scope); free(m_scope_pool); for (size_t i = 0; i < m_value_id; ++i) { delete m_value_pool[i]; } free(m_value_pool); } /** * Compiles a variable declaration */ void Compiler::varDeclaration(const CString* var, Value* node) { /** * A null value is represented by m_value_id = 0 on value pool */ m_ir.push_back(IR(OP_VAR_DECL, m_scope->push(var, node ? m_value_id : 0))); if (node) { m_value_pool[m_value_id++] = node; } } /** * Compiles a variable assignment */ void Compiler::assignment(const CString* var, Value* value, const location& loc) { Symbol* sym = m_scope->getSymbol(var); if (!sym) { errorf(loc, "Variable `%S' cannot be found!", var); } m_ir.push_back(IR(OP_ASSIGN, sym->getValueId(), m_value_id)); m_value_pool[m_value_id++] = value; } /** * Creates a new lexical scope */ void Compiler::newScope() { m_scope = m_scope->newLexicalScope(); m_scope->setId(m_scope_id); m_scope_pool[m_scope_id] = m_scope; m_ir.push_back(IR(OP_SCOPE, m_scope_id)); ++m_scope_id; } /** * Scope end marker to switch to parent scope */ void Compiler::endScope() { m_scope = m_scope->getParent(); m_ir.push_back(IR(OP_SCOPE, m_scope->getId())); } } // clever <commit_msg>- Simplify code<commit_after>/** * Clever programming language * Copyright (c) 2011-2012 Clever Team * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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 <cstdlib> #include "compiler/cstring.h" #include "compiler/compiler.h" #include "compiler/scope.h" #include "compiler/value.h" #include "interpreter/location.hh" namespace clever { /** * Compiler initialization phase */ void Compiler::init() { m_scope = new Scope; m_scope_pool = (Scope**) calloc(10, sizeof(Scope*)); m_value_pool = (Value**) calloc(10, sizeof(Value*)); if (!m_scope_pool || !m_value_pool) { error("Out of memory!"); } m_scope_pool[m_scope_id++] = m_scope; m_value_pool[m_value_id++] = NULL; } /** * Compiler termination phase */ void Compiler::end() { m_ir.push_back(IR(OP_RETURN, 0)); } /** * Displays an error message and exits */ void Compiler::error(const char* msg) const { std::cout << "Compile error: " << msg << std::endl; exit(1); } /** * Displays an error message */ void Compiler::error(const std::string& message, const location& loc) const { if (loc.begin.filename) { std::cerr << "Compile error: " << message << " on " << *loc.begin.filename << " line " << loc.begin.line << "\n"; } else { std::cerr << "Compile error: " << message << " on line " << loc.begin.line << "\n"; } exit(1); } /** * Displays a formatted error message and abort the compilation */ void Compiler::errorf(const location& loc, const char* format, ...) const { std::ostringstream out; va_list args; va_start(args, format); vsprintf(out, format, args); va_end(args); error(out.str(), loc); } /** * Frees all resource used by the compiler */ void Compiler::shutdown() { CLEVER_SAFE_DELETE(g_cstring_tbl); CLEVER_SAFE_DELETE(m_scope); free(m_scope_pool); for (size_t i = 0; i < m_value_id; ++i) { delete m_value_pool[i]; } free(m_value_pool); } /** * Compiles a variable declaration */ void Compiler::varDeclaration(const CString* var, Value* node) { /** * A null value is represented by m_value_id = 0 on value pool */ m_ir.push_back(IR(OP_VAR_DECL, m_scope->push(var, node ? m_value_id : 0))); if (node) { m_value_pool[m_value_id++] = node; } } /** * Compiles a variable assignment */ void Compiler::assignment(const CString* var, Value* value, const location& loc) { Symbol* sym = m_scope->getSymbol(var); if (!sym) { errorf(loc, "Variable `%S' cannot be found!", var); } m_ir.push_back(IR(OP_ASSIGN, sym->getValueId(), m_value_id)); m_value_pool[m_value_id++] = value; } /** * Creates a new lexical scope */ void Compiler::newScope() { m_scope = m_scope->newLexicalScope(); m_scope->setId(m_scope_id); m_ir.push_back(IR(OP_SCOPE, m_scope_id)); m_scope_pool[m_scope_id++] = m_scope; } /** * Scope end marker to switch to parent scope */ void Compiler::endScope() { m_scope = m_scope->getParent(); m_ir.push_back(IR(OP_SCOPE, m_scope->getId())); } } // clever <|endoftext|>
<commit_before>/******************************************************************************* * c7a/api/allgather_node.hpp * * Part of Project c7a. * * Copyright (C) 2015 Alexander Noe <uagtc@student.kit.edu> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_ALLGATHER_NODE_HEADER #define C7A_API_ALLGATHER_NODE_HEADER #include <c7a/common/future.hpp> #include <c7a/net/collective_communication.hpp> #include <c7a/data/manager.hpp> #include <string> #include "action_node.hpp" #include "dia_node.hpp" #include "function_stack.hpp" namespace c7a { template <typename Input, typename Output, typename Stack> class AllGatherNode : public ActionNode<Input> { public: using Super = ActionNode<Input>; using Super::context_; using Super::data_id_; AllGatherNode(Context& ctx, DIANode<Input>* parent, //TODO(??) don't we need to pass shared ptrs for the ref counting? Stack& stack, std::vector<Output>* out_vector ) : ActionNode<Input>(ctx, { parent }), local_stack_(stack), out_vector_(out_vector), channel_used_(ctx.get_data_manager().AllocateNetworkChannel()) { emitters_ = context_. get_data_manager().template GetNetworkEmitters<Output>(channel_used_); auto pre_op_function = [=](Output input) { PreOp(input); }; auto lop_chain = local_stack_.push(pre_op_function).emit(); parent->RegisterChild(lop_chain); } void PreOp(Output element) { local_data_.push_back(element); } virtual ~AllGatherNode() { } //! Closes the output file void execute() override { for (auto element : local_data_) { for (size_t i = 0; i < emitters_.size(); i++) { emitters_[i](element); } } for (size_t i = 0; i < emitters_.size(); i++) { emitters_[i].Close(); } auto it = context_.get_data_manager().template GetIterator<Output>(channel_used_); do { it.WaitForMore(); while (it.HasNext()) { out_vector_->push_back(it.Next()); } } while (!it.IsClosed()); } /*! * Returns "[AllGatherNode]" and its id as a string. * \return "[AllGatherNode]" */ std::string ToString() override { return "[AllGatherNode] Id: " + data_id_.ToString(); } private: //! Local stack Stack local_stack_; std::vector<Output> local_data_; std::vector<Output> * out_vector_; data::ChannelId channel_used_; static const bool debug = false; std::vector<data::Emitter<Output>> emitters_; }; } // namespace c7a #endif // !C7A_API_WRITE_NODE_HEADER /******************************************************************************/ <commit_msg>push data trhough network in allgather's pre-op<commit_after>/******************************************************************************* * c7a/api/allgather_node.hpp * * Part of Project c7a. * * Copyright (C) 2015 Alexander Noe <uagtc@student.kit.edu> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_ALLGATHER_NODE_HEADER #define C7A_API_ALLGATHER_NODE_HEADER #include <c7a/common/future.hpp> #include <c7a/net/collective_communication.hpp> #include <c7a/data/manager.hpp> #include <string> #include "action_node.hpp" #include "dia_node.hpp" #include "function_stack.hpp" namespace c7a { template <typename Input, typename Output, typename Stack> class AllGatherNode : public ActionNode<Input> { public: using Super = ActionNode<Input>; using Super::context_; using Super::data_id_; AllGatherNode(Context& ctx, DIANode<Input>* parent, //TODO(??) don't we need to pass shared ptrs for the ref counting? Stack& stack, std::vector<Output>* out_vector ) : ActionNode<Input>(ctx, { parent }), local_stack_(stack), out_vector_(out_vector), channel_used_(ctx.get_data_manager().AllocateNetworkChannel()) { emitters_ = context_. get_data_manager().template GetNetworkEmitters<Output>(channel_used_); auto pre_op_function = [=](Output input) { PreOp(input); }; auto lop_chain = local_stack_.push(pre_op_function).emit(); parent->RegisterChild(lop_chain); } void PreOp(Output element) { for (size_t i = 0; i < emitters_.size(); i++) { emitters_[i](element); } } virtual ~AllGatherNode() { } //! Closes the output file void execute() override { //data has been pushed during pre-op -> close emitters for (size_t i = 0; i < emitters_.size(); i++) { emitters_[i].Close(); } auto it = context_.get_data_manager().template GetIterator<Output>(channel_used_); do { it.WaitForMore(); while (it.HasNext()) { out_vector_->push_back(it.Next()); } } while (!it.IsClosed()); } /*! * Returns "[AllGatherNode]" and its id as a string. * \return "[AllGatherNode]" */ std::string ToString() override { return "[AllGatherNode] Id: " + data_id_.ToString(); } private: //! Local stack Stack local_stack_; std::vector<Output> * out_vector_; data::ChannelId channel_used_; static const bool debug = false; std::vector<data::Emitter<Output>> emitters_; }; } // namespace c7a #endif // !C7A_API_WRITE_NODE_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: environmentofanchoredobject.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-03-08 14:01:53 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _ENVIRONMENTOFANCHOREDOBJECT #include <environmentofanchoredobject.hxx> #endif #ifndef _FRAME_HXX #include <frame.hxx> #endif #ifndef _PAGEFRM_HXX #include <pagefrm.hxx> #endif #ifndef _FLYFRM_HXX #include <flyfrm.hxx> #endif using namespace objectpositioning; SwEnvironmentOfAnchoredObject::SwEnvironmentOfAnchoredObject( const bool _bFollowTextFlow ) : mbFollowTextFlow( _bFollowTextFlow ) {} SwEnvironmentOfAnchoredObject::~SwEnvironmentOfAnchoredObject() {} /** determine environment layout frame for possible horizontal object positions OD 05.11.2003 @author OD */ const SwLayoutFrm& SwEnvironmentOfAnchoredObject::GetHoriEnvironmentLayoutFrm( const SwFrm& _rHoriOrientFrm, const bool _bForPageAlignment ) const { const SwFrm* pHoriEnvironmentLayFrm = &_rHoriOrientFrm; if ( !mbFollowTextFlow ) { if ( _bForPageAlignment ) { while ( !pHoriEnvironmentLayFrm->IsCellFrm() && !pHoriEnvironmentLayFrm->IsPageFrm() ) { pHoriEnvironmentLayFrm = pHoriEnvironmentLayFrm->IsFlyFrm() ? static_cast<const SwFlyFrm*>(pHoriEnvironmentLayFrm)->GetAnchor() : pHoriEnvironmentLayFrm->GetUpper(); ASSERT( pHoriEnvironmentLayFrm, "SwEnvironmentOfAnchoredObject::GetHoriEnvironmentLayoutFrm(..) - no page|cell frame found" ); } } else { pHoriEnvironmentLayFrm = _rHoriOrientFrm.FindPageFrm(); } } else { while ( !pHoriEnvironmentLayFrm->IsCellFrm() && !pHoriEnvironmentLayFrm->IsFlyFrm() && !pHoriEnvironmentLayFrm->IsPageFrm() ) { pHoriEnvironmentLayFrm = pHoriEnvironmentLayFrm->GetUpper(); ASSERT( pHoriEnvironmentLayFrm, "SwEnvironmentOfAnchoredObject::GetHoriEnvironmentLayoutFrm(..) - no page|fly|cell frame found" ); } } ASSERT( pHoriEnvironmentLayFrm->ISA(SwLayoutFrm), "SwEnvironmentOfAnchoredObject::GetHoriEnvironmentLayoutFrm(..) - found frame isn't a layout frame" ); return static_cast<const SwLayoutFrm&>(*pHoriEnvironmentLayFrm); } /** determine environment layout frame for possible vertical object positions OD 05.11.2003 @author OD */ const SwLayoutFrm& SwEnvironmentOfAnchoredObject::GetVertEnvironmentLayoutFrm( const SwFrm& _rVertOrientFrm, const bool _bForPageAlignment ) const { const SwFrm* pVertEnvironmentLayFrm = &_rVertOrientFrm; if ( !mbFollowTextFlow ) { if ( _bForPageAlignment ) { while ( !pVertEnvironmentLayFrm->IsCellFrm() && !pVertEnvironmentLayFrm->IsPageFrm() ) { pVertEnvironmentLayFrm = pVertEnvironmentLayFrm->IsFlyFrm() ? static_cast<const SwFlyFrm*>(pVertEnvironmentLayFrm)->GetAnchor() : pVertEnvironmentLayFrm->GetUpper(); ASSERT( pVertEnvironmentLayFrm, "SwEnvironmentOfAnchoredObject::GetVertEnvironmentLayoutFrm(..) - proposed frame not found" ); } } else { pVertEnvironmentLayFrm = _rVertOrientFrm.FindPageFrm(); } } else { while ( !pVertEnvironmentLayFrm->IsCellFrm() && !pVertEnvironmentLayFrm->IsFlyFrm() && !pVertEnvironmentLayFrm->IsHeaderFrm() && !pVertEnvironmentLayFrm->IsFooterFrm() && !pVertEnvironmentLayFrm->IsFtnFrm() && !pVertEnvironmentLayFrm->IsPageBodyFrm() && !pVertEnvironmentLayFrm->IsPageFrm() ) { pVertEnvironmentLayFrm = pVertEnvironmentLayFrm->GetUpper(); ASSERT( pVertEnvironmentLayFrm, "SwEnvironmentOfAnchoredObject::GetVertEnvironmentLayoutFrm(..) - proposed frame not found" ); } } ASSERT( pVertEnvironmentLayFrm->ISA(SwLayoutFrm), "SwEnvironmentOfAnchoredObject::GetVertEnvironmentLayoutFrm(..) - found frame isn't a layout frame" ); return static_cast<const SwLayoutFrm&>(*pVertEnvironmentLayFrm); } <commit_msg>INTEGRATION: CWS swdrawpositioning (1.2.6); FILE MERGED 2004/04/07 12:23:11 od 1.2.6.1: #i26791# - adjustments for the unification of the positioning of Writer fly frames and drawing objects<commit_after>/************************************************************************* * * $RCSfile: environmentofanchoredobject.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hjs $ $Date: 2004-06-28 13:42:54 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _ENVIRONMENTOFANCHOREDOBJECT #include <environmentofanchoredobject.hxx> #endif #ifndef _FRAME_HXX #include <frame.hxx> #endif #ifndef _PAGEFRM_HXX #include <pagefrm.hxx> #endif #ifndef _FLYFRM_HXX #include <flyfrm.hxx> #endif using namespace objectpositioning; SwEnvironmentOfAnchoredObject::SwEnvironmentOfAnchoredObject( const bool _bFollowTextFlow ) : mbFollowTextFlow( _bFollowTextFlow ) {} SwEnvironmentOfAnchoredObject::~SwEnvironmentOfAnchoredObject() {} /** determine environment layout frame for possible horizontal object positions OD 05.11.2003 @author OD */ const SwLayoutFrm& SwEnvironmentOfAnchoredObject::GetHoriEnvironmentLayoutFrm( const SwFrm& _rHoriOrientFrm, const bool _bForPageAlignment ) const { const SwFrm* pHoriEnvironmentLayFrm = &_rHoriOrientFrm; if ( !mbFollowTextFlow ) { if ( _bForPageAlignment ) { while ( !pHoriEnvironmentLayFrm->IsCellFrm() && !pHoriEnvironmentLayFrm->IsPageFrm() ) { pHoriEnvironmentLayFrm = pHoriEnvironmentLayFrm->IsFlyFrm() ? static_cast<const SwFlyFrm*>(pHoriEnvironmentLayFrm)->GetAnchorFrm() : pHoriEnvironmentLayFrm->GetUpper(); ASSERT( pHoriEnvironmentLayFrm, "SwEnvironmentOfAnchoredObject::GetHoriEnvironmentLayoutFrm(..) - no page|cell frame found" ); } } else { pHoriEnvironmentLayFrm = _rHoriOrientFrm.FindPageFrm(); } } else { while ( !pHoriEnvironmentLayFrm->IsCellFrm() && !pHoriEnvironmentLayFrm->IsFlyFrm() && !pHoriEnvironmentLayFrm->IsPageFrm() ) { pHoriEnvironmentLayFrm = pHoriEnvironmentLayFrm->GetUpper(); ASSERT( pHoriEnvironmentLayFrm, "SwEnvironmentOfAnchoredObject::GetHoriEnvironmentLayoutFrm(..) - no page|fly|cell frame found" ); } } ASSERT( pHoriEnvironmentLayFrm->ISA(SwLayoutFrm), "SwEnvironmentOfAnchoredObject::GetHoriEnvironmentLayoutFrm(..) - found frame isn't a layout frame" ); return static_cast<const SwLayoutFrm&>(*pHoriEnvironmentLayFrm); } /** determine environment layout frame for possible vertical object positions OD 05.11.2003 @author OD */ const SwLayoutFrm& SwEnvironmentOfAnchoredObject::GetVertEnvironmentLayoutFrm( const SwFrm& _rVertOrientFrm, const bool _bForPageAlignment ) const { const SwFrm* pVertEnvironmentLayFrm = &_rVertOrientFrm; if ( !mbFollowTextFlow ) { if ( _bForPageAlignment ) { while ( !pVertEnvironmentLayFrm->IsCellFrm() && !pVertEnvironmentLayFrm->IsPageFrm() ) { pVertEnvironmentLayFrm = pVertEnvironmentLayFrm->IsFlyFrm() ? static_cast<const SwFlyFrm*>(pVertEnvironmentLayFrm)->GetAnchorFrm() : pVertEnvironmentLayFrm->GetUpper(); ASSERT( pVertEnvironmentLayFrm, "SwEnvironmentOfAnchoredObject::GetVertEnvironmentLayoutFrm(..) - proposed frame not found" ); } } else { pVertEnvironmentLayFrm = _rVertOrientFrm.FindPageFrm(); } } else { while ( !pVertEnvironmentLayFrm->IsCellFrm() && !pVertEnvironmentLayFrm->IsFlyFrm() && !pVertEnvironmentLayFrm->IsHeaderFrm() && !pVertEnvironmentLayFrm->IsFooterFrm() && !pVertEnvironmentLayFrm->IsFtnFrm() && !pVertEnvironmentLayFrm->IsPageBodyFrm() && !pVertEnvironmentLayFrm->IsPageFrm() ) { pVertEnvironmentLayFrm = pVertEnvironmentLayFrm->GetUpper(); ASSERT( pVertEnvironmentLayFrm, "SwEnvironmentOfAnchoredObject::GetVertEnvironmentLayoutFrm(..) - proposed frame not found" ); } } ASSERT( pVertEnvironmentLayFrm->ISA(SwLayoutFrm), "SwEnvironmentOfAnchoredObject::GetVertEnvironmentLayoutFrm(..) - found frame isn't a layout frame" ); return static_cast<const SwLayoutFrm&>(*pVertEnvironmentLayFrm); } <|endoftext|>
<commit_before>/* * Copyright 2015 - 2018 gtalent2@gmail.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "types.hpp" #ifdef DEBUG #define OxError(x) x ? reinterpret_cast<uint64_t>(__FILE__) | _errorTags(__LINE__, x) : 0 #else #define OxError(x) x #endif #define oxReturnError(x) if (const auto err = x) return err namespace ox { using Error = uint64_t; constexpr Error errCode(Error err) { return (err >> 58) & onMask<Error>(5); } struct ErrorInfo { const char *file = nullptr; int line = -1; Error errCode = 0; ErrorInfo() = default; ErrorInfo(Error err) { this->file = reinterpret_cast<const char*>(err & onMask<Error>(48)); this->line = static_cast<int>((err >> 48) & onMask<Error>(11)); this->errCode = ox::errCode(err); } }; static constexpr Error _errorTags(Error line, Error errCode) { line &= onMask<Error>(11); line <<= 48; errCode &= onMask<Error>(5); errCode <<= 59; return errCode | line; } template<typename T> struct ValErr { T value; Error error; inline constexpr ValErr() = default; inline constexpr ValErr(T value, Error error = 0): value(value), error(error) { } inline constexpr operator const T&() const { return value; } inline constexpr operator T&() { return value; } inline constexpr bool ok() const { return error == 0; } }; } <commit_msg>[ox/std] Further constexpr OxError<commit_after>/* * Copyright 2015 - 2018 gtalent2@gmail.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "types.hpp" #ifdef DEBUG #define OxError(x) ox::_error(__FILE__, __LINE__, x) #else #define OxError(x) x #endif #define oxReturnError(x) if (const auto err = x) return err namespace ox { using Error = uint64_t; constexpr Error errCode(Error err) { return (err >> 58) & onMask<Error>(5); } struct ErrorInfo { const char *file = nullptr; int line = -1; Error errCode = 0; ErrorInfo() = default; ErrorInfo(Error err) { this->file = reinterpret_cast<const char*>(err & onMask<Error>(48)); this->line = static_cast<int>((err >> 48) & onMask<Error>(11)); this->errCode = ox::errCode(err); } }; static constexpr Error _errorTags(Error line, Error errCode) { line &= onMask<Error>(11); line <<= 48; errCode &= onMask<Error>(5); errCode <<= 59; return errCode | line; } static constexpr Error _error(const char *file, int line, Error errCode) { return errCode ? reinterpret_cast<uint64_t>(file) | _errorTags(line, errCode) : 0; } template<typename T> struct ValErr { T value; Error error; inline constexpr ValErr() = default; inline constexpr ValErr(T value, Error error = 0): value(value), error(error) { } inline constexpr operator const T&() const { return value; } inline constexpr operator T&() { return value; } inline constexpr bool ok() const { return error == 0; } }; } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "MemoryLeakCheck.h" #include "Color.h" #include "Quaternion.h" #include "Transform.h" #include "Vector3D.h" #include "Matrix4.h" #include "IAttribute.h" #include "AssetReference.h" #include <QScriptEngine> #include <QColor> #include <QVector3D> #include <QQuaternion> #include <QScriptValueIterator> #include "LoggingFunctions.h" DEFINE_POCO_LOGGING_FUNCTIONS("JavaScriptEngine") Q_DECLARE_METATYPE(IAttribute*); QScriptValue toScriptValueColor(QScriptEngine *engine, const Color &s) { QScriptValue obj = engine->newObject(); obj.setProperty("r", QScriptValue(engine, s.r)); obj.setProperty("g", QScriptValue(engine, s.g)); obj.setProperty("b", QScriptValue(engine, s.b)); obj.setProperty("a", QScriptValue(engine, s.a)); return obj; } void fromScriptValueColor(const QScriptValue &obj, Color &s) { s.r = (float)obj.property("r").toNumber(); s.g = (float)obj.property("g").toNumber(); s.b = (float)obj.property("b").toNumber(); s.a = (float)obj.property("a").toNumber(); } /* QScriptValue toScriptValueQColor(QScriptEngine *engine, const QColor &s) { QScriptValue obj = engine->newObject(); obj.setProperty("r", QScriptValue(engine, s.red())); obj.setProperty("g", QScriptValue(engine, s.green())); obj.setProperty("b", QScriptValue(engine, s.blue())); obj.setProperty("a", QScriptValue(engine, s.alpha())); return obj; } void fromScriptValueQColor(const QScriptValue &obj, QColor &s) { s.setRed((float)obj.property("r").toNumber()); s.setGreen((float)obj.property("g").toNumber()); s.setBlue((float)obj.property("b").toNumber()); s.setAlpha((float)obj.property("a").toNumber()); } */ QScriptValue Vector3df_prototype_normalize(QScriptContext *ctx, QScriptEngine *engine); QScriptValue Vector3df_prototype_getLength(QScriptContext *ctx, QScriptEngine *engine); QScriptValue Vector3df_prototype_mul(QScriptContext *ctx, QScriptEngine *engine); QScriptValue toScriptValueVector3(QScriptEngine *engine, const Vector3df &s) { QScriptValue obj = engine->newObject(); obj.setProperty("x", QScriptValue(engine, s.x)); obj.setProperty("y", QScriptValue(engine, s.y)); obj.setProperty("z", QScriptValue(engine, s.z)); //this should suffice only once for the prototype somehow, but couldn't get that to work //ctorVector3df.property("prototype").setProperty("normalize", normalizeVector3df); obj.prototype().setProperty("normalize", engine->newFunction(Vector3df_prototype_normalize)); obj.prototype().setProperty("getLength", engine->newFunction(Vector3df_prototype_getLength)); obj.prototype().setProperty("mul", engine->newFunction(Vector3df_prototype_mul)); return obj; } void fromScriptValueVector3(const QScriptValue &obj, Vector3df &s) { s.x = (float)obj.property("x").toNumber(); s.y = (float)obj.property("y").toNumber(); s.z = (float)obj.property("z").toNumber(); } QScriptValue Vector3df_prototype_normalize(QScriptContext *ctx, QScriptEngine *engine) { Vector3df vec; fromScriptValueVector3(ctx->thisObject(), vec); return toScriptValueVector3(engine, vec.normalize()); } QScriptValue Vector3df_prototype_getLength(QScriptContext *ctx, QScriptEngine *engine) { Vector3df vec; fromScriptValueVector3(ctx->thisObject(), vec); return vec.getLength(); } QScriptValue Vector3df_prototype_mul(QScriptContext *ctx, QScriptEngine *engine) { if (ctx->argumentCount() != 1) return ctx->throwError("Vector3df mul() takes a single number argument."); if (!ctx->argument(0).isNumber()) return ctx->throwError(QScriptContext::TypeError, "Vector3df mul(): argument is not a number"); float scalar = ctx->argument(0).toNumber(); //XXX add vec*vec Vector3df vec; fromScriptValueVector3(ctx->thisObject(), vec); return toScriptValueVector3(engine, vec * scalar); } /* QScriptValue toScriptValueQVector3D(QScriptEngine *engine, const QVector3D &s) { QScriptValue obj = engine->newObject(); obj.setProperty("x", QScriptValue(engine, s.x())); obj.setProperty("y", QScriptValue(engine, s.y())); obj.setProperty("z", QScriptValue(engine, s.z())); return obj; } void fromScriptValueQVector3D(const QScriptValue &obj, QVector3D &s) { s.setX((float)obj.property("x").toNumber()); s.setY((float)obj.property("y").toNumber()); s.setZ((float)obj.property("z").toNumber()); } */ QScriptValue toScriptValueQuaternion(QScriptEngine *engine, const Quaternion &s) { QScriptValue obj = engine->newObject(); obj.setProperty("x", QScriptValue(engine, s.x)); obj.setProperty("y", QScriptValue(engine, s.y)); obj.setProperty("z", QScriptValue(engine, s.z)); obj.setProperty("w", QScriptValue(engine, s.w)); return obj; } void fromScriptValueQuaternion(const QScriptValue &obj, Quaternion &s) { s.x = (float)obj.property("x").toNumber(); s.y = (float)obj.property("y").toNumber(); s.z = (float)obj.property("z").toNumber(); s.w = (float)obj.property("w").toNumber(); } /* QScriptValue toScriptValueQQuaternion(QScriptEngine *engine, const QQuaternion &s) { QScriptValue obj = engine->newObject(); obj.setProperty("x", QScriptValue(engine, s.x())); obj.setProperty("y", QScriptValue(engine, s.y())); obj.setProperty("z", QScriptValue(engine, s.z())); obj.setProperty("w", QScriptValue(engine, s.scalar())); return obj; } void fromScriptValueQQuaternion(const QScriptValue &obj, QQuaternion &s) { s.setX((float)obj.property("x").toNumber()); s.setY((float)obj.property("y").toNumber()); s.setZ((float)obj.property("z").toNumber()); s.setScalar((float)obj.property("w").toNumber()); } */ QScriptValue toScriptValueTransform(QScriptEngine *engine, const Transform &s) { QScriptValue obj = engine->newObject(); obj.setProperty("pos", toScriptValueVector3(engine, s.position)); obj.setProperty("rot", toScriptValueVector3(engine, s.rotation)); obj.setProperty("scale", toScriptValueVector3(engine, s.scale)); return obj; } void fromScriptValueTransform(const QScriptValue &obj, Transform &s) { fromScriptValueVector3(obj.property("pos"), s.position); fromScriptValueVector3(obj.property("rot"), s.rotation); fromScriptValueVector3(obj.property("scale"), s.scale); } QScriptValue toScriptValueIAttribute(QScriptEngine *engine, const IAttribute *&s) { QScriptValue obj = engine->newObject(); if(s) { obj.setProperty("name", QScriptValue(engine, QString::fromStdString(s->GetNameString()))); obj.setProperty("typename", QScriptValue(engine, QString::fromStdString(s->TypeName()))); obj.setProperty("value", QScriptValue(engine, QString::fromStdString(s->ToString()))); } else { LogError("Fail to get attribute values from IAttribute pointer, cause pointer was a null. returning empty object."); } return obj; } void fromScriptValueAssetReference(const QScriptValue &obj, AssetReference &s) { s.ref = obj.property("ref").toString(); } QScriptValue toScriptValueAssetReference(QScriptEngine *engine, const AssetReference &s) { QScriptValue obj = engine->newObject(); obj.setProperty("ref", QScriptValue(engine, s.ref)); return obj; } void fromScriptValueAssetReferenceList(const QScriptValue &obj, AssetReferenceList &s) { QScriptValueIterator it(obj); while (it.hasNext()) { it.next(); AssetReference reference(it.value().toString()); s.Append(reference); } } QScriptValue toScriptValueAssetReferenceList(QScriptEngine *engine, const AssetReferenceList &s) { QScriptValue obj = engine->newObject(); for( int i = 0; i < s.refs.size(); ++i) { obj.setProperty(i, QScriptValue(engine, s.refs[i].toString())); } return obj; } void fromScriptValueIAttribute(const QScriptValue &obj, IAttribute *&s) { } QScriptValue createColor(QScriptContext *ctx, QScriptEngine *engine) { Color newColor; return engine->toScriptValue(newColor); } QScriptValue createVector3df(QScriptContext *ctx, QScriptEngine *engine) { Vector3df newVec; newVec.x = 0; newVec.y = 0; newVec.z = 0; return engine->toScriptValue(newVec); } QScriptValue createQuaternion(QScriptContext *ctx, QScriptEngine *engine) { Quaternion newQuat; return engine->toScriptValue(newQuat); } QScriptValue createTransform(QScriptContext *ctx, QScriptEngine *engine) { Transform newTransform; return engine->toScriptValue(newTransform); } QScriptValue createAssetReference(QScriptContext *ctx, QScriptEngine *engine) { AssetReference newAssetRef; return engine->toScriptValue(newAssetRef); } QScriptValue createAssetReferenceList(QScriptContext *ctx, QScriptEngine *engine) { AssetReferenceList newAssetRefList; return engine->toScriptValue(newAssetRefList); } void RegisterNaaliCoreMetaTypes() { qRegisterMetaType<Color>("Color"); qRegisterMetaType<Vector3df>("Vector3df"); qRegisterMetaType<Quaternion>("Quaternion"); qRegisterMetaType<Transform>("Transform"); qRegisterMetaType<AssetReference>("AssetReference"); qRegisterMetaType<AssetReferenceList>("AssetReferenceList"); } void ExposeNaaliCoreTypes(QScriptEngine *engine) { qScriptRegisterMetaType(engine, toScriptValueColor, fromScriptValueColor); //qScriptRegisterMetaType(engine, toScriptValueQColor, fromScriptValueQColor); qScriptRegisterMetaType(engine, toScriptValueVector3, fromScriptValueVector3); //qScriptRegisterMetaType(engine, toScriptValueQVector3D, fromScriptValueQVector3D); qScriptRegisterMetaType(engine, toScriptValueQuaternion, fromScriptValueQuaternion); //qScriptRegisterMetaType(engine, toScriptValueQQuaternion, fromScriptValueQQuaternion); qScriptRegisterMetaType(engine, toScriptValueTransform, fromScriptValueTransform); qScriptRegisterMetaType(engine, toScriptValueAssetReference, fromScriptValueAssetReference); qScriptRegisterMetaType(engine, toScriptValueAssetReferenceList, fromScriptValueAssetReferenceList); //qScriptRegisterMetaType<IAttribute*>(engine, toScriptValueIAttribute, fromScriptValueIAttribute); int id = qRegisterMetaType<IAttribute*>("IAttribute*"); qScriptRegisterMetaType_helper( engine, id, reinterpret_cast<QScriptEngine::MarshalFunction>(toScriptValueIAttribute), reinterpret_cast<QScriptEngine::DemarshalFunction>(fromScriptValueIAttribute), QScriptValue()); // Register constructors QScriptValue ctorColor = engine->newFunction(createColor); engine->globalObject().setProperty("Color", ctorColor); QScriptValue ctorTransform = engine->newFunction(createTransform); engine->globalObject().setProperty("Transform", ctorTransform); QScriptValue ctorAssetReference = engine->newFunction(createAssetReference); engine->globalObject().setProperty("AssetReference", ctorAssetReference); QScriptValue ctorAssetReferenceList = engine->newFunction(createAssetReferenceList); engine->globalObject().setProperty("AssetReferenceList", ctorAssetReferenceList); // Register both constructors and methods (with js prototype style) // http://doc.qt.nokia.com/latest/scripting.html#prototype-based-programming-with-the-qtscript-c-api /* doesn't work for some reason, is now hacked in toScriptValue to every instance (bad!) QScriptValue protoVector3df = engine->newObject(); protoVector3df.setProperty("normalize2", engine->newFunction(Vector3df_prototype_normalize));*/ QScriptValue ctorVector3df = engine->newFunction(createVector3df); //, protoVector3df); engine->globalObject().setProperty("Vector3df", ctorVector3df); QScriptValue ctorQuaternion = engine->newFunction(createQuaternion); engine->globalObject().setProperty("Quaternion", ctorQuaternion); } <commit_msg>remove previous attempt to put vector3df methods to the prototype of that type -- we don't actually have that type for js now, just return a generic object where put the vals, so these ended up in the global prototype used for all objects. now just stupidly puts the funcs to each new vec separately, to be improved.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "MemoryLeakCheck.h" #include "Color.h" #include "Quaternion.h" #include "Transform.h" #include "Vector3D.h" #include "Matrix4.h" #include "IAttribute.h" #include "AssetReference.h" #include <QScriptEngine> #include <QColor> #include <QVector3D> #include <QQuaternion> #include <QScriptValueIterator> #include "LoggingFunctions.h" DEFINE_POCO_LOGGING_FUNCTIONS("JavaScriptEngine") Q_DECLARE_METATYPE(IAttribute*); QScriptValue toScriptValueColor(QScriptEngine *engine, const Color &s) { QScriptValue obj = engine->newObject(); obj.setProperty("r", QScriptValue(engine, s.r)); obj.setProperty("g", QScriptValue(engine, s.g)); obj.setProperty("b", QScriptValue(engine, s.b)); obj.setProperty("a", QScriptValue(engine, s.a)); return obj; } void fromScriptValueColor(const QScriptValue &obj, Color &s) { s.r = (float)obj.property("r").toNumber(); s.g = (float)obj.property("g").toNumber(); s.b = (float)obj.property("b").toNumber(); s.a = (float)obj.property("a").toNumber(); } /* QScriptValue toScriptValueQColor(QScriptEngine *engine, const QColor &s) { QScriptValue obj = engine->newObject(); obj.setProperty("r", QScriptValue(engine, s.red())); obj.setProperty("g", QScriptValue(engine, s.green())); obj.setProperty("b", QScriptValue(engine, s.blue())); obj.setProperty("a", QScriptValue(engine, s.alpha())); return obj; } void fromScriptValueQColor(const QScriptValue &obj, QColor &s) { s.setRed((float)obj.property("r").toNumber()); s.setGreen((float)obj.property("g").toNumber()); s.setBlue((float)obj.property("b").toNumber()); s.setAlpha((float)obj.property("a").toNumber()); } */ QScriptValue Vector3df_prototype_normalize(QScriptContext *ctx, QScriptEngine *engine); QScriptValue Vector3df_prototype_getLength(QScriptContext *ctx, QScriptEngine *engine); QScriptValue Vector3df_prototype_mul(QScriptContext *ctx, QScriptEngine *engine); QScriptValue toScriptValueVector3(QScriptEngine *engine, const Vector3df &s) { QScriptValue obj = engine->newObject(); obj.setProperty("x", QScriptValue(engine, s.x)); obj.setProperty("y", QScriptValue(engine, s.y)); obj.setProperty("z", QScriptValue(engine, s.z)); //this should suffice only once for the prototype somehow, but couldn't get that to work //ctorVector3df.property("prototype").setProperty("normalize", normalizeVector3df); obj.setProperty("normalize", engine->newFunction(Vector3df_prototype_normalize)); obj.setProperty("getLength", engine->newFunction(Vector3df_prototype_getLength)); obj.setProperty("mul", engine->newFunction(Vector3df_prototype_mul)); return obj; } void fromScriptValueVector3(const QScriptValue &obj, Vector3df &s) { s.x = (float)obj.property("x").toNumber(); s.y = (float)obj.property("y").toNumber(); s.z = (float)obj.property("z").toNumber(); } QScriptValue Vector3df_prototype_normalize(QScriptContext *ctx, QScriptEngine *engine) { Vector3df vec; fromScriptValueVector3(ctx->thisObject(), vec); return toScriptValueVector3(engine, vec.normalize()); } QScriptValue Vector3df_prototype_getLength(QScriptContext *ctx, QScriptEngine *engine) { Vector3df vec; fromScriptValueVector3(ctx->thisObject(), vec); return vec.getLength(); } QScriptValue Vector3df_prototype_mul(QScriptContext *ctx, QScriptEngine *engine) { if (ctx->argumentCount() != 1) return ctx->throwError("Vector3df mul() takes a single number argument."); if (!ctx->argument(0).isNumber()) return ctx->throwError(QScriptContext::TypeError, "Vector3df mul(): argument is not a number"); float scalar = ctx->argument(0).toNumber(); //XXX add vec*vec Vector3df vec; fromScriptValueVector3(ctx->thisObject(), vec); return toScriptValueVector3(engine, vec * scalar); } /* QScriptValue toScriptValueQVector3D(QScriptEngine *engine, const QVector3D &s) { QScriptValue obj = engine->newObject(); obj.setProperty("x", QScriptValue(engine, s.x())); obj.setProperty("y", QScriptValue(engine, s.y())); obj.setProperty("z", QScriptValue(engine, s.z())); return obj; } void fromScriptValueQVector3D(const QScriptValue &obj, QVector3D &s) { s.setX((float)obj.property("x").toNumber()); s.setY((float)obj.property("y").toNumber()); s.setZ((float)obj.property("z").toNumber()); } */ QScriptValue toScriptValueQuaternion(QScriptEngine *engine, const Quaternion &s) { QScriptValue obj = engine->newObject(); obj.setProperty("x", QScriptValue(engine, s.x)); obj.setProperty("y", QScriptValue(engine, s.y)); obj.setProperty("z", QScriptValue(engine, s.z)); obj.setProperty("w", QScriptValue(engine, s.w)); return obj; } void fromScriptValueQuaternion(const QScriptValue &obj, Quaternion &s) { s.x = (float)obj.property("x").toNumber(); s.y = (float)obj.property("y").toNumber(); s.z = (float)obj.property("z").toNumber(); s.w = (float)obj.property("w").toNumber(); } /* QScriptValue toScriptValueQQuaternion(QScriptEngine *engine, const QQuaternion &s) { QScriptValue obj = engine->newObject(); obj.setProperty("x", QScriptValue(engine, s.x())); obj.setProperty("y", QScriptValue(engine, s.y())); obj.setProperty("z", QScriptValue(engine, s.z())); obj.setProperty("w", QScriptValue(engine, s.scalar())); return obj; } void fromScriptValueQQuaternion(const QScriptValue &obj, QQuaternion &s) { s.setX((float)obj.property("x").toNumber()); s.setY((float)obj.property("y").toNumber()); s.setZ((float)obj.property("z").toNumber()); s.setScalar((float)obj.property("w").toNumber()); } */ QScriptValue toScriptValueTransform(QScriptEngine *engine, const Transform &s) { QScriptValue obj = engine->newObject(); obj.setProperty("pos", toScriptValueVector3(engine, s.position)); obj.setProperty("rot", toScriptValueVector3(engine, s.rotation)); obj.setProperty("scale", toScriptValueVector3(engine, s.scale)); return obj; } void fromScriptValueTransform(const QScriptValue &obj, Transform &s) { fromScriptValueVector3(obj.property("pos"), s.position); fromScriptValueVector3(obj.property("rot"), s.rotation); fromScriptValueVector3(obj.property("scale"), s.scale); } QScriptValue toScriptValueIAttribute(QScriptEngine *engine, const IAttribute *&s) { QScriptValue obj = engine->newObject(); if(s) { obj.setProperty("name", QScriptValue(engine, QString::fromStdString(s->GetNameString()))); obj.setProperty("typename", QScriptValue(engine, QString::fromStdString(s->TypeName()))); obj.setProperty("value", QScriptValue(engine, QString::fromStdString(s->ToString()))); } else { LogError("Fail to get attribute values from IAttribute pointer, cause pointer was a null. returning empty object."); } return obj; } void fromScriptValueAssetReference(const QScriptValue &obj, AssetReference &s) { s.ref = obj.property("ref").toString(); } QScriptValue toScriptValueAssetReference(QScriptEngine *engine, const AssetReference &s) { QScriptValue obj = engine->newObject(); obj.setProperty("ref", QScriptValue(engine, s.ref)); return obj; } void fromScriptValueAssetReferenceList(const QScriptValue &obj, AssetReferenceList &s) { QScriptValueIterator it(obj); while (it.hasNext()) { it.next(); AssetReference reference(it.value().toString()); s.Append(reference); } } QScriptValue toScriptValueAssetReferenceList(QScriptEngine *engine, const AssetReferenceList &s) { QScriptValue obj = engine->newObject(); for( int i = 0; i < s.refs.size(); ++i) { obj.setProperty(i, QScriptValue(engine, s.refs[i].toString())); } return obj; } void fromScriptValueIAttribute(const QScriptValue &obj, IAttribute *&s) { } QScriptValue createColor(QScriptContext *ctx, QScriptEngine *engine) { Color newColor; return engine->toScriptValue(newColor); } QScriptValue createVector3df(QScriptContext *ctx, QScriptEngine *engine) { Vector3df newVec; newVec.x = 0; newVec.y = 0; newVec.z = 0; return engine->toScriptValue(newVec); } QScriptValue createQuaternion(QScriptContext *ctx, QScriptEngine *engine) { Quaternion newQuat; return engine->toScriptValue(newQuat); } QScriptValue createTransform(QScriptContext *ctx, QScriptEngine *engine) { Transform newTransform; return engine->toScriptValue(newTransform); } QScriptValue createAssetReference(QScriptContext *ctx, QScriptEngine *engine) { AssetReference newAssetRef; return engine->toScriptValue(newAssetRef); } QScriptValue createAssetReferenceList(QScriptContext *ctx, QScriptEngine *engine) { AssetReferenceList newAssetRefList; return engine->toScriptValue(newAssetRefList); } void RegisterNaaliCoreMetaTypes() { qRegisterMetaType<Color>("Color"); qRegisterMetaType<Vector3df>("Vector3df"); qRegisterMetaType<Quaternion>("Quaternion"); qRegisterMetaType<Transform>("Transform"); qRegisterMetaType<AssetReference>("AssetReference"); qRegisterMetaType<AssetReferenceList>("AssetReferenceList"); } void ExposeNaaliCoreTypes(QScriptEngine *engine) { qScriptRegisterMetaType(engine, toScriptValueColor, fromScriptValueColor); //qScriptRegisterMetaType(engine, toScriptValueQColor, fromScriptValueQColor); qScriptRegisterMetaType(engine, toScriptValueVector3, fromScriptValueVector3); //qScriptRegisterMetaType(engine, toScriptValueQVector3D, fromScriptValueQVector3D); qScriptRegisterMetaType(engine, toScriptValueQuaternion, fromScriptValueQuaternion); //qScriptRegisterMetaType(engine, toScriptValueQQuaternion, fromScriptValueQQuaternion); qScriptRegisterMetaType(engine, toScriptValueTransform, fromScriptValueTransform); qScriptRegisterMetaType(engine, toScriptValueAssetReference, fromScriptValueAssetReference); qScriptRegisterMetaType(engine, toScriptValueAssetReferenceList, fromScriptValueAssetReferenceList); //qScriptRegisterMetaType<IAttribute*>(engine, toScriptValueIAttribute, fromScriptValueIAttribute); int id = qRegisterMetaType<IAttribute*>("IAttribute*"); qScriptRegisterMetaType_helper( engine, id, reinterpret_cast<QScriptEngine::MarshalFunction>(toScriptValueIAttribute), reinterpret_cast<QScriptEngine::DemarshalFunction>(fromScriptValueIAttribute), QScriptValue()); // Register constructors QScriptValue ctorColor = engine->newFunction(createColor); engine->globalObject().setProperty("Color", ctorColor); QScriptValue ctorTransform = engine->newFunction(createTransform); engine->globalObject().setProperty("Transform", ctorTransform); QScriptValue ctorAssetReference = engine->newFunction(createAssetReference); engine->globalObject().setProperty("AssetReference", ctorAssetReference); QScriptValue ctorAssetReferenceList = engine->newFunction(createAssetReferenceList); engine->globalObject().setProperty("AssetReferenceList", ctorAssetReferenceList); // Register both constructors and methods (with js prototype style) // http://doc.qt.nokia.com/latest/scripting.html#prototype-based-programming-with-the-qtscript-c-api /* doesn't work for some reason, is now hacked in toScriptValue to every instance (bad!) */ QScriptValue protoVector3df = engine->newObject(); protoVector3df.setProperty("normalize2", engine->newFunction(Vector3df_prototype_normalize)); //leaving in for debug/test purposes QScriptValue ctorVector3df = engine->newFunction(createVector3df, protoVector3df); //this is supposed to work according to docs, doesnt. engine->globalObject().setProperty("Vector3df", ctorVector3df); QScriptValue ctorQuaternion = engine->newFunction(createQuaternion); engine->globalObject().setProperty("Quaternion", ctorQuaternion); } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: $ */ //_________________________________________________________________________ // Steering class for particle (gamma, hadron) identification and correlation analysis // It is called by the task class AliAnalysisTaskParticleCorrelation and it connects the input // (ESD/AOD/MonteCarlo) got with AliCaloTrackReader (produces TClonesArrays of AODs // (TParticles in MC case if requested)), with the // analysis classes that derive from AliAnaPartCorrBaseClass // // -- Author: Gustavo Conesa (INFN-LNF) #include <cstdlib> // --- ROOT system --- #include "TClonesArray.h" #include "TList.h" #include "TH1.h" //#include "Riostream.h" #include <TObjectTable.h> //---- AliRoot system ---- #include "AliAnaPartCorrBaseClass.h" #include "AliAnaPartCorrMaker.h" #include "AliCaloTrackReader.h" ClassImp(AliAnaPartCorrMaker) //____________________________________________________________________________ AliAnaPartCorrMaker::AliAnaPartCorrMaker() : TObject(), fOutputContainer(new TList ), fAnalysisContainer(new TList ), fMakeHisto(0), fMakeAOD(0), fAnaDebug(0), fReader(0x0), fAODBranchList(new TList ) { //Default Ctor if(fAnaDebug > 1 ) printf("*** Analysis Maker Constructor *** \n"); //Initialize parameters, pointers and histograms if(!fReader) fReader = new AliCaloTrackReader(); InitParameters(); } //____________________________________________________________________________ AliAnaPartCorrMaker::AliAnaPartCorrMaker(const AliAnaPartCorrMaker & g) : TObject(), fOutputContainer(g. fOutputContainer), fAnalysisContainer(g.fAnalysisContainer), fMakeHisto(g.fMakeHisto), fMakeAOD(fMakeAOD), fAnaDebug(g. fAnaDebug), fReader(g.fReader), fAODBranchList(g.fAODBranchList) { // cpy ctor } //_________________________________________________________________________ AliAnaPartCorrMaker & AliAnaPartCorrMaker::operator = (const AliAnaPartCorrMaker & source) { // assignment operator if(this == &source)return *this; ((TObject *)this)->operator=(source); fOutputContainer = source.fOutputContainer ; fAnalysisContainer = source.fAnalysisContainer ; fAnaDebug = source.fAnaDebug; fMakeHisto = source.fMakeHisto; fMakeAOD = source.fMakeAOD; fReader = source.fReader ; fAODBranchList = source.fAODBranchList; return *this; } //____________________________________________________________________________ AliAnaPartCorrMaker::~AliAnaPartCorrMaker() { // Remove all pointers. // Protection added in case of NULL pointers (MG) if (fOutputContainer) { fOutputContainer->Clear(); delete fOutputContainer ; } if (fAnalysisContainer) { fAnalysisContainer->Clear(); delete fAnalysisContainer ; } if (fReader) delete fReader ; if(fAODBranchList){ // for(Int_t iaod = 0; iaod < fAODBranchList->GetEntries(); iaod++) // fAODBranchList->At(iaod)->Clear(); fAODBranchList->Clear(); delete fAODBranchList ; } } //________________________________________________________________________ TList * AliAnaPartCorrMaker::GetAODBranchList() { // Get any new output AOD branches from analysis and put them in a list // The list is filled in the maker, and new branch passed to the analysis frame // AliAnalysisTaskPartCorr for(Int_t iana = 0; iana < fAnalysisContainer->GetEntries(); iana++){ AliAnaPartCorrBaseClass * ana = ((AliAnaPartCorrBaseClass *) fAnalysisContainer->At(iana)) ; if(ana->NewOutputAOD()) fAODBranchList->Add(ana->GetCreateOutputAODBranch()); } return fAODBranchList ; } //________________________________________________________________________ TList *AliAnaPartCorrMaker::GetOutputContainer() { // Fill the output list of histograms during the CreateOutputObjects stage. if(!fAnalysisContainer || fAnalysisContainer->GetEntries()==0){ printf("AliAnaPartCorrMaker::GetOutputContainer() - Analysis job list not initialized!!!\n"); //abort(); } char newname[128]; for(Int_t iana = 0; iana < fAnalysisContainer->GetEntries(); iana++){ AliAnaPartCorrBaseClass * ana = ((AliAnaPartCorrBaseClass *) fAnalysisContainer->At(iana)) ; if(fMakeHisto){// Analysis with histograms as output on //Fill container with appropriate histograms TList * templist = ana -> GetCreateOutputObjects(); for(Int_t i = 0; i < templist->GetEntries(); i++){ //Add only to the histogram name the name of the task if( strcmp((templist->At(i))->ClassName(),"TObjString") ) { sprintf(newname,"%s%s", (ana->GetAddedHistogramsStringToName()).Data(), (templist->At(i))->GetName()); ((TH1*) templist->At(i))->SetName(newname); } //Add histogram to general container fOutputContainer->Add(templist->At(i)) ; } }// Analysis with histograms as output on }//Loop on analysis defined return fOutputContainer; } //________________________________________________________________________ void AliAnaPartCorrMaker::Init() { //Init container histograms and other common variables // Fill the output list of histograms during the CreateOutputObjects stage. if(!fAnalysisContainer || fAnalysisContainer->GetEntries()==0){ printf("AliAnaPartCorrMaker::GetOutputInit() - Analysis job list not initialized!!!\n"); //abort(); } //Initialize reader fReader->Init(); for(Int_t iana = 0; iana < fAnalysisContainer->GetEntries(); iana++){ AliAnaPartCorrBaseClass * ana = ((AliAnaPartCorrBaseClass *) fAnalysisContainer->At(iana)) ; ana->SetReader(fReader); //SetReader for each analysis ana->Init(); }//Loop on analysis defined } //____________________________________________________________________________ void AliAnaPartCorrMaker::InitParameters() { //Init data members fMakeHisto = kTRUE; fMakeAOD = kTRUE; fAnaDebug = 0; // No debugging info displayed by default } //__________________________________________________________________ void AliAnaPartCorrMaker::Print(const Option_t * opt) const { //Print some relevant parameters set for the analysis if(! opt) return; printf("***** Print: %s %s ******\n", GetName(), GetTitle() ) ; printf("Debug level = %d\n", fAnaDebug) ; printf("Produce Histo = %d\n", fMakeHisto) ; printf("Produce AOD = %d\n", fMakeAOD) ; } //____________________________________________________________________________ void AliAnaPartCorrMaker::ProcessEvent(const Int_t iEntry, const char * currentFileName){ //Process analysis for this event if(fMakeHisto && !fOutputContainer){ printf("AliAnaPartCorrMaker::ProcessEvent() - Histograms not initialized\n"); abort(); } if(fAnaDebug >= 0 ){ printf("*** Event %d *** \n",iEntry); if(fAnaDebug > 1 ) printf("AliAnaPartCorrMaker::Current File Name : %s\n", currentFileName); } //Each event needs an empty branch for(Int_t iaod = 0; iaod < fAODBranchList->GetEntries(); iaod++) fAODBranchList->At(iaod)->Clear(); //Tell the reader to fill the data in the 3 detector lists Bool_t ok = fReader->FillInputEvent(iEntry, currentFileName); if(!ok){ printf("*** Skip event *** %d \n",iEntry); return ; } printf(">>>>>>>>>> BEFORE >>>>>>>>>>>\n"); gObjectTable->Print(); //Loop on analysis algorithms if(fAnaDebug > 0 ) printf("*** Begin analysis *** \n"); Int_t nana = fAnalysisContainer->GetEntries() ; for(Int_t iana = 0; iana < nana; iana++){ AliAnaPartCorrBaseClass * ana = ((AliAnaPartCorrBaseClass *) fAnalysisContainer->At(iana)) ; ana->ConnectInputOutputAODBranches(); //Sets branches for each analysis //Make analysis, create aods in aod branch or AODCaloClusters if(fMakeAOD) ana->MakeAnalysisFillAOD() ; //Make further analysis with aod branch and fill histograms if(fMakeHisto) ana->MakeAnalysisFillHistograms() ; } fReader->ResetLists(); printf(">>>>>>>>>> AFTER >>>>>>>>>>>\n"); gObjectTable->Print(); if(fAnaDebug > 0 ) printf("*** End analysis *** \n"); } //________________________________________________________________________ void AliAnaPartCorrMaker::Terminate(TList * outputList) { //Execute Terminate of analysis //Do some final plots. if (!outputList) { Error("Terminate", "No output list"); return; } for(Int_t iana = 0; iana < fAnalysisContainer->GetEntries(); iana++){ AliAnaPartCorrBaseClass * ana = ((AliAnaPartCorrBaseClass *) fAnalysisContainer->At(iana)) ; ana->Terminate(outputList); }//Loop on analysis defined } <commit_msg>Revert changes in AliAnaPartCorrMaker, testing printouts removed<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: $ */ //_________________________________________________________________________ // Steering class for particle (gamma, hadron) identification and correlation analysis // It is called by the task class AliAnalysisTaskParticleCorrelation and it connects the input // (ESD/AOD/MonteCarlo) got with AliCaloTrackReader (produces TClonesArrays of AODs // (TParticles in MC case if requested)), with the // analysis classes that derive from AliAnaPartCorrBaseClass // // -- Author: Gustavo Conesa (INFN-LNF) #include <cstdlib> // --- ROOT system --- #include "TClonesArray.h" #include "TList.h" #include "TH1.h" //#include "Riostream.h" //#include <TObjectTable.h> //---- AliRoot system ---- #include "AliAnaPartCorrBaseClass.h" #include "AliAnaPartCorrMaker.h" #include "AliCaloTrackReader.h" ClassImp(AliAnaPartCorrMaker) //____________________________________________________________________________ AliAnaPartCorrMaker::AliAnaPartCorrMaker() : TObject(), fOutputContainer(new TList ), fAnalysisContainer(new TList ), fMakeHisto(0), fMakeAOD(0), fAnaDebug(0), fReader(0x0), fAODBranchList(new TList ) { //Default Ctor if(fAnaDebug > 1 ) printf("*** Analysis Maker Constructor *** \n"); //Initialize parameters, pointers and histograms if(!fReader) fReader = new AliCaloTrackReader(); InitParameters(); } //____________________________________________________________________________ AliAnaPartCorrMaker::AliAnaPartCorrMaker(const AliAnaPartCorrMaker & g) : TObject(), fOutputContainer(g. fOutputContainer), fAnalysisContainer(g.fAnalysisContainer), fMakeHisto(g.fMakeHisto), fMakeAOD(fMakeAOD), fAnaDebug(g. fAnaDebug), fReader(g.fReader), fAODBranchList(g.fAODBranchList) { // cpy ctor } //_________________________________________________________________________ AliAnaPartCorrMaker & AliAnaPartCorrMaker::operator = (const AliAnaPartCorrMaker & source) { // assignment operator if(this == &source)return *this; ((TObject *)this)->operator=(source); fOutputContainer = source.fOutputContainer ; fAnalysisContainer = source.fAnalysisContainer ; fAnaDebug = source.fAnaDebug; fMakeHisto = source.fMakeHisto; fMakeAOD = source.fMakeAOD; fReader = source.fReader ; fAODBranchList = source.fAODBranchList; return *this; } //____________________________________________________________________________ AliAnaPartCorrMaker::~AliAnaPartCorrMaker() { // Remove all pointers. // Protection added in case of NULL pointers (MG) if (fOutputContainer) { fOutputContainer->Clear(); delete fOutputContainer ; } if (fAnalysisContainer) { fAnalysisContainer->Clear(); delete fAnalysisContainer ; } if (fReader) delete fReader ; if(fAODBranchList){ // for(Int_t iaod = 0; iaod < fAODBranchList->GetEntries(); iaod++) // fAODBranchList->At(iaod)->Clear(); fAODBranchList->Clear(); delete fAODBranchList ; } } //________________________________________________________________________ TList * AliAnaPartCorrMaker::GetAODBranchList() { // Get any new output AOD branches from analysis and put them in a list // The list is filled in the maker, and new branch passed to the analysis frame // AliAnalysisTaskPartCorr for(Int_t iana = 0; iana < fAnalysisContainer->GetEntries(); iana++){ AliAnaPartCorrBaseClass * ana = ((AliAnaPartCorrBaseClass *) fAnalysisContainer->At(iana)) ; if(ana->NewOutputAOD()) fAODBranchList->Add(ana->GetCreateOutputAODBranch()); } return fAODBranchList ; } //________________________________________________________________________ TList *AliAnaPartCorrMaker::GetOutputContainer() { // Fill the output list of histograms during the CreateOutputObjects stage. if(!fAnalysisContainer || fAnalysisContainer->GetEntries()==0){ printf("AliAnaPartCorrMaker::GetOutputContainer() - Analysis job list not initialized!!!\n"); //abort(); } char newname[128]; for(Int_t iana = 0; iana < fAnalysisContainer->GetEntries(); iana++){ AliAnaPartCorrBaseClass * ana = ((AliAnaPartCorrBaseClass *) fAnalysisContainer->At(iana)) ; if(fMakeHisto){// Analysis with histograms as output on //Fill container with appropriate histograms TList * templist = ana -> GetCreateOutputObjects(); for(Int_t i = 0; i < templist->GetEntries(); i++){ //Add only to the histogram name the name of the task if( strcmp((templist->At(i))->ClassName(),"TObjString") ) { sprintf(newname,"%s%s", (ana->GetAddedHistogramsStringToName()).Data(), (templist->At(i))->GetName()); ((TH1*) templist->At(i))->SetName(newname); } //Add histogram to general container fOutputContainer->Add(templist->At(i)) ; } }// Analysis with histograms as output on }//Loop on analysis defined return fOutputContainer; } //________________________________________________________________________ void AliAnaPartCorrMaker::Init() { //Init container histograms and other common variables // Fill the output list of histograms during the CreateOutputObjects stage. if(!fAnalysisContainer || fAnalysisContainer->GetEntries()==0){ printf("AliAnaPartCorrMaker::GetOutputInit() - Analysis job list not initialized!!!\n"); //abort(); } //Initialize reader fReader->Init(); for(Int_t iana = 0; iana < fAnalysisContainer->GetEntries(); iana++){ AliAnaPartCorrBaseClass * ana = ((AliAnaPartCorrBaseClass *) fAnalysisContainer->At(iana)) ; ana->SetReader(fReader); //SetReader for each analysis ana->Init(); }//Loop on analysis defined } //____________________________________________________________________________ void AliAnaPartCorrMaker::InitParameters() { //Init data members fMakeHisto = kTRUE; fMakeAOD = kTRUE; fAnaDebug = 0; // No debugging info displayed by default } //__________________________________________________________________ void AliAnaPartCorrMaker::Print(const Option_t * opt) const { //Print some relevant parameters set for the analysis if(! opt) return; printf("***** Print: %s %s ******\n", GetName(), GetTitle() ) ; printf("Debug level = %d\n", fAnaDebug) ; printf("Produce Histo = %d\n", fMakeHisto) ; printf("Produce AOD = %d\n", fMakeAOD) ; } //____________________________________________________________________________ void AliAnaPartCorrMaker::ProcessEvent(const Int_t iEntry, const char * currentFileName){ //Process analysis for this event if(fMakeHisto && !fOutputContainer){ printf("AliAnaPartCorrMaker::ProcessEvent() - Histograms not initialized\n"); abort(); } if(fAnaDebug >= 0 ){ printf("*** Event %d *** \n",iEntry); if(fAnaDebug > 1 ) printf("AliAnaPartCorrMaker::Current File Name : %s\n", currentFileName); } //Each event needs an empty branch for(Int_t iaod = 0; iaod < fAODBranchList->GetEntries(); iaod++) fAODBranchList->At(iaod)->Clear(); //Tell the reader to fill the data in the 3 detector lists Bool_t ok = fReader->FillInputEvent(iEntry, currentFileName); if(!ok){ printf("*** Skip event *** %d \n",iEntry); return ; } //printf(">>>>>>>>>> BEFORE >>>>>>>>>>>\n"); //gObjectTable->Print(); //Loop on analysis algorithms if(fAnaDebug > 0 ) printf("*** Begin analysis *** \n"); Int_t nana = fAnalysisContainer->GetEntries() ; for(Int_t iana = 0; iana < nana; iana++){ AliAnaPartCorrBaseClass * ana = ((AliAnaPartCorrBaseClass *) fAnalysisContainer->At(iana)) ; ana->ConnectInputOutputAODBranches(); //Sets branches for each analysis //Make analysis, create aods in aod branch or AODCaloClusters if(fMakeAOD) ana->MakeAnalysisFillAOD() ; //Make further analysis with aod branch and fill histograms if(fMakeHisto) ana->MakeAnalysisFillHistograms() ; } fReader->ResetLists(); //printf(">>>>>>>>>> AFTER >>>>>>>>>>>\n"); //gObjectTable->Print(); if(fAnaDebug > 0 ) printf("*** End analysis *** \n"); } //________________________________________________________________________ void AliAnaPartCorrMaker::Terminate(TList * outputList) { //Execute Terminate of analysis //Do some final plots. if (!outputList) { Error("Terminate", "No output list"); return; } for(Int_t iana = 0; iana < fAnalysisContainer->GetEntries(); iana++){ AliAnaPartCorrBaseClass * ana = ((AliAnaPartCorrBaseClass *) fAnalysisContainer->At(iana)) ; ana->Terminate(outputList); }//Loop on analysis defined } <|endoftext|>
<commit_before>// $Id$ // // Standalone jet finder // // Authors: R.Haake #include "AliFJWrapper.h" #include "AliEmcalJet.h" #include "AliEmcalJetFinder.h" #include "AliLog.h" #include <vector> #include "TH1.h" //________________________________________________________________________ AliEmcalJetFinder::AliEmcalJetFinder() : TNamed("EmcalJetFinder","EmcalJetFinder"), fFastjetWrapper(0), fInputVectorIndex(0), fJetCount(0), fJetArray(), fGhostArea(0.005), fRadius(0.4), fJetAlgorithm(0), fRecombScheme(-1), fTrackMaxEta(0.9), fJetMaxEta(0.5), fJetMinPt(0), fJetMinArea(0) { // Constructor fFastjetWrapper = new AliFJWrapper("FJWrapper", "FJWrapper"); } //________________________________________________________________________ AliEmcalJetFinder::AliEmcalJetFinder(const char* name) : TNamed(name, name), fFastjetWrapper(0), fInputVectorIndex(0), fJetCount(0), fJetArray(), fGhostArea(0.005), fRadius(0.4), fJetAlgorithm(0), fRecombScheme(-1), fTrackMaxEta(0.9), fJetMaxEta(0.5), fJetMinPt(0), fJetMinArea(0) { // Constructor fFastjetWrapper = new AliFJWrapper("FJWrapper", "FJWrapper"); } //________________________________________________________________________ AliEmcalJetFinder::~AliEmcalJetFinder() { if(fFastjetWrapper) delete fFastjetWrapper; } //________________________________________________________________________ Bool_t AliEmcalJetFinder::FindJets() { // Tidy up and check input fJetArray.clear(); fJetCount = 0; if(!fInputVectorIndex) { AliError("No input vectors added to jet finder!"); return kFALSE; } // Pass settings to fastjet fFastjetWrapper->SetAreaType(fastjet::active_area_explicit_ghosts); fFastjetWrapper->SetGhostArea(fGhostArea); fFastjetWrapper->SetR(fRadius); if(fJetAlgorithm == 0) fFastjetWrapper->SetAlgorithm(fastjet::antikt_algorithm); if(fJetAlgorithm == 1) fFastjetWrapper->SetAlgorithm(fastjet::kt_algorithm); if(fRecombScheme>=0) fFastjetWrapper->SetRecombScheme(static_cast<fastjet::RecombinationScheme>(fRecombScheme)); fFastjetWrapper->SetMaxRap(fTrackMaxEta); // Run jet finding fFastjetWrapper->Run(); // Save the found jets as light-weight objects std::vector<fastjet::PseudoJet> fastjets = fFastjetWrapper->GetInclusiveJets(); fJetArray.resize(fastjets.size()); for (UInt_t i=0; i<fastjets.size(); i++) { // Apply jet cuts if (fastjets[i].perp()<fJetMinPt) continue; if (fFastjetWrapper->GetJetArea(i)<fJetMinArea) continue; if (TMath::Abs(fastjets[i].eta())>fJetMaxEta) continue; AliEmcalJet* jet = new AliEmcalJet(fastjets[i].perp(), fastjets[i].eta(), fastjets[i].phi(), fastjets[i].m()); // Set the most important properties of the jet Int_t nConstituents(fFastjetWrapper->GetJetConstituents(i).size()); jet->SetNumberOfTracks(nConstituents); jet->SetNumberOfClusters(nConstituents); fJetArray[fJetCount] = jet; fJetCount++; } fJetArray.resize(fJetCount); fastjets.clear(); fFastjetWrapper->Clear(); fInputVectorIndex = 0; return kTRUE; } //________________________________________________________________________ void AliEmcalJetFinder::AddInputVector(Double_t px, Double_t py, Double_t pz) { fFastjetWrapper->AddInputVector(px, py, pz, TMath::Sqrt(px*px + py*py + pz*pz), fInputVectorIndex + 100); fInputVectorIndex++; } //________________________________________________________________________ void AliEmcalJetFinder::AddInputVector(Double_t px, Double_t py, Double_t pz, Double_t E) { fFastjetWrapper->AddInputVector(px, py, pz, E, fInputVectorIndex + 100); fInputVectorIndex++; } //________________________________________________________________________ void AliEmcalJetFinder::FillPtHistogram(TH1* histogram) { if(!histogram) return; for (std::size_t i=0; i<fJetArray.size(); i++) { histogram->Fill(fJetArray[i]->Pt()); } } //________________________________________________________________________ void AliEmcalJetFinder::FillPhiHistogram(TH1* histogram) { if(!histogram) return; for (std::size_t i=0; i<fJetArray.size(); i++) { histogram->Fill(fJetArray[i]->Phi()); } } //________________________________________________________________________ void AliEmcalJetFinder::FillEtaHistogram(TH1* histogram) { if(!histogram) return; for (std::size_t i=0; i<fJetArray.size(); i++) { histogram->Fill(fJetArray[i]->Eta()); } } <commit_msg>Fix small memory leak: delete EmcalJet objects from vector<commit_after>// $Id$ // // Standalone jet finder // CINT-compatible wrapper for AliFJWrapper, can be used in macros and from the ROOT command line. // Compiled code can use AliFJWrapper directly // // Authors: R.Haake #include "AliFJWrapper.h" #include "AliEmcalJet.h" #include "AliEmcalJetFinder.h" #include "AliLog.h" #include <vector> #include "TH1.h" //________________________________________________________________________ AliEmcalJetFinder::AliEmcalJetFinder() : TNamed("EmcalJetFinder","EmcalJetFinder"), fFastjetWrapper(0), fInputVectorIndex(0), fJetCount(0), fJetArray(), fGhostArea(0.005), fRadius(0.4), fJetAlgorithm(0), fRecombScheme(-1), fTrackMaxEta(0.9), fJetMaxEta(0.5), fJetMinPt(0), fJetMinArea(0) { // Constructor fFastjetWrapper = new AliFJWrapper("FJWrapper", "FJWrapper"); } //________________________________________________________________________ AliEmcalJetFinder::AliEmcalJetFinder(const char* name) : TNamed(name, name), fFastjetWrapper(0), fInputVectorIndex(0), fJetCount(0), fJetArray(), fGhostArea(0.005), fRadius(0.4), fJetAlgorithm(0), fRecombScheme(-1), fTrackMaxEta(0.9), fJetMaxEta(0.5), fJetMinPt(0), fJetMinArea(0) { // Constructor fFastjetWrapper = new AliFJWrapper("FJWrapper", "FJWrapper"); } //________________________________________________________________________ AliEmcalJetFinder::~AliEmcalJetFinder() { if(fFastjetWrapper) delete fFastjetWrapper; } //________________________________________________________________________ Bool_t AliEmcalJetFinder::FindJets() { // Tidy up and check input for (UInt_t i=0; i<fJetArray.size(); i++) { delete fJetArray[i]; fJetArray[i] = 0; } fJetArray.clear(); fJetCount = 0; if(!fInputVectorIndex) { AliError("No input vectors added to jet finder!"); return kFALSE; } // Pass settings to fastjet fFastjetWrapper->SetAreaType(fastjet::active_area_explicit_ghosts); fFastjetWrapper->SetGhostArea(fGhostArea); fFastjetWrapper->SetR(fRadius); if(fJetAlgorithm == 0) fFastjetWrapper->SetAlgorithm(fastjet::antikt_algorithm); if(fJetAlgorithm == 1) fFastjetWrapper->SetAlgorithm(fastjet::kt_algorithm); if(fRecombScheme>=0) fFastjetWrapper->SetRecombScheme(static_cast<fastjet::RecombinationScheme>(fRecombScheme)); fFastjetWrapper->SetMaxRap(fTrackMaxEta); // Run jet finding fFastjetWrapper->Run(); // Save the found jets as light-weight objects std::vector<fastjet::PseudoJet> fastjets = fFastjetWrapper->GetInclusiveJets(); fJetArray.resize(fastjets.size()); for (UInt_t i=0; i<fastjets.size(); i++) { // Apply jet cuts if (fastjets[i].perp()<fJetMinPt) continue; if (fFastjetWrapper->GetJetArea(i)<fJetMinArea) continue; if (TMath::Abs(fastjets[i].eta())>fJetMaxEta) continue; AliEmcalJet* jet = new AliEmcalJet(fastjets[i].perp(), fastjets[i].eta(), fastjets[i].phi(), fastjets[i].m()); // Set the most important properties of the jet Int_t nConstituents(fFastjetWrapper->GetJetConstituents(i).size()); jet->SetNumberOfTracks(nConstituents); jet->SetNumberOfClusters(nConstituents); fJetArray[fJetCount] = jet; fJetCount++; } fJetArray.resize(fJetCount); //fastjets.clear(); // will be done by the destructor at the end of the function fFastjetWrapper->Clear(); fInputVectorIndex = 0; return kTRUE; } //________________________________________________________________________ void AliEmcalJetFinder::AddInputVector(Double_t px, Double_t py, Double_t pz) { fFastjetWrapper->AddInputVector(px, py, pz, TMath::Sqrt(px*px + py*py + pz*pz), fInputVectorIndex + 100); fInputVectorIndex++; } //________________________________________________________________________ void AliEmcalJetFinder::AddInputVector(Double_t px, Double_t py, Double_t pz, Double_t E) { fFastjetWrapper->AddInputVector(px, py, pz, E, fInputVectorIndex + 100); fInputVectorIndex++; } //________________________________________________________________________ void AliEmcalJetFinder::FillPtHistogram(TH1* histogram) { if(!histogram) return; for (std::size_t i=0; i<fJetArray.size(); i++) { histogram->Fill(fJetArray[i]->Pt()); } } //________________________________________________________________________ void AliEmcalJetFinder::FillPhiHistogram(TH1* histogram) { if(!histogram) return; for (std::size_t i=0; i<fJetArray.size(); i++) { histogram->Fill(fJetArray[i]->Phi()); } } //________________________________________________________________________ void AliEmcalJetFinder::FillEtaHistogram(TH1* histogram) { if(!histogram) return; for (std::size_t i=0; i<fJetArray.size(); i++) { histogram->Fill(fJetArray[i]->Eta()); } } <|endoftext|>
<commit_before>/* * Copyright 2018 Kacper Kasper <kacperkasper@gmail.com> * All rights reserved. Distributed under the terms of the MIT license. */ #include "Editorconfig.h" #include <algorithm> #include <fstream> #include <regex> #include <sstream> #include <string> #include <Directory.h> #include <Entry.h> #include <String.h> bool Editorconfig::Find(BPath* filePath, BPath* editorconfigPath) { if(filePath == nullptr) return false; bool found = false; BPath parentPath(*filePath); BDirectory parentDir; BEntry editorconfigFile; do { parentPath.GetParent(&parentPath); parentDir.SetTo(parentPath.Path()); editorconfigFile.SetTo(&parentDir, ".editorconfig"); found = editorconfigFile.Exists(); } while(!found && !parentDir.IsRootDirectory()); if(found && editorconfigPath != nullptr) { editorconfigFile.GetPath(editorconfigPath); } return found; } bool Editorconfig::Parse(const char* filename, BMessage* propertiesDict) { if(propertiesDict == nullptr) return false; std::ifstream file(filename, std::ifstream::in); if(!file.is_open()) return false; std::string currentSectionName; BMessage currentSection; std::string line; do { std::getline(file, line); if(line.empty() || line[0] == '#' || line[0] == ';') continue; if(line[0] == '[' && line[line.size() - 1] == ']') { // section if(!currentSectionName.empty() && !currentSection.IsEmpty()) { propertiesDict->AddMessage(currentSectionName.c_str(), &currentSection); currentSection.MakeEmpty(); } currentSectionName = line.substr(1, line.size() - 2); } else { // property std::string name, value; line.erase(std::remove_if(line.begin(), line.end(), [](char x) { return std::isspace(x); }), line.end()); std::istringstream linestream(line); std::getline(linestream, name, '='); std::getline(linestream, value, '='); currentSection.AddString(name.c_str(), value.c_str()); } } while(!file.eof()); if(!currentSectionName.empty() && !currentSection.IsEmpty()) { propertiesDict->AddMessage(currentSectionName.c_str(), &currentSection); } file.close(); return true; } void Editorconfig::MatchFilename(const char* filename, const BMessage* allProperties, BMessage* properties) { if(allProperties == nullptr) return; char* name; uint32 type; int32 count; for(int32 i = 0; allProperties->GetInfo(B_MESSAGE_TYPE, i, &name, &type, &count) == B_OK; i++) { BString regexStr(name); bool dirSpecific = false; int32 slashIndex = regexStr.FindFirst("/"); if(slashIndex != B_ERROR && slashIndex > 0 && regexStr[slashIndex - 1] != '\\') dirSpecific = true; bool inBrace = false; int32 c = 0; while(c < regexStr.Length()) { if(regexStr[c] == '*') { if(c > 0 && regexStr[c - 1] == '\\') { c++; continue; } // ** if(c < regexStr.Length() - 1 && regexStr[c + 1] == '*') { regexStr.Replace("**", "(.+)", 1, c); c += strlen("(.+)"); } else { BString s; if(dirSpecific) s = "([^/]+)"; else s = "(.+)"; regexStr.Replace("*", s, 1, c); c += s.Length(); } continue; } else if(regexStr[c] == '!') { // FIXME: only if in []? if(c > 0 && regexStr[c - 1] == '\\') { c++; continue; } regexStr.Replace("!", "^", 1, c); } else if(regexStr[c] == '.') { regexStr.Replace(".", "\\.", 1, c); c += 2; continue; } if(!inBrace) { if(regexStr[c] == '{') { if(c > 0 && regexStr[c - 1] == '\\') { c++; continue; } inBrace = true; regexStr.Replace("{", "(", 1, c); } } else { if(c > 0 && regexStr[c - 1] == '\\') { c++; continue; } if(regexStr[c] == ',') regexStr.Replace(",", "|", 1, c); if(regexStr[c] == '}') { inBrace = false; regexStr.Replace("}", ")", 1, c); } } c++; } std::regex expr(regexStr.String()); if(properties != nullptr && std::regex_match(filename, expr)) { BMessage globProperties; if(allProperties->FindMessage(name, &globProperties) == B_OK) { char* stringName; for(int32 j = 0; globProperties.GetInfo(B_STRING_TYPE, j, &stringName, &type, &count) == B_OK; j++) { BString value; globProperties.FindString(stringName, &value); properties->RemoveName(stringName); properties->AddString(stringName, value); } } } } } <commit_msg>Editorconfig: Fix Nested Strings (#133)<commit_after>/* * Copyright 2018 Kacper Kasper <kacperkasper@gmail.com> * All rights reserved. Distributed under the terms of the MIT license. */ #include "Editorconfig.h" #include <algorithm> #include <fstream> #include <regex> #include <sstream> #include <string> #include <Directory.h> #include <Entry.h> #include <String.h> bool Editorconfig::Find(BPath* filePath, BPath* editorconfigPath) { if(filePath == nullptr) return false; bool found = false; BPath parentPath(*filePath); BDirectory parentDir; BEntry editorconfigFile; do { parentPath.GetParent(&parentPath); parentDir.SetTo(parentPath.Path()); editorconfigFile.SetTo(&parentDir, ".editorconfig"); found = editorconfigFile.Exists(); } while(!found && !parentDir.IsRootDirectory()); if(found && editorconfigPath != nullptr) { editorconfigFile.GetPath(editorconfigPath); } return found; } bool Editorconfig::Parse(const char* filename, BMessage* propertiesDict) { if(propertiesDict == nullptr) return false; std::ifstream file(filename, std::ifstream::in); if(!file.is_open()) return false; std::string currentSectionName; BMessage currentSection; std::string line; do { std::getline(file, line); if(line.empty() || line[0] == '#' || line[0] == ';') continue; if(line[0] == '[' && line[line.size() - 1] == ']') { // section if(!currentSectionName.empty() && !currentSection.IsEmpty()) { propertiesDict->AddMessage(currentSectionName.c_str(), &currentSection); currentSection.MakeEmpty(); } currentSectionName = line.substr(1, line.size() - 2); } else { // property std::string name, value; line.erase(std::remove_if(line.begin(), line.end(), [](char x) { return std::isspace(x); }), line.end()); std::istringstream linestream(line); std::getline(linestream, name, '='); std::getline(linestream, value, '='); currentSection.AddString(name.c_str(), value.c_str()); } } while(!file.eof()); if(!currentSectionName.empty() && !currentSection.IsEmpty()) { propertiesDict->AddMessage(currentSectionName.c_str(), &currentSection); } file.close(); return true; } void Editorconfig::MatchFilename(const char* filename, const BMessage* allProperties, BMessage* properties) { if(allProperties == nullptr) return; char* name; uint32 type; int32 count; for(int32 i = 0; allProperties->GetInfo(B_MESSAGE_TYPE, i, &name, &type, &count) == B_OK; i++) { BString regexStr(name); bool dirSpecific = false; int32 slashIndex = regexStr.FindFirst("/"); if(slashIndex != B_ERROR && slashIndex > 0 && regexStr[slashIndex - 1] != '\\') dirSpecific = true; int32 inBraceCount = 0; int32 c = 0; while(c < regexStr.Length()) { if(regexStr[c] == '*') { if(c > 0 && regexStr[c - 1] == '\\') { c++; continue; } // ** if(c < regexStr.Length() - 1 && regexStr[c + 1] == '*') { regexStr.Replace("**", "(.+)", 1, c); c += strlen("(.+)"); } else { BString s; if(dirSpecific) s = "([^/]+)"; else s = "(.+)"; regexStr.Replace("*", s, 1, c); c += s.Length(); } continue; } else if(regexStr[c] == '!') { // FIXME: only if in []? if(c > 0 && regexStr[c - 1] == '\\') { c++; continue; } regexStr.Replace("!", "^", 1, c); } else if(regexStr[c] == '.') { regexStr.Replace(".", "\\.", 1, c); c += 2; continue; } if(regexStr[c] == '{') { if(c > 0 && regexStr[c - 1] == '\\') { c++; continue; } inBraceCount++; regexStr.Replace("{", "(", 1, c); } if(inBraceCount > 0) { if(c > 0 && regexStr[c - 1] == '\\') { c++; continue; } if(regexStr[c] == ',') regexStr.Replace(",", "|", 1, c); if(regexStr[c] == '}') { inBraceCount--; regexStr.Replace("}", ")", 1, c); } } c++; } if(inBraceCount != 0) return; std::regex expr(regexStr.String()); if(properties != nullptr && std::regex_match(filename, expr)) { BMessage globProperties; if(allProperties->FindMessage(name, &globProperties) == B_OK) { char* stringName; for(int32 j = 0; globProperties.GetInfo(B_STRING_TYPE, j, &stringName, &type, &count) == B_OK; j++) { BString value; globProperties.FindString(stringName, &value); properties->RemoveName(stringName); properties->AddString(stringName, value); } } } } } <|endoftext|>
<commit_before>#include "common/RhodesApp.h" #include "common/RhoStd.h" #include "common/RhoConf.h" #include "common/RhoFile.h" #include "common/RhoDefs.h" #include "common/Tokenizer.h" #include "logging/RhoLogConf.h" #include "generated/cpp/LogCaptureBase.h" namespace rho { using namespace apiGenerator; using namespace common; class CLogCaptureImpl: public CLogCaptureSingletonBase, public ILogSink { public: CLogCaptureImpl(): CLogCaptureSingletonBase(), mMaxLines(1024), mTotalSize(0) {} // ILogSink virtual void writeLogMessage( String& strMsg ) { if ( mMaxLines > 0 ) { if (mCapturedLog.size() > mMaxLines) { mCapturedLog.clear(); mTotalSize = 0; } if (mExcludeCategories.size()>0) { for(Vector<String>::const_iterator it = mExcludeCategories.begin(); it != mExcludeCategories.end(); ++it) { if (strMsg.find(*it)!=String::npos) { return; } } } mCapturedLog.push_back(strMsg); mTotalSize += strMsg.size() + 2; } } virtual int getCurPos() { return mCapturedLog.size(); } virtual void clear() { } // ILogCaptureSingleto virtual void getExcludeCategories(rho::apiGenerator::CMethodResult& oResult) { const Vector<rho::String>& log_attr = mExcludeCategories; size_t len = 0; for(Vector<rho::String>::const_iterator iter = log_attr.begin(); iter != log_attr.end(); iter++) { len += (*iter).length() + 1; // including separator } rho::String str; str.reserve(len); for(Vector<rho::String>::const_iterator iter = log_attr.begin(); iter != log_attr.end(); iter++) { if (iter != log_attr.begin()) { str += ","; } str += *iter; } oResult.set( str ); } virtual void setExcludeCategories( const rho::String& excludeCategories, rho::apiGenerator::CMethodResult& oResult) { if ( excludeCategories.length() > 0 ) { rho::common::CTokenizer oTokenizer( excludeCategories, "," ); while (oTokenizer.hasMoreTokens()) { String tok = rho::String_trim(oTokenizer.nextToken()); if (tok.length() == 0) continue; mExcludeCategories.addElement( tok ); } } else mExcludeCategories.removeAllElements(); } virtual void getMaxLines(rho::apiGenerator::CMethodResult& oResult) { oResult.set(mMaxLines); } virtual void setMaxLines( int maxLines, rho::apiGenerator::CMethodResult& oResult) { mMaxLines = maxLines; } virtual void start(rho::apiGenerator::CMethodResult& oResult) { LOGCONF().addAuxSink(this); } virtual void stop(rho::apiGenerator::CMethodResult& oResult) { LOGCONF().removeAuxSink(this); } virtual void clear(rho::apiGenerator::CMethodResult& oResult) { mCapturedLog.clear(); mTotalSize = 0; } virtual void numLines(rho::apiGenerator::CMethodResult& oResult) { oResult.set( static_cast<int>(mCapturedLog.size()) ); } virtual void read(rho::apiGenerator::CMethodResult& oResult) { String str; str.reserve(mTotalSize); for (Vector<String>::iterator it = mCapturedLog.begin(); it != mCapturedLog.end(); ++it ) { str += *it; str += '\n'; } oResult.set(str); } private: Vector<String> mCapturedLog; Vector<String> mExcludeCategories; int mMaxLines; size_t mTotalSize; }; class CLogCaptureFactory: public CLogCaptureFactoryBase { public: ~CLogCaptureFactory(){} ILogCaptureSingleton* createModuleSingleton() { return new CLogCaptureImpl(); } }; } extern "C" void Init_LogCapture_extension() { rho::CLogCaptureFactory::setInstance( new rho::CLogCaptureFactory() ); rho::Init_LogCapture_API(); } <commit_msg>Add proper LogCapture destructor<commit_after>#include "common/RhodesApp.h" #include "common/RhoStd.h" #include "common/RhoConf.h" #include "common/RhoFile.h" #include "common/RhoDefs.h" #include "common/Tokenizer.h" #include "logging/RhoLogConf.h" #include "generated/cpp/LogCaptureBase.h" namespace rho { using namespace apiGenerator; using namespace common; class CLogCaptureImpl: public CLogCaptureSingletonBase, public ILogSink { public: CLogCaptureImpl(): CLogCaptureSingletonBase(), mMaxLines(1024), mTotalSize(0) {} virtual ~CLogCaptureImpl() { LOGCONF().removeAuxSink(this); } // ILogSink virtual void writeLogMessage( String& strMsg ) { if ( mMaxLines > 0 ) { if (mCapturedLog.size() > mMaxLines) { mCapturedLog.clear(); mTotalSize = 0; } if (mExcludeCategories.size()>0) { for(Vector<String>::const_iterator it = mExcludeCategories.begin(); it != mExcludeCategories.end(); ++it) { if (strMsg.find(*it)!=String::npos) { return; } } } mCapturedLog.push_back(strMsg); mTotalSize += strMsg.size() + 2; } } virtual int getCurPos() { return mCapturedLog.size(); } virtual void clear() { } // ILogCaptureSingleto virtual void getExcludeCategories(rho::apiGenerator::CMethodResult& oResult) { const Vector<rho::String>& log_attr = mExcludeCategories; size_t len = 0; for(Vector<rho::String>::const_iterator iter = log_attr.begin(); iter != log_attr.end(); iter++) { len += (*iter).length() + 1; // including separator } rho::String str; str.reserve(len); for(Vector<rho::String>::const_iterator iter = log_attr.begin(); iter != log_attr.end(); iter++) { if (iter != log_attr.begin()) { str += ","; } str += *iter; } oResult.set( str ); } virtual void setExcludeCategories( const rho::String& excludeCategories, rho::apiGenerator::CMethodResult& oResult) { if ( excludeCategories.length() > 0 ) { rho::common::CTokenizer oTokenizer( excludeCategories, "," ); while (oTokenizer.hasMoreTokens()) { String tok = rho::String_trim(oTokenizer.nextToken()); if (tok.length() == 0) continue; mExcludeCategories.addElement( tok ); } } else mExcludeCategories.removeAllElements(); } virtual void getMaxLines(rho::apiGenerator::CMethodResult& oResult) { oResult.set(mMaxLines); } virtual void setMaxLines( int maxLines, rho::apiGenerator::CMethodResult& oResult) { mMaxLines = maxLines; } virtual void start(rho::apiGenerator::CMethodResult& oResult) { LOGCONF().addAuxSink(this); } virtual void stop(rho::apiGenerator::CMethodResult& oResult) { LOGCONF().removeAuxSink(this); } virtual void clear(rho::apiGenerator::CMethodResult& oResult) { mCapturedLog.clear(); mTotalSize = 0; } virtual void numLines(rho::apiGenerator::CMethodResult& oResult) { oResult.set( static_cast<int>(mCapturedLog.size()) ); } virtual void read(rho::apiGenerator::CMethodResult& oResult) { String str; str.reserve(mTotalSize); for (Vector<String>::iterator it = mCapturedLog.begin(); it != mCapturedLog.end(); ++it ) { str += *it; str += '\n'; } oResult.set(str); } private: Vector<String> mCapturedLog; Vector<String> mExcludeCategories; int mMaxLines; size_t mTotalSize; }; class CLogCaptureFactory: public CLogCaptureFactoryBase { public: ~CLogCaptureFactory(){} ILogCaptureSingleton* createModuleSingleton() { return new CLogCaptureImpl(); } }; } extern "C" void Init_LogCapture_extension() { rho::CLogCaptureFactory::setInstance( new rho::CLogCaptureFactory() ); rho::Init_LogCapture_API(); } <|endoftext|>
<commit_before>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <fnord-base/uri.h> #include <fnordmetric/environment.h> #include <fnordmetric/adminui.h> namespace fnordmetric { AdminUI::AdminUI( std::string path_prefix /* = "/admin" */) : path_prefix_(path_prefix), webui_bundle_("FnordMetric"), webui_mount_(&webui_bundle_, path_prefix) { webui_bundle_.addComponent("fnord/3rdparty/codemirror.js"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.woff"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.css"); webui_bundle_.addComponent("fnord/3rdparty/reset.css"); webui_bundle_.addComponent("fnord/components/fn-table.css"); webui_bundle_.addComponent("fnord/components/fn-button.css"); webui_bundle_.addComponent("fnord/components/fn-modal.css"); webui_bundle_.addComponent("fnord/components/fn-tabbar.css"); webui_bundle_.addComponent("fnord/components/fn-message.css"); webui_bundle_.addComponent("fnord/components/fn-tooltip.css"); webui_bundle_.addComponent("fnord/components/fn-dropdown.css"); webui_bundle_.addComponent("fnord/components/fn-date-time-selector.css"); webui_bundle_.addComponent("fnord/components/fn-search.css"); webui_bundle_.addComponent("fnord/components/fn-input.css"); webui_bundle_.addComponent("fnord/components/fn-search.css"); webui_bundle_.addComponent("fnord/fnord.js"); webui_bundle_.addComponent("fnord/date_util.js"); webui_bundle_.addComponent("fnord/components/fn-appbar.html"); webui_bundle_.addComponent("fnord/components/fn-button.html"); webui_bundle_.addComponent("fnord/components/fn-button-group.html"); webui_bundle_.addComponent("fnord/components/fn-icon.html"); webui_bundle_.addComponent("fnord/components/fn-input.html"); webui_bundle_.addComponent("fnord/components/fn-loader.html"); webui_bundle_.addComponent("fnord/components/fn-menu.html"); webui_bundle_.addComponent("fnord/components/fn-search.html"); webui_bundle_.addComponent("fnord/components/fn-table.html"); webui_bundle_.addComponent("fnord/components/fn-splitpane.html"); webui_bundle_.addComponent("fnord/components/fn-codeeditor.html"); webui_bundle_.addComponent("fnord/components/fn-dropdown.html"); webui_bundle_.addComponent("fnord/components/fn-datepicker.html"); webui_bundle_.addComponent("fnord/components/fn-timeinput.html"); webui_bundle_.addComponent("fnord/components/fn-daterangepicker.html"); webui_bundle_.addComponent("fnord/components/fn-tabbar.html"); webui_bundle_.addComponent("fnord/components/fn-modal.html"); webui_bundle_.addComponent("fnord/components/fn-pager.html"); webui_bundle_.addComponent("fnord/components/fn-tooltip.html"); webui_bundle_.addComponent("fnord/components/fn-flexbox.html"); webui_bundle_.addComponent("fnord/components/fn-checkbox.html"); webui_bundle_.addComponent("fnord/components/fn-date-time-selector.html"); webui_bundle_.addComponent("fnord/components/fn-calendar.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-list.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-preview.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-search.html"); webui_bundle_.addComponent("fnord-metricdb/metric-control.html"); webui_bundle_.addComponent("fnord-metricdb/fn-metric-explorer.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-app.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-console.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-query-editor.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.html"); //webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-midnightblue.css"); //webui_bundle_.addComponent("fnord/themes/midnight-blue.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-cockpit.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-util.js"); webui_bundle_.addComponent( "fnordmetric/fnordmetric-embed-query-popup.html"); } void AdminUI::handleHTTPRequest( http::HTTPRequest* request, http::HTTPResponse* response) { fnord::URI uri(request->uri()); auto path = uri.path(); if (path == "/") { response->setStatus(http::kStatusFound); response->addHeader("Content-Type", "text/html; charset=utf-8"); response->addHeader("Location", path_prefix_); return; } if (path == "/fontawesome.woff") { request->setURI( StringUtil::format( "$0/__components__/fnord/3rdparty/fontawesome.woff", path_prefix_)); } webui_mount_.handleHTTPRequest(request, response); } } <commit_msg>render search view in metric-explorer-list<commit_after>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <fnord-base/uri.h> #include <fnordmetric/environment.h> #include <fnordmetric/adminui.h> namespace fnordmetric { AdminUI::AdminUI( std::string path_prefix /* = "/admin" */) : path_prefix_(path_prefix), webui_bundle_("FnordMetric"), webui_mount_(&webui_bundle_, path_prefix) { webui_bundle_.addComponent("fnord/3rdparty/codemirror.js"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.woff"); webui_bundle_.addComponent("fnord/3rdparty/fontawesome.css"); webui_bundle_.addComponent("fnord/3rdparty/reset.css"); webui_bundle_.addComponent("fnord/components/fn-table.css"); webui_bundle_.addComponent("fnord/components/fn-button.css"); webui_bundle_.addComponent("fnord/components/fn-modal.css"); webui_bundle_.addComponent("fnord/components/fn-tabbar.css"); webui_bundle_.addComponent("fnord/components/fn-message.css"); webui_bundle_.addComponent("fnord/components/fn-tooltip.css"); webui_bundle_.addComponent("fnord/components/fn-dropdown.css"); webui_bundle_.addComponent("fnord/components/fn-date-time-selector.css"); webui_bundle_.addComponent("fnord/components/fn-search.css"); webui_bundle_.addComponent("fnord/components/fn-input.css"); webui_bundle_.addComponent("fnord/components/fn-search.css"); webui_bundle_.addComponent("fnord/fnord.js"); webui_bundle_.addComponent("fnord/date_util.js"); webui_bundle_.addComponent("fnord/components/fn-appbar.html"); webui_bundle_.addComponent("fnord/components/fn-button.html"); webui_bundle_.addComponent("fnord/components/fn-button-group.html"); webui_bundle_.addComponent("fnord/components/fn-icon.html"); webui_bundle_.addComponent("fnord/components/fn-input.html"); webui_bundle_.addComponent("fnord/components/fn-loader.html"); webui_bundle_.addComponent("fnord/components/fn-menu.html"); webui_bundle_.addComponent("fnord/components/fn-search.html"); webui_bundle_.addComponent("fnord/components/fn-table.html"); webui_bundle_.addComponent("fnord/components/fn-splitpane.html"); webui_bundle_.addComponent("fnord/components/fn-codeeditor.html"); webui_bundle_.addComponent("fnord/components/fn-dropdown.html"); webui_bundle_.addComponent("fnord/components/fn-datepicker.html"); webui_bundle_.addComponent("fnord/components/fn-timeinput.html"); webui_bundle_.addComponent("fnord/components/fn-daterangepicker.html"); webui_bundle_.addComponent("fnord/components/fn-tabbar.html"); webui_bundle_.addComponent("fnord/components/fn-modal.html"); webui_bundle_.addComponent("fnord/components/fn-pager.html"); webui_bundle_.addComponent("fnord/components/fn-tooltip.html"); webui_bundle_.addComponent("fnord/components/fn-flexbox.html"); webui_bundle_.addComponent("fnord/components/fn-checkbox.html"); webui_bundle_.addComponent("fnord/components/fn-date-time-selector.html"); webui_bundle_.addComponent("fnord/components/fn-calendar.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-list.html"); webui_bundle_.addComponent("fnord-metricdb/metric-explorer-preview.html"); webui_bundle_.addComponent("fnord-metricdb/metric-control.html"); webui_bundle_.addComponent("fnord-metricdb/fn-metric-explorer.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-app.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-console.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-query-editor.html"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.html"); //webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-midnightblue.css"); //webui_bundle_.addComponent("fnord/themes/midnight-blue.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-cockpit.css"); webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-util.js"); webui_bundle_.addComponent( "fnordmetric/fnordmetric-embed-query-popup.html"); } void AdminUI::handleHTTPRequest( http::HTTPRequest* request, http::HTTPResponse* response) { fnord::URI uri(request->uri()); auto path = uri.path(); if (path == "/") { response->setStatus(http::kStatusFound); response->addHeader("Content-Type", "text/html; charset=utf-8"); response->addHeader("Location", path_prefix_); return; } if (path == "/fontawesome.woff") { request->setURI( StringUtil::format( "$0/__components__/fnord/3rdparty/fontawesome.woff", path_prefix_)); } webui_mount_.handleHTTPRequest(request, response); } } <|endoftext|>
<commit_before>/* * Copyright 2012-2013 BrewPi/Elco Jacobs. * Copyright 2013 Matthew McGowan. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "Brewpi.h" #include "OneWireTempSensor.h" #include "DallasTemperature.h" #include "OneWire.h" #include "OneWireDevices.h" #include "PiLink.h" #include "Ticks.h" OneWireTempSensor::~OneWireTempSensor(){ delete sensor; }; /** * Initializes the temperature sensor. * This method is called when the sensor is first created and also any time the sensor reports it's disconnected. * If the result is DEVICE_DISCONNECTED then subsequent calls to read() will also return DEVICE_DISCONNECTED. * Clients should attempt to re-initialize the sensor by calling init() again. */ fixed7_9 OneWireTempSensor::init(){ // save address and pinNr for debug messages char addressString[17]; printBytes(sensorAddress, 8, addressString); uint8_t pinNr = oneWire->pinNr(); if (sensor==NULL) { sensor = new DallasTemperature(oneWire); if (sensor==NULL) { logErrorString(ERROR_SRAM_SENSOR, addressString); setConnected(false); return DEVICE_DISCONNECTED; } } // get sensor address - todo this is deprecated and will be phased out. Needed to support revA shields #if BREWPI_STATIC_CONFIG==BREWPI_SHIELD_REV_A if (!sensorAddress[0]) { if (!sensor->getAddress(sensorAddress, 0)) { // error no sensor found logErrorInt(ERROR_SENSOR_NO_ADDRESS_ON_PIN, pinNr); setConnected(false); return DEVICE_DISCONNECTED; } else { #if (BREWPI_DEBUG > 0) printBytes(sensorAddress, 8, addressString); #endif } } #endif // This quickly tests if the sensor is connected. Suring the main TempControl loop, we don't want to spend many seconds // scanning each sensor since this brings things to a halt. if (!sensor->isConnected(sensorAddress)) { setConnected(false); return DEVICE_DISCONNECTED; } logDebug("Fetching initial temperature of sensor %s", addressString); sensor->setResolution(sensorAddress, 12); sensor->setWaitForConversion(false); // read initial temperature twice - first read is inaccurate fixed7_9 temperature; for (int i=0; i<2; i++) { temperature = DEVICE_DISCONNECTED; lastRequestTime = ticks.seconds(); while(temperature == DEVICE_DISCONNECTED){ sensor->requestTemperatures(); waitForConversion(); temperature = sensor->getTempRaw(sensorAddress); logDebug("Sensor initial temp read: pin %d %s %d", this->oneWire->pinNr(), addressString, temperature); if(ticks.timeSince(lastRequestTime) > 4) { setConnected(false); return DEVICE_DISCONNECTED; } } } temperature = constrainTemp(temperature+calibrationOffset, ((int) INT_MIN)>>5, ((int) INT_MAX)>>5)<<5; // sensor returns 12 bits with 4 fraction bits. Store with 9 fraction bits DEBUG_ONLY(logInfoIntStringTemp(INFO_TEMP_SENSOR_INITIALIZED, pinNr, addressString, temperature);) setConnected(true); return temperature; } void OneWireTempSensor::waitForConversion() { wait.millis(750); } void OneWireTempSensor::setConnected(bool connected) { if (this->connected==connected) return; // state is stays the same char addressString[17]; printBytes(sensorAddress, 8, addressString); this->connected = connected; if(connected){ logInfoIntString(INFO_TEMP_SENSOR_CONNECTED, this->oneWire->pinNr(), addressString); } else{ logWarningIntString(WARNING_TEMP_SENSOR_DISCONNECTED, this->oneWire->pinNr(), addressString); } } fixed7_9 OneWireTempSensor::read(){ if (!connected) return DEVICE_DISCONNECTED; if(ticks.timeSince(lastRequestTime) > 5){ // if last request is longer than 5 seconds ago, request again and delay sensor->requestTemperatures(); lastRequestTime = ticks.seconds(); waitForConversion(); } fixed7_9 temperature = sensor->getTempRaw(sensorAddress); if(temperature == DEVICE_DISCONNECTED){ setConnected(false); return DEVICE_DISCONNECTED; } temperature = constrainTemp(temperature+calibrationOffset, ((int) INT_MIN)>>5, ((int) INT_MAX)>>5)<<5; // sensor returns 12 bits with 4 fraction bits. Store with 9 fraction bits // already send request for next read sensor->requestTemperatures(); lastRequestTime = ticks.seconds(); return temperature; } <commit_msg>Shift output of sensors by -48C before storing as well. This should allow measuring mash temperatures.<commit_after>/* * Copyright 2012-2013 BrewPi/Elco Jacobs. * Copyright 2013 Matthew McGowan. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "Brewpi.h" #include "OneWireTempSensor.h" #include "DallasTemperature.h" #include "OneWire.h" #include "OneWireDevices.h" #include "PiLink.h" #include "Ticks.h" OneWireTempSensor::~OneWireTempSensor(){ delete sensor; }; /** * Initializes the temperature sensor. * This method is called when the sensor is first created and also any time the sensor reports it's disconnected. * If the result is DEVICE_DISCONNECTED then subsequent calls to read() will also return DEVICE_DISCONNECTED. * Clients should attempt to re-initialize the sensor by calling init() again. */ fixed7_9 OneWireTempSensor::init(){ // save address and pinNr for debug messages char addressString[17]; printBytes(sensorAddress, 8, addressString); uint8_t pinNr = oneWire->pinNr(); if (sensor==NULL) { sensor = new DallasTemperature(oneWire); if (sensor==NULL) { logErrorString(ERROR_SRAM_SENSOR, addressString); setConnected(false); return DEVICE_DISCONNECTED; } } // get sensor address - todo this is deprecated and will be phased out. Needed to support revA shields #if BREWPI_STATIC_CONFIG==BREWPI_SHIELD_REV_A if (!sensorAddress[0]) { if (!sensor->getAddress(sensorAddress, 0)) { // error no sensor found logErrorInt(ERROR_SENSOR_NO_ADDRESS_ON_PIN, pinNr); setConnected(false); return DEVICE_DISCONNECTED; } else { #if (BREWPI_DEBUG > 0) printBytes(sensorAddress, 8, addressString); #endif } } #endif // This quickly tests if the sensor is connected. Suring the main TempControl loop, we don't want to spend many seconds // scanning each sensor since this brings things to a halt. if (!sensor->isConnected(sensorAddress)) { setConnected(false); return DEVICE_DISCONNECTED; } logDebug("Fetching initial temperature of sensor %s", addressString); sensor->setResolution(sensorAddress, 12); sensor->setWaitForConversion(false); // read initial temperature twice - first read is inaccurate fixed7_9 temperature; for (int i=0; i<2; i++) { temperature = DEVICE_DISCONNECTED; lastRequestTime = ticks.seconds(); while(temperature == DEVICE_DISCONNECTED){ sensor->requestTemperatures(); waitForConversion(); temperature = sensor->getTempRaw(sensorAddress); logDebug("Sensor initial temp read: pin %d %s %d", this->oneWire->pinNr(), addressString, temperature); if(ticks.timeSince(lastRequestTime) > 4) { setConnected(false); return DEVICE_DISCONNECTED; } } } // sensor returns 12 bits with 4 fraction bits. Store with 9 fraction bits and add the offset for storage temperature = constrainTemp(temperature+calibrationOffset+(C_OFFSET>>5), ((int) INT_MIN)>>5, ((int) INT_MAX)>>5)<<5; DEBUG_ONLY(logInfoIntStringTemp(INFO_TEMP_SENSOR_INITIALIZED, pinNr, addressString, temperature);) setConnected(true); return temperature; } void OneWireTempSensor::waitForConversion() { wait.millis(750); } void OneWireTempSensor::setConnected(bool connected) { if (this->connected==connected) return; // state is stays the same char addressString[17]; printBytes(sensorAddress, 8, addressString); this->connected = connected; if(connected){ logInfoIntString(INFO_TEMP_SENSOR_CONNECTED, this->oneWire->pinNr(), addressString); } else{ logWarningIntString(WARNING_TEMP_SENSOR_DISCONNECTED, this->oneWire->pinNr(), addressString); } } fixed7_9 OneWireTempSensor::read(){ if (!connected) return DEVICE_DISCONNECTED; if(ticks.timeSince(lastRequestTime) > 5){ // if last request is longer than 5 seconds ago, request again and delay sensor->requestTemperatures(); lastRequestTime = ticks.seconds(); waitForConversion(); } fixed7_9 temperature = sensor->getTempRaw(sensorAddress); if(temperature == DEVICE_DISCONNECTED){ setConnected(false); return DEVICE_DISCONNECTED; } // sensor returns 12 bits with 4 fraction bits. Store with 9 fraction bits and add the offset for storage temperature = constrainTemp(temperature+calibrationOffset+(C_OFFSET>>5), ((int) INT_MIN)>>5, ((int) INT_MAX)>>5)<<5; // already send request for next read sensor->requestTemperatures(); lastRequestTime = ticks.seconds(); return temperature; } <|endoftext|>
<commit_before>/***************************************************************************** * Messages.cpp : Information about an item **************************************************************************** * Copyright (C) 2006-2007 the VideoLAN team * $Id$ * * Authors: Jean-Baptiste Kempf <jb (at) videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "dialogs/messages.hpp" #include <QSpinBox> #include <QLabel> #include <QTextEdit> #include <QTextCursor> #include <QFileDialog> #include <QTextStream> #include <QMessageBox> #include <QTabWidget> #include <QTreeWidget> #include <QTreeWidgetItem> #include <QHeaderView> #include <QMutex> #include <assert.h> MessagesDialog *MessagesDialog::instance = NULL; enum { MsgEvent_Type = QEvent::User + MsgEventType + 1, }; class MsgEvent : public QEvent { public: MsgEvent( msg_item_t *msg ) : QEvent( (QEvent::Type)MsgEvent_Type ), msg(msg) { msg_Hold( msg ); } virtual ~MsgEvent() { msg_Release( msg ); } msg_item_t *msg; }; struct msg_cb_data_t { MessagesDialog *self; }; static void MsgCallback( msg_cb_data_t *, msg_item_t *, unsigned ); MessagesDialog::MessagesDialog( intf_thread_t *_p_intf) : QVLCFrame( _p_intf ) { setWindowTitle( qtr( "Messages" ) ); /* General widgets */ QGridLayout *mainLayout = new QGridLayout( this ); mainTab = new QTabWidget( this ); mainTab->setTabPosition( QTabWidget::North ); /* Messages */ QWidget *msgWidget = new QWidget; QGridLayout *msgLayout = new QGridLayout( msgWidget ); messages = new QTextEdit(); messages->setReadOnly( true ); messages->setGeometry( 0, 0, 440, 600 ); messages->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); messages->setTextInteractionFlags( Qt::TextSelectableByMouse ); msgLayout->addWidget( messages, 0, 0, 1, 0 ); mainTab->addTab( msgWidget, qtr( "Messages" ) ); /* Modules tree */ QWidget *treeWidget = new QWidget; QGridLayout *treeLayout = new QGridLayout( treeWidget ); modulesTree = new QTreeWidget(); modulesTree->header()->hide(); treeLayout->addWidget( modulesTree, 0, 0, 1, 0 ); mainTab->addTab( treeWidget, qtr( "Modules tree" ) ); /* Buttons and general layout */ QPushButton *closeButton = new QPushButton( qtr( "&Close" ) ); closeButton->setDefault( true ); clearUpdateButton = new QPushButton( qtr( "C&lear" ) ); saveLogButton = new QPushButton( qtr( "&Save as..." ) ); saveLogButton->setToolTip( qtr( "Saves all the displayed logs to a file" ) ); verbosityBox = new QSpinBox(); verbosityBox->setRange( 0, 2 ); verbosityBox->setValue( config_GetInt( p_intf, "verbose" ) ); verbosityBox->setWrapping( true ); verbosityBox->setMaximumWidth( 50 ); verbosityLabel = new QLabel( qtr( "Verbosity Level" ) ); mainLayout->addWidget( mainTab, 0, 0, 1, 0 ); mainLayout->addWidget( verbosityLabel, 1, 0, 1, 1 ); mainLayout->addWidget( verbosityBox, 1, 1 ); mainLayout->setColumnStretch( 2, 10 ); mainLayout->addWidget( saveLogButton, 1, 3 ); mainLayout->addWidget( clearUpdateButton, 1, 4 ); mainLayout->addWidget( closeButton, 1, 5 ); BUTTONACT( closeButton, hide() ); BUTTONACT( clearUpdateButton, clearOrUpdate() ); BUTTONACT( saveLogButton, save() ); CONNECT( mainTab, currentChanged( int ), this, updateTab( int ) ); /* General action */ readSettings( "Messages", QSize( 600, 450 ) ); /* Hook up to LibVLC messaging */ cbData = new msg_cb_data_t; cbData->self = this; sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, cbData ); } MessagesDialog::~MessagesDialog() { writeSettings( "Messages" ); msg_Unsubscribe( sub ); delete cbData; }; void MessagesDialog::updateTab( int index ) { /* Second tab : modules tree */ if( index == 1 ) { verbosityLabel->hide(); verbosityBox->hide(); clearUpdateButton->setText( qtr( "&Update" ) ); saveLogButton->hide(); updateTree(); } /* First tab : messages */ else { verbosityLabel->show(); verbosityBox->show(); clearUpdateButton->setText( qtr( "&Clear" ) ); saveLogButton->show(); } } void MessagesDialog::sinkMessage( msg_item_t *item ) { if ((item->i_type == VLC_MSG_WARN && verbosityBox->value() < 1) || (item->i_type == VLC_MSG_DBG && verbosityBox->value() < 2 )) return; /* Copy selected text to the clipboard */ if( messages->textCursor().hasSelection() ) messages->copy(); /* Fix selected text bug */ if( !messages->textCursor().atEnd() || messages->textCursor().anchor() != messages->textCursor().position() ) messages->moveCursor( QTextCursor::End ); messages->setFontItalic( true ); messages->setTextColor( "darkBlue" ); messages->insertPlainText( qfu( item->psz_module ) ); switch (item->i_type) { case VLC_MSG_INFO: messages->setTextColor( "blue" ); messages->insertPlainText( " info: " ); break; case VLC_MSG_ERR: messages->setTextColor( "red" ); messages->insertPlainText( " error: " ); break; case VLC_MSG_WARN: messages->setTextColor( "green" ); messages->insertPlainText( " warning: " ); break; case VLC_MSG_DBG: default: messages->setTextColor( "grey" ); messages->insertPlainText( " debug: " ); break; } /* Add message Regular black Font */ messages->setFontItalic( false ); messages->setTextColor( "black" ); messages->insertPlainText( qfu(item->psz_msg) ); messages->insertPlainText( "\n" ); } void MessagesDialog::customEvent( QEvent *event ) { MsgEvent *msge = static_cast<MsgEvent *>(event); assert( msge ); sinkMessage( msge->msg ); } void MessagesDialog::clearOrUpdate() { if( mainTab->currentIndex() ) updateTree(); else clear(); } void MessagesDialog::clear() { messages->clear(); } bool MessagesDialog::save() { QString saveLogFileName = QFileDialog::getSaveFileName( this, qtr( "Save log file as..." ), qfu( config_GetHomeDir() ), qtr( "Texts / Logs (*.log *.txt);; All (*.*) ") ); if( !saveLogFileName.isNull() ) { QFile file( saveLogFileName ); if ( !file.open( QFile::WriteOnly | QFile::Text ) ) { QMessageBox::warning( this, qtr( "Application" ), qtr( "Cannot write to file %1:\n%2." ) .arg( saveLogFileName ) .arg( file.errorString() ) ); return false; } QTextStream out( &file ); out << messages->toPlainText() << "\n"; return true; } return false; } void MessagesDialog::buildTree( QTreeWidgetItem *parentItem, vlc_object_t *p_obj ) { QTreeWidgetItem *item; if( parentItem ) item = new QTreeWidgetItem( parentItem ); else item = new QTreeWidgetItem( modulesTree ); if( p_obj->psz_object_name ) item->setText( 0, qfu( p_obj->psz_object_type ) + " \"" + qfu( p_obj->psz_object_name ) + "\" (" + QString::number((uintptr_t)p_obj) + ")" ); else item->setText( 0, qfu( p_obj->psz_object_type ) + " (" + QString::number((uintptr_t)p_obj) + ")" ); item->setExpanded( true ); vlc_list_t *l = vlc_list_children( p_obj ); for( int i=0; i < l->i_count; i++ ) buildTree( item, l->p_values[i].p_object ); vlc_list_release( l ); } void MessagesDialog::updateTree() { modulesTree->clear(); buildTree( NULL, VLC_OBJECT( p_intf->p_libvlc ) ); } static void MsgCallback( msg_cb_data_t *data, msg_item_t *item, unsigned ) { int canc = vlc_savecancel(); QApplication::postEvent( data->self, new MsgEvent( item ) ); vlc_restorecancel( canc ); } <commit_msg>Qt: put the ensureCursorVisible(); back.<commit_after>/***************************************************************************** * Messages.cpp : Information about an item **************************************************************************** * Copyright (C) 2006-2007 the VideoLAN team * $Id$ * * Authors: Jean-Baptiste Kempf <jb (at) videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "dialogs/messages.hpp" #include <QSpinBox> #include <QLabel> #include <QTextEdit> #include <QTextCursor> #include <QFileDialog> #include <QTextStream> #include <QMessageBox> #include <QTabWidget> #include <QTreeWidget> #include <QTreeWidgetItem> #include <QHeaderView> #include <QMutex> #include <assert.h> MessagesDialog *MessagesDialog::instance = NULL; enum { MsgEvent_Type = QEvent::User + MsgEventType + 1, }; class MsgEvent : public QEvent { public: MsgEvent( msg_item_t *msg ) : QEvent( (QEvent::Type)MsgEvent_Type ), msg(msg) { msg_Hold( msg ); } virtual ~MsgEvent() { msg_Release( msg ); } msg_item_t *msg; }; struct msg_cb_data_t { MessagesDialog *self; }; static void MsgCallback( msg_cb_data_t *, msg_item_t *, unsigned ); MessagesDialog::MessagesDialog( intf_thread_t *_p_intf) : QVLCFrame( _p_intf ) { setWindowTitle( qtr( "Messages" ) ); /* General widgets */ QGridLayout *mainLayout = new QGridLayout( this ); mainTab = new QTabWidget( this ); mainTab->setTabPosition( QTabWidget::North ); /* Messages */ QWidget *msgWidget = new QWidget; QGridLayout *msgLayout = new QGridLayout( msgWidget ); messages = new QTextEdit(); messages->setReadOnly( true ); messages->setGeometry( 0, 0, 440, 600 ); messages->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); messages->setTextInteractionFlags( Qt::TextSelectableByMouse ); msgLayout->addWidget( messages, 0, 0, 1, 0 ); mainTab->addTab( msgWidget, qtr( "Messages" ) ); /* Modules tree */ QWidget *treeWidget = new QWidget; QGridLayout *treeLayout = new QGridLayout( treeWidget ); modulesTree = new QTreeWidget(); modulesTree->header()->hide(); treeLayout->addWidget( modulesTree, 0, 0, 1, 0 ); mainTab->addTab( treeWidget, qtr( "Modules tree" ) ); /* Buttons and general layout */ QPushButton *closeButton = new QPushButton( qtr( "&Close" ) ); closeButton->setDefault( true ); clearUpdateButton = new QPushButton( qtr( "C&lear" ) ); saveLogButton = new QPushButton( qtr( "&Save as..." ) ); saveLogButton->setToolTip( qtr( "Saves all the displayed logs to a file" ) ); verbosityBox = new QSpinBox(); verbosityBox->setRange( 0, 2 ); verbosityBox->setValue( config_GetInt( p_intf, "verbose" ) ); verbosityBox->setWrapping( true ); verbosityBox->setMaximumWidth( 50 ); verbosityLabel = new QLabel( qtr( "Verbosity Level" ) ); mainLayout->addWidget( mainTab, 0, 0, 1, 0 ); mainLayout->addWidget( verbosityLabel, 1, 0, 1, 1 ); mainLayout->addWidget( verbosityBox, 1, 1 ); mainLayout->setColumnStretch( 2, 10 ); mainLayout->addWidget( saveLogButton, 1, 3 ); mainLayout->addWidget( clearUpdateButton, 1, 4 ); mainLayout->addWidget( closeButton, 1, 5 ); BUTTONACT( closeButton, hide() ); BUTTONACT( clearUpdateButton, clearOrUpdate() ); BUTTONACT( saveLogButton, save() ); CONNECT( mainTab, currentChanged( int ), this, updateTab( int ) ); /* General action */ readSettings( "Messages", QSize( 600, 450 ) ); /* Hook up to LibVLC messaging */ cbData = new msg_cb_data_t; cbData->self = this; sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, cbData ); } MessagesDialog::~MessagesDialog() { writeSettings( "Messages" ); msg_Unsubscribe( sub ); delete cbData; }; void MessagesDialog::updateTab( int index ) { /* Second tab : modules tree */ if( index == 1 ) { verbosityLabel->hide(); verbosityBox->hide(); clearUpdateButton->setText( qtr( "&Update" ) ); saveLogButton->hide(); updateTree(); } /* First tab : messages */ else { verbosityLabel->show(); verbosityBox->show(); clearUpdateButton->setText( qtr( "&Clear" ) ); saveLogButton->show(); } } void MessagesDialog::sinkMessage( msg_item_t *item ) { if ((item->i_type == VLC_MSG_WARN && verbosityBox->value() < 1) || (item->i_type == VLC_MSG_DBG && verbosityBox->value() < 2 )) return; /* Copy selected text to the clipboard */ if( messages->textCursor().hasSelection() ) messages->copy(); /* Fix selected text bug */ if( !messages->textCursor().atEnd() || messages->textCursor().anchor() != messages->textCursor().position() ) messages->moveCursor( QTextCursor::End ); messages->setFontItalic( true ); messages->setTextColor( "darkBlue" ); messages->insertPlainText( qfu( item->psz_module ) ); switch (item->i_type) { case VLC_MSG_INFO: messages->setTextColor( "blue" ); messages->insertPlainText( " info: " ); break; case VLC_MSG_ERR: messages->setTextColor( "red" ); messages->insertPlainText( " error: " ); break; case VLC_MSG_WARN: messages->setTextColor( "green" ); messages->insertPlainText( " warning: " ); break; case VLC_MSG_DBG: default: messages->setTextColor( "grey" ); messages->insertPlainText( " debug: " ); break; } /* Add message Regular black Font */ messages->setFontItalic( false ); messages->setTextColor( "black" ); messages->insertPlainText( qfu(item->psz_msg) ); messages->insertPlainText( "\n" ); messages->ensureCursorVisible(); } void MessagesDialog::customEvent( QEvent *event ) { MsgEvent *msge = static_cast<MsgEvent *>(event); assert( msge ); sinkMessage( msge->msg ); } void MessagesDialog::clearOrUpdate() { if( mainTab->currentIndex() ) updateTree(); else clear(); } void MessagesDialog::clear() { messages->clear(); } bool MessagesDialog::save() { QString saveLogFileName = QFileDialog::getSaveFileName( this, qtr( "Save log file as..." ), qfu( config_GetHomeDir() ), qtr( "Texts / Logs (*.log *.txt);; All (*.*) ") ); if( !saveLogFileName.isNull() ) { QFile file( saveLogFileName ); if ( !file.open( QFile::WriteOnly | QFile::Text ) ) { QMessageBox::warning( this, qtr( "Application" ), qtr( "Cannot write to file %1:\n%2." ) .arg( saveLogFileName ) .arg( file.errorString() ) ); return false; } QTextStream out( &file ); out << messages->toPlainText() << "\n"; return true; } return false; } void MessagesDialog::buildTree( QTreeWidgetItem *parentItem, vlc_object_t *p_obj ) { QTreeWidgetItem *item; if( parentItem ) item = new QTreeWidgetItem( parentItem ); else item = new QTreeWidgetItem( modulesTree ); if( p_obj->psz_object_name ) item->setText( 0, qfu( p_obj->psz_object_type ) + " \"" + qfu( p_obj->psz_object_name ) + "\" (" + QString::number((uintptr_t)p_obj) + ")" ); else item->setText( 0, qfu( p_obj->psz_object_type ) + " (" + QString::number((uintptr_t)p_obj) + ")" ); item->setExpanded( true ); vlc_list_t *l = vlc_list_children( p_obj ); for( int i=0; i < l->i_count; i++ ) buildTree( item, l->p_values[i].p_object ); vlc_list_release( l ); } void MessagesDialog::updateTree() { modulesTree->clear(); buildTree( NULL, VLC_OBJECT( p_intf->p_libvlc ) ); } static void MsgCallback( msg_cb_data_t *data, msg_item_t *item, unsigned ) { int canc = vlc_savecancel(); QApplication::postEvent( data->self, new MsgEvent( item ) ); vlc_restorecancel( canc ); } <|endoftext|>
<commit_before> #include "PolycodeWindowsPlayer.h" #include <Polycode.h> #include "PolycodeView.h" #include "windows.h" #include "resource.h" #define STANDALONE_MODE using namespace Polycode; extern Win32Core *core; void wtoc(char* Dest, TCHAR* Source, int SourceSize) { for(int i = 0; i < SourceSize; ++i) Dest[i] = (char)Source[i]; } int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int nArgs; LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); String fileName = ""; if(nArgs > 1) { fileName = String(szArglist[1]); } fileName = fileName.replace("\\", "/"); PolycodeView *view = new PolycodeView(hInstance, nCmdShow, L"Polycode Player", false, false); PolycodeWindowsPlayer *player = new PolycodeWindowsPlayer(view, fileName.c_str(), false, true); HICON mainIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); SendMessage(view->hwnd, WM_SETICON, ICON_SMALL, (LPARAM) mainIcon ); // player->addEventListener(view, PolycodeDebugEvent::EVENT_ERROR); // player->addEventListener(view, PolycodeDebugEvent::EVENT_PRINT); player->runPlayer(); core = (Win32Core*)player->getCore(); MSG Msg; do { if(PeekMessage(&Msg, NULL, 0,0,PM_REMOVE)) { TranslateMessage(&Msg); DispatchMessage(&Msg); } } while(player->Update()); return Msg.wParam; } <commit_msg>Disconnect debugger in Windows player on quit<commit_after> #include "PolycodeWindowsPlayer.h" #include <Polycode.h> #include "PolycodeView.h" #include "windows.h" #include "resource.h" #define STANDALONE_MODE using namespace Polycode; extern Win32Core *core; void wtoc(char* Dest, TCHAR* Source, int SourceSize) { for(int i = 0; i < SourceSize; ++i) Dest[i] = (char)Source[i]; } int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int nArgs; LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); String fileName = ""; if(nArgs > 1) { fileName = String(szArglist[1]); } fileName = fileName.replace("\\", "/"); PolycodeView *view = new PolycodeView(hInstance, nCmdShow, L"Polycode Player", false, false); PolycodeWindowsPlayer *player = new PolycodeWindowsPlayer(view, fileName.c_str(), false, true); HICON mainIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); SendMessage(view->hwnd, WM_SETICON, ICON_SMALL, (LPARAM) mainIcon ); // player->addEventListener(view, PolycodeDebugEvent::EVENT_ERROR); // player->addEventListener(view, PolycodeDebugEvent::EVENT_PRINT); player->runPlayer(); core = (Win32Core*)player->getCore(); MSG Msg; do { if(PeekMessage(&Msg, NULL, 0,0,PM_REMOVE)) { TranslateMessage(&Msg); DispatchMessage(&Msg); } } while(player->Update()); delete player; return Msg.wParam; } <|endoftext|>
<commit_before>/***************************************************************************** * playtree.cpp ***************************************************************************** * Copyright (C) 2005 the VideoLAN team * $Id$ * * Authors: Antoine Cellerier <dionoea@videolan.org> * Clément Stenac <zorglub@videolan.org> * Erwan Tulou <erwan10@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include "playtree.hpp" #include <vlc_playlist.h> #include <vlc_url.h> #include "../utils/ustring.hpp" Playtree::Playtree( intf_thread_t *pIntf ) : VarTree( pIntf ), m_pPlaylist( pIntf->p_sys->p_playlist ) { getPositionVar().addObserver( this ); buildTree(); } Playtree::~Playtree() { getPositionVar().delObserver( this ); } void Playtree::delSelected() { for( Iterator it = m_children.begin(); it != m_children.end(); ) { if( it->isSelected() && !it->isReadonly() ) { playlist_Lock( m_pPlaylist ); playlist_item_t *pItem = playlist_ItemGetById( m_pPlaylist, it->getId() ); if( pItem ) { if( pItem->i_children == -1 ) { playlist_DeleteFromInput( m_pPlaylist, pItem->p_input, pl_Locked ); } else { playlist_NodeDelete( m_pPlaylist, pItem, true, false ); } } playlist_Unlock( m_pPlaylist ); it = it->getNextSiblingOrUncle(); } else { it = getNextItem( it ); } } } void Playtree::action( VarTree *pElem ) { playlist_Lock( m_pPlaylist ); playlist_item_t *pItem = playlist_ItemGetById( m_pPlaylist, pElem->getId() ); if( pItem ) { playlist_Control( m_pPlaylist, PLAYLIST_VIEWPLAY, pl_Locked, pItem->p_parent, pItem ); } playlist_Unlock( m_pPlaylist ); } void Playtree::onChange() { buildTree(); tree_update descr( tree_update::ResetAll, end() ); notify( &descr ); } void Playtree::onUpdateItem( int id ) { Iterator it = findById( id ); if( it != m_children.end() ) { // Update the item playlist_Lock( m_pPlaylist ); playlist_item_t *pNode = playlist_ItemGetById( m_pPlaylist, it->getId() ); if( !pNode ) { playlist_Unlock( m_pPlaylist ); return; } UString *pName = getTitle( pNode->p_input ); playlist_Unlock( m_pPlaylist ); if( *pName != *(it->getString()) ) { it->setString( UStringPtr( pName ) ); tree_update descr( tree_update::ItemUpdated, IteratorVisible( it, this ) ); notify( &descr ); } else { delete pName; } } else { msg_Warn( getIntf(), "cannot find node with id %d", id ); } } void Playtree::onUpdateCurrent( bool b_active ) { if( b_active ) { playlist_Lock( m_pPlaylist ); playlist_item_t* current = playlist_CurrentPlayingItem( m_pPlaylist ); if( !current ) { playlist_Unlock( m_pPlaylist ); return; } Iterator it = findById( current->i_id ); if( it != m_children.end() ) { it->setPlaying( true ); tree_update descr( tree_update::ItemUpdated, IteratorVisible( it, this ) ); notify( &descr ); } playlist_Unlock( m_pPlaylist ); } else { for( Iterator it = m_children.begin(); it != m_children.end(); it = getNextItem( it ) ) { if( it->isPlaying() ) { it->setPlaying( false ); tree_update descr( tree_update::ItemUpdated, IteratorVisible( it, this ) ); notify( &descr ); break; } } } } void Playtree::onDelete( int i_id ) { Iterator it = findById( i_id ) ; if( it != m_children.end() ) { VarTree* parent = it->parent(); if( parent ) { tree_update descr( tree_update::DeletingItem, IteratorVisible( it, this ) ); notify( &descr ); parent->removeChild( it ); m_allItems.erase( i_id ); tree_update descr2( tree_update::ItemDeleted, end() ); notify( &descr2 ); } } } void Playtree::onAppend( playlist_add_t *p_add ) { Iterator it_node = findById( p_add->i_node ); if( it_node != m_children.end() ) { playlist_Lock( m_pPlaylist ); playlist_item_t *pItem = playlist_ItemGetById( m_pPlaylist, p_add->i_item ); if( !pItem ) { playlist_Unlock( m_pPlaylist ); return; } int pos; for( pos = 0; pos < pItem->p_parent->i_children; pos++ ) if( pItem->p_parent->pp_children[pos] == pItem ) break; UString *pName = getTitle( pItem->p_input ); playlist_item_t* current = playlist_CurrentPlayingItem( m_pPlaylist ); Iterator it = it_node->add( p_add->i_item, UStringPtr( pName ), false, pItem == current, false, pItem->i_flags & PLAYLIST_RO_FLAG, pos ); m_allItems[pItem->i_id] = &*it; playlist_Unlock( m_pPlaylist ); tree_update descr( tree_update::ItemInserted, IteratorVisible( it, this ) ); notify( &descr ); } } void Playtree::buildNode( playlist_item_t *pNode, VarTree &rTree ) { UString *pName = getTitle( pNode->p_input ); Iterator it = rTree.add( pNode->i_id, UStringPtr( pName ), false, playlist_CurrentPlayingItem(m_pPlaylist) == pNode, false, pNode->i_flags & PLAYLIST_RO_FLAG ); m_allItems[pNode->i_id] = &*it; for( int i = 0; i < pNode->i_children; i++ ) { buildNode( pNode->pp_children[i], *it ); } } void Playtree::buildTree() { clear(); playlist_Lock( m_pPlaylist ); for( int i = 0; i < m_pPlaylist->p_root->i_children; i++ ) { buildNode( m_pPlaylist->p_root->pp_children[i], *this ); } playlist_Unlock( m_pPlaylist ); } void Playtree::onUpdateSlider() { tree_update descr( tree_update::SliderChanged, end() ); notify( &descr ); } void Playtree::insertItems( VarTree& elem, const list<string>& files, bool start ) { bool first = true; VarTree* p_elem = &elem; playlist_item_t* p_node = NULL; int i_pos = -1; playlist_Lock( m_pPlaylist ); if( p_elem == this ) { for( Iterator it = m_children.begin(); it != m_children.end(); ++it ) { if( it->getId() == m_pPlaylist->p_local_category->i_id ) { p_elem = &*it; break; } } } if( p_elem->getId() == m_pPlaylist->p_local_category->i_id ) { p_node = m_pPlaylist->p_local_category; i_pos = 0; p_elem->setExpanded( true ); } else if( p_elem->getId() == m_pPlaylist->p_ml_category->i_id ) { p_node = m_pPlaylist->p_ml_category; i_pos = 0; p_elem->setExpanded( true ); } else if( p_elem->size() && p_elem->isExpanded() ) { p_node = playlist_ItemGetById( m_pPlaylist, p_elem->getId() ); i_pos = 0; } else { p_node = playlist_ItemGetById( m_pPlaylist, p_elem->parent()->getId() ); i_pos = p_elem->getIndex(); i_pos++; } if( !p_node ) goto fin; for( list<string>::const_iterator it = files.begin(); it != files.end(); ++it, i_pos++, first = false ) { input_item_t *pItem; if( strstr( it->c_str(), "://" ) ) pItem = input_item_New( it->c_str(), NULL ); else { char *psz_uri = vlc_path2uri( it->c_str(), NULL ); if( psz_uri == NULL ) continue; pItem = input_item_New( psz_uri, NULL ); free( psz_uri ); } if( pItem == NULL) continue; int i_mode = PLAYLIST_APPEND; if( first && start ) i_mode |= PLAYLIST_GO; playlist_NodeAddInput( m_pPlaylist, pItem, p_node, i_mode, i_pos, pl_Locked ); } fin: playlist_Unlock( m_pPlaylist ); } UString* Playtree::getTitle( input_item_t *pItem ) { char *psz_name = input_item_GetTitle( pItem ); if( EMPTY_STR( psz_name ) ) { free( psz_name ); psz_name = input_item_GetName( pItem ); } if( !psz_name ) psz_name = strdup ( "" ); UString *pTitle = new UString( getIntf(), psz_name ); free( psz_name ); return pTitle; } VarTree::Iterator Playtree::findById( int id ) { map<int,VarTree*>::iterator it = m_allItems.find( id ); if( it == m_allItems.end() ) return m_children.end(); else return it->second->getSelf(); } <commit_msg>skins2: simplify playlist title<commit_after>/***************************************************************************** * playtree.cpp ***************************************************************************** * Copyright (C) 2005 the VideoLAN team * $Id$ * * Authors: Antoine Cellerier <dionoea@videolan.org> * Clément Stenac <zorglub@videolan.org> * Erwan Tulou <erwan10@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include "playtree.hpp" #include <vlc_playlist.h> #include <vlc_url.h> #include "../utils/ustring.hpp" Playtree::Playtree( intf_thread_t *pIntf ) : VarTree( pIntf ), m_pPlaylist( pIntf->p_sys->p_playlist ) { getPositionVar().addObserver( this ); buildTree(); } Playtree::~Playtree() { getPositionVar().delObserver( this ); } void Playtree::delSelected() { for( Iterator it = m_children.begin(); it != m_children.end(); ) { if( it->isSelected() && !it->isReadonly() ) { playlist_Lock( m_pPlaylist ); playlist_item_t *pItem = playlist_ItemGetById( m_pPlaylist, it->getId() ); if( pItem ) { if( pItem->i_children == -1 ) { playlist_DeleteFromInput( m_pPlaylist, pItem->p_input, pl_Locked ); } else { playlist_NodeDelete( m_pPlaylist, pItem, true, false ); } } playlist_Unlock( m_pPlaylist ); it = it->getNextSiblingOrUncle(); } else { it = getNextItem( it ); } } } void Playtree::action( VarTree *pElem ) { playlist_Lock( m_pPlaylist ); playlist_item_t *pItem = playlist_ItemGetById( m_pPlaylist, pElem->getId() ); if( pItem ) { playlist_Control( m_pPlaylist, PLAYLIST_VIEWPLAY, pl_Locked, pItem->p_parent, pItem ); } playlist_Unlock( m_pPlaylist ); } void Playtree::onChange() { buildTree(); tree_update descr( tree_update::ResetAll, end() ); notify( &descr ); } void Playtree::onUpdateItem( int id ) { Iterator it = findById( id ); if( it != m_children.end() ) { // Update the item playlist_Lock( m_pPlaylist ); playlist_item_t *pNode = playlist_ItemGetById( m_pPlaylist, it->getId() ); if( !pNode ) { playlist_Unlock( m_pPlaylist ); return; } UString *pName = getTitle( pNode->p_input ); playlist_Unlock( m_pPlaylist ); if( *pName != *(it->getString()) ) { it->setString( UStringPtr( pName ) ); tree_update descr( tree_update::ItemUpdated, IteratorVisible( it, this ) ); notify( &descr ); } else { delete pName; } } else { msg_Warn( getIntf(), "cannot find node with id %d", id ); } } void Playtree::onUpdateCurrent( bool b_active ) { if( b_active ) { playlist_Lock( m_pPlaylist ); playlist_item_t* current = playlist_CurrentPlayingItem( m_pPlaylist ); if( !current ) { playlist_Unlock( m_pPlaylist ); return; } Iterator it = findById( current->i_id ); if( it != m_children.end() ) { it->setPlaying( true ); tree_update descr( tree_update::ItemUpdated, IteratorVisible( it, this ) ); notify( &descr ); } playlist_Unlock( m_pPlaylist ); } else { for( Iterator it = m_children.begin(); it != m_children.end(); it = getNextItem( it ) ) { if( it->isPlaying() ) { it->setPlaying( false ); tree_update descr( tree_update::ItemUpdated, IteratorVisible( it, this ) ); notify( &descr ); break; } } } } void Playtree::onDelete( int i_id ) { Iterator it = findById( i_id ) ; if( it != m_children.end() ) { VarTree* parent = it->parent(); if( parent ) { tree_update descr( tree_update::DeletingItem, IteratorVisible( it, this ) ); notify( &descr ); parent->removeChild( it ); m_allItems.erase( i_id ); tree_update descr2( tree_update::ItemDeleted, end() ); notify( &descr2 ); } } } void Playtree::onAppend( playlist_add_t *p_add ) { Iterator it_node = findById( p_add->i_node ); if( it_node != m_children.end() ) { playlist_Lock( m_pPlaylist ); playlist_item_t *pItem = playlist_ItemGetById( m_pPlaylist, p_add->i_item ); if( !pItem ) { playlist_Unlock( m_pPlaylist ); return; } int pos; for( pos = 0; pos < pItem->p_parent->i_children; pos++ ) if( pItem->p_parent->pp_children[pos] == pItem ) break; UString *pName = getTitle( pItem->p_input ); playlist_item_t* current = playlist_CurrentPlayingItem( m_pPlaylist ); Iterator it = it_node->add( p_add->i_item, UStringPtr( pName ), false, pItem == current, false, pItem->i_flags & PLAYLIST_RO_FLAG, pos ); m_allItems[pItem->i_id] = &*it; playlist_Unlock( m_pPlaylist ); tree_update descr( tree_update::ItemInserted, IteratorVisible( it, this ) ); notify( &descr ); } } void Playtree::buildNode( playlist_item_t *pNode, VarTree &rTree ) { UString *pName = getTitle( pNode->p_input ); Iterator it = rTree.add( pNode->i_id, UStringPtr( pName ), false, playlist_CurrentPlayingItem(m_pPlaylist) == pNode, false, pNode->i_flags & PLAYLIST_RO_FLAG ); m_allItems[pNode->i_id] = &*it; for( int i = 0; i < pNode->i_children; i++ ) { buildNode( pNode->pp_children[i], *it ); } } void Playtree::buildTree() { clear(); playlist_Lock( m_pPlaylist ); for( int i = 0; i < m_pPlaylist->p_root->i_children; i++ ) { buildNode( m_pPlaylist->p_root->pp_children[i], *this ); } playlist_Unlock( m_pPlaylist ); } void Playtree::onUpdateSlider() { tree_update descr( tree_update::SliderChanged, end() ); notify( &descr ); } void Playtree::insertItems( VarTree& elem, const list<string>& files, bool start ) { bool first = true; VarTree* p_elem = &elem; playlist_item_t* p_node = NULL; int i_pos = -1; playlist_Lock( m_pPlaylist ); if( p_elem == this ) { for( Iterator it = m_children.begin(); it != m_children.end(); ++it ) { if( it->getId() == m_pPlaylist->p_local_category->i_id ) { p_elem = &*it; break; } } } if( p_elem->getId() == m_pPlaylist->p_local_category->i_id ) { p_node = m_pPlaylist->p_local_category; i_pos = 0; p_elem->setExpanded( true ); } else if( p_elem->getId() == m_pPlaylist->p_ml_category->i_id ) { p_node = m_pPlaylist->p_ml_category; i_pos = 0; p_elem->setExpanded( true ); } else if( p_elem->size() && p_elem->isExpanded() ) { p_node = playlist_ItemGetById( m_pPlaylist, p_elem->getId() ); i_pos = 0; } else { p_node = playlist_ItemGetById( m_pPlaylist, p_elem->parent()->getId() ); i_pos = p_elem->getIndex(); i_pos++; } if( !p_node ) goto fin; for( list<string>::const_iterator it = files.begin(); it != files.end(); ++it, i_pos++, first = false ) { input_item_t *pItem; if( strstr( it->c_str(), "://" ) ) pItem = input_item_New( it->c_str(), NULL ); else { char *psz_uri = vlc_path2uri( it->c_str(), NULL ); if( psz_uri == NULL ) continue; pItem = input_item_New( psz_uri, NULL ); free( psz_uri ); } if( pItem == NULL) continue; int i_mode = PLAYLIST_APPEND; if( first && start ) i_mode |= PLAYLIST_GO; playlist_NodeAddInput( m_pPlaylist, pItem, p_node, i_mode, i_pos, pl_Locked ); } fin: playlist_Unlock( m_pPlaylist ); } UString* Playtree::getTitle( input_item_t *pItem ) { char *psz_name = input_item_GetTitleFbName( pItem ); UString *pTitle = new UString( getIntf(), psz_name ); free( psz_name ); return pTitle; } VarTree::Iterator Playtree::findById( int id ) { map<int,VarTree*>::iterator it = m_allItems.find( id ); if( it == m_allItems.end() ) return m_children.end(); else return it->second->getSelf(); } <|endoftext|>
<commit_before>/* compute the Restricted Voronoi Diagram in CPU */ //RVD computing part #include "Command_line.h" #include "Mesh_io.h" #include "Mesh.h" #include "Points.h" #include "Mesh_repair.h" // Cuda part #include "CudaHelper.h" #include <time.h> // Renderring part #include "Glut_generator.h" #include "DrawGraphics.h" //kdtree #include "Kdtree.h" #include "CUDA_KDtree.h" // in/out put #include <iostream> #include <fstream> #include <iomanip> #include "RVD.h" #define WINDOWS_WIDTH 1000 #define WINDOWS_HEIGHT 800 using namespace P_RVD; #define KNN GraphicsDrawer* m_GraphicsDrawer = new GraphicsDrawer(); Points p_in, p_out; Mesh M_in; /* call the cuda function pass the data to the device this without knn */ extern "C" void runCuda(double* host_seeds_pointer, double* host_mesh_vertex_pointer, int* host_facet_index, int points_nb, int mesh_vertex_nb, int mesh_facet_number); /* call this cuda function after you've got the nearest neighbors */ extern "C" void runRVD(double* host_seeds_pointer, double* host_mesh_vertex_pointer, int* host_facet_index, int points_nb, int mesh_vertex_nb, int mesh_facet_nb, std::vector<int> facet_center_neigbors, std::vector<int> seeds_neighbors, std::vector<int>& seeds_polygon_nb); /* call the knn cuda */ extern "C" void runKnnCuda(Points r, Points queries, std::vector<int> indexes); /* renderring part */ void RenderCB(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(0.1f, 0.1f, 0.2f, 0.0f); glDisable(GL_COLOR_MATERIAL); glDisable(GL_LIGHTING); glColor3f(1.0f, 0.0f, 0.0f); m_GraphicsDrawer->DrawPoints(p_in); glColor3f(0.0f, 1.0f, 0.0f); m_GraphicsDrawer->DrawPoints(p_out); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glColor3f(0.8f, 0.8f, 0.8f); glPolygonMode(GL_FRONT, GL_LINE); m_GraphicsDrawer->DrawMesh(M_in); glFlush(); glutSwapBuffers(); glutPostRedisplay(); } void myResize(int width, int height) { //get the viewport of GLUI and then set the viewport back to that after the resize glViewport(0, 0, width, height);//viewportڴ趨һӽǵĴСһڻΪӽ glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluPerspective(60.0, (float)width / height, 0.5f, 20.0f);//趨ӽ glPopMatrix(); gluLookAt(1.0f, 0.0f, 0.0f, 0.0f, 0.f, 0.0f, 0.0f, 1.0f, 0.0f); glClearColor((GLclampf)1 / 255, (GLclampf)1 / 255, (GLclampf)1 / 255, 0.0);//ˢɻɫ glEnable(GL_DEPTH_TEST); } int main(int argc, char** argv) { std::vector<std::string> filenames; if (!Cmd::parse_argu(argc, argv, filenames)) { fprintf(stderr, "cannot parse the argument into filenames!"); return -1; } std::string mesh_filename = filenames[0]; std::string points_filename = filenames[0]; std::string output_filename; if (filenames.size() >= 2) { points_filename = filenames[1]; } output_filename = (filenames.size() == 3) ? filenames[2] : "out.eobj"; Mesh M_out, points_in; FileType mesh_type = OBJfile; if (!mesh_load(mesh_filename, M_in)) { fprintf(stderr, "cannot load Mesh into M_in!"); return -1; } if (!mesh_load(points_filename, points_in, false)) { fprintf(stderr, "cannot load points into points_in!"); return -1; } mesh_repair(M_in); Points points(points_in); Points points_out(points_in); /* trans the data from host to device */ double* host_points = NULL; trans_points(points, host_points); //-------end test---------- double* host_mesh_vertex = NULL; int* host_facet_index = NULL; trans_mesh(M_in, host_mesh_vertex, host_facet_index); std::vector<int> seeds_polygon_nb; #ifdef KNN /* Kdtree Create the tree */ KDtree tree; CUDA_KDTree GPU_tree; const int maxTreeLevel = 13; // play ground with this value to get the best result std::vector<Kd_tree_point> data(points.getPointsNumber()); for (t_index i = 0; i < data.size(); ++i) { Vector3d temp = points.getPoint(i); data[i].coords[0] = temp.x; data[i].coords[1] = temp.y; data[i].coords[2] = temp.z; } std::vector<int> facet_neighbors_indexes, seeds_neighbors_indexes; std::vector<double> facet_neighbors_dists, seeds_neighbors_dists; long _kkt = clock(); tree.Create_kdtree(data, maxTreeLevel); GPU_tree.CreateKDtree(tree.GetRoot(), tree.GetNumNodes(), data, tree.GetLevel()); printf("knn1 time : %lfms\n", (double)(clock() - _kkt)); GPU_tree.Search(M_in, facet_neighbors_indexes, facet_neighbors_dists); printf("knn1 time : %lfms\n", (double)(clock() - _kkt)); GPU_tree.Search_knn(data, seeds_neighbors_indexes, seeds_neighbors_dists, 10); printf("knn1 time : %lfms\n", (double)(clock() - _kkt)); for (int i = 0; i < seeds_neighbors_indexes.size(); ++i) { if (seeds_neighbors_indexes[i] = 12345678) printf("seed %d error", i / 20); } //long _kdtree_time = clock(); //runKnnCuda(points, points, seeds_neighbors_indexes); //printf("Search kdtree time : %lfms\n", (double)(clock() - _kdtree_time)); //printf("vincent kdtree time : %lfms\n", (double)(clock() - _kdtree_time)); //freopen("out1", "w", stdout); long ti = clock(); runRVD(host_points, host_mesh_vertex, host_facet_index, points.getPointsNumber(), M_in.meshVertices.getPointNumber(), M_in.meshFacets.getFacetsNumber(), facet_neighbors_indexes, seeds_neighbors_indexes, seeds_polygon_nb); printf("RVD time : %lfms\n", (double)(clock() - ti)); #else runCuda(host_points, host_mesh_vertex, host_facet_index, points.getPointsNumber(), M_in.meshVertices.getPointNumber(), M_in.meshFacets.getFacetsNumber()); #endif // KNN //getchar(); /* Compute the RVD in CPU */ long t2 = clock(); RestrictedVoronoiDiagram *m_RVD = new RestrictedVoronoiDiagram(&M_in, &points_out); m_RVD->compute_RVD(); printf("CPU running time : %lfms\n", (double)(clock() - t2)); getchar(); /* Set the Windows Use the GLUT lib */ GLUTBackendInit(argc, argv, true, false); GLUTBackendCreateWindow(WINDOWS_WIDTH, WINDOWS_HEIGHT, false, "Rvd"); //GraphicsDrawer* m_GraphicsDrawer = new GraphicsDrawer(); //m_GraphicsDrawer->Init(); //m_GraphicsDrawer->Run(); //p_in records the position before //p_out records the position after compute RVD p_in = points; p_out = points_out; //glutDisplayFunc(&RenderCB); //glutReshapeFunc(&myResize); //glutPostRedisplay(); //glutMainLoop(); delete m_GraphicsDrawer; return 0; } <commit_msg>k = 20<commit_after>/* compute the Restricted Voronoi Diagram in CPU */ //RVD computing part #include "Command_line.h" #include "Mesh_io.h" #include "Mesh.h" #include "Points.h" #include "Mesh_repair.h" // Cuda part #include "CudaHelper.h" #include <time.h> // Renderring part #include "Glut_generator.h" #include "DrawGraphics.h" //kdtree #include "Kdtree.h" #include "CUDA_KDtree.h" // in/out put #include <iostream> #include <fstream> #include <iomanip> #include "RVD.h" #define WINDOWS_WIDTH 1000 #define WINDOWS_HEIGHT 800 using namespace P_RVD; #define KNN GraphicsDrawer* m_GraphicsDrawer = new GraphicsDrawer(); Points p_in, p_out; Mesh M_in; /* call the cuda function pass the data to the device this without knn */ extern "C" void runCuda(double* host_seeds_pointer, double* host_mesh_vertex_pointer, int* host_facet_index, int points_nb, int mesh_vertex_nb, int mesh_facet_number); /* call this cuda function after you've got the nearest neighbors */ extern "C" void runRVD(double* host_seeds_pointer, double* host_mesh_vertex_pointer, int* host_facet_index, int points_nb, int mesh_vertex_nb, int mesh_facet_nb, std::vector<int> facet_center_neigbors, std::vector<int> seeds_neighbors, std::vector<int>& seeds_polygon_nb); /* call the knn cuda */ extern "C" void runKnnCuda(Points r, Points queries, int* indexes); /* renderring part */ void RenderCB(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(0.1f, 0.1f, 0.2f, 0.0f); glDisable(GL_COLOR_MATERIAL); glDisable(GL_LIGHTING); glColor3f(1.0f, 0.0f, 0.0f); m_GraphicsDrawer->DrawPoints(p_in); glColor3f(0.0f, 1.0f, 0.0f); m_GraphicsDrawer->DrawPoints(p_out); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glColor3f(0.8f, 0.8f, 0.8f); glPolygonMode(GL_FRONT, GL_LINE); m_GraphicsDrawer->DrawMesh(M_in); glFlush(); glutSwapBuffers(); glutPostRedisplay(); } void myResize(int width, int height) { //get the viewport of GLUI and then set the viewport back to that after the resize glViewport(0, 0, width, height);//viewportڴ趨һӽǵĴСһڻΪӽ glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluPerspective(60.0, (float)width / height, 0.5f, 20.0f);//趨ӽ glPopMatrix(); gluLookAt(1.0f, 0.0f, 0.0f, 0.0f, 0.f, 0.0f, 0.0f, 1.0f, 0.0f); glClearColor((GLclampf)1 / 255, (GLclampf)1 / 255, (GLclampf)1 / 255, 0.0);//ˢɻɫ glEnable(GL_DEPTH_TEST); } int main(int argc, char** argv) { std::vector<std::string> filenames; if (!Cmd::parse_argu(argc, argv, filenames)) { fprintf(stderr, "cannot parse the argument into filenames!"); return -1; } std::string mesh_filename = filenames[0]; std::string points_filename = filenames[0]; std::string output_filename; if (filenames.size() >= 2) { points_filename = filenames[1]; } output_filename = (filenames.size() == 3) ? filenames[2] : "out.eobj"; Mesh M_out, points_in; FileType mesh_type = OBJfile; if (!mesh_load(mesh_filename, M_in)) { fprintf(stderr, "cannot load Mesh into M_in!"); return -1; } if (!mesh_load(points_filename, points_in, false)) { fprintf(stderr, "cannot load points into points_in!"); return -1; } mesh_repair(M_in); Points points(points_in); Points points_out(points_in); /* trans the data from host to device */ double* host_points = NULL; trans_points(points, host_points); //-------end test---------- double* host_mesh_vertex = NULL; int* host_facet_index = NULL; trans_mesh(M_in, host_mesh_vertex, host_facet_index); std::vector<int> seeds_polygon_nb; #ifdef KNN /* Kdtree Create the tree */ KDtree tree; CUDA_KDTree GPU_tree; const int maxTreeLevel = 13; // play ground with this value to get the best result std::vector<Kd_tree_point> data(points.getPointsNumber()); for (t_index i = 0; i < data.size(); ++i) { Vector3d temp = points.getPoint(i); data[i].coords[0] = temp.x; data[i].coords[1] = temp.y; data[i].coords[2] = temp.z; } std::vector<int> facet_neighbors_indexes, seeds_neighbors_indexes; std::vector<double> facet_neighbors_dists, seeds_neighbors_dists; long _kkt = clock(); tree.Create_kdtree(data, maxTreeLevel); GPU_tree.CreateKDtree(tree.GetRoot(), tree.GetNumNodes(), data, tree.GetLevel()); printf("knn1 time : %lfms\n", (double)(clock() - _kkt)); GPU_tree.Search(M_in, facet_neighbors_indexes, facet_neighbors_dists); printf("knn1 time : %lfms\n", (double)(clock() - _kkt)); //GPU_tree.Search_knn(data, seeds_neighbors_indexes, seeds_neighbors_dists, 10); //printf("knn1 time : %lfms\n", (double)(clock() - _kkt)); long _kdtree_time = clock(); seeds_neighbors_indexes.resize(20 * points.getPointsNumber()); int* ind = (int*)malloc(20 * points.getPointsNumber() * sizeof(int)); runKnnCuda(points, points, ind); for (int i = 0; i < seeds_neighbors_indexes.size(); ++i) seeds_neighbors_indexes[i] = ind[i]-1; free(ind); printf("vincent kdtree time : %lfms\n", (double)(clock() - _kdtree_time)); //freopen("out1", "w", stdout); long ti = clock(); runRVD(host_points, host_mesh_vertex, host_facet_index, points.getPointsNumber(), M_in.meshVertices.getPointNumber(), M_in.meshFacets.getFacetsNumber(), facet_neighbors_indexes, seeds_neighbors_indexes, seeds_polygon_nb); printf("RVD time : %lfms\n", (double)(clock() - ti)); #else runCuda(host_points, host_mesh_vertex, host_facet_index, points.getPointsNumber(), M_in.meshVertices.getPointNumber(), M_in.meshFacets.getFacetsNumber()); #endif // KNN //getchar(); /* Compute the RVD in CPU */ long t2 = clock(); RestrictedVoronoiDiagram *m_RVD = new RestrictedVoronoiDiagram(&M_in, &points_out); m_RVD->compute_RVD(); printf("CPU running time : %lfms\n", (double)(clock() - t2)); getchar(); /* Set the Windows Use the GLUT lib */ GLUTBackendInit(argc, argv, true, false); GLUTBackendCreateWindow(WINDOWS_WIDTH, WINDOWS_HEIGHT, false, "Rvd"); //GraphicsDrawer* m_GraphicsDrawer = new GraphicsDrawer(); //m_GraphicsDrawer->Init(); //m_GraphicsDrawer->Run(); //p_in records the position before //p_out records the position after compute RVD p_in = points; p_out = points_out; //glutDisplayFunc(&RenderCB); //glutReshapeFunc(&myResize); //glutPostRedisplay(); //glutMainLoop(); delete m_GraphicsDrawer; return 0; } <|endoftext|>
<commit_before>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2021 Antti Nuortimo. // // 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 <https://www.gnu.org/licenses/>. #ifndef __YLIKUUTIO_ONTOLOGY_LISP_FUNCTION_OVERLOAD_HPP_INCLUDED #define __YLIKUUTIO_ONTOLOGY_LISP_FUNCTION_OVERLOAD_HPP_INCLUDED #include "generic_lisp_function_overload.hpp" #include "console.hpp" #include "lisp_function.hpp" #include "code/ylikuutio/data/any_value.hpp" #include "code/ylikuutio/data/tuple_templates.hpp" #include "code/ylikuutio/data/wrap.hpp" #include "code/ylikuutio/lisp/function_arg_extractor.hpp" #include "code/ylikuutio/lisp/lisp_templates.hpp" // Include standard headers #include <cstddef> // std::size_t #include <functional> // std::function, std::invoke #include <iostream> // std::cout, std::cin, std::cerr #include <optional> // std::optional #include <string> // std::string #include <tuple> // std::apply, std::tuple, std::tuple_cat #include <vector> // std::vector // This is a bit complicated, as the callback may receive different kinds of arguments. // // The default context is `Universe`. // // 1. If the callback has `yli::ontology::Universe*` as an argument, then the `Universe*` will be provided. // This does not consume any parameters. The `Universe` is set as context. // // 2. If the callback has `yli::ontology::Console*` as an argument, then this `Console*` will be provided. // This does not consume any parameters. In the future other `Console`s will be made reachable as well, // with `yli::ontology::SomeConsole*`. The `Console` is set as context. // // 3. Otherwise, if the callback has `yli::ontology::Entity*` or some subtype of `Entity` as an argument, // then the string will be looked up and converted into that. The `Entity` is set as context. // // 4. If the callback has `yli::ontology::Variable*` as an argument, then the `Variable` with that name // will be looked up from the current context. // // 5. If the callback has `bool` as an argument, then the string will be converted into that. // // 6. If the callback has `float` as an argument, then the string will be converted into that. // // 7. If the callback has `double` as an argument, then the string will be converted into that. // // 8. If the callback has `int32_t` as an argument, then the string will be converted into that. // // 9. If the callback has `uint32_t` as an argument, then the string will be converted into that. // // If any lookup or conversion fails, the callback will not be called. // If `dynamic_cast` from `yli::ontology::Entity*` into its subtype results in `nullptr`, the callback will not be called. // If there is not enough parameters for all conversions, the callback will not be called. // If not all parameters are consumed, the callback will not be called. // // Therefore, the number of provided parameters must match the following equation: // // number-of-provided-parameters = number-of-function-arguments - number-of-Universe-arguments - number-of-Console-arguments namespace yli::ontology { class Entity; class Universe; class Console; class ParentModule; template<typename... Types> class LispFunctionOverload: public yli::ontology::GenericLispFunctionOverload { public: private: template<typename Tag> std::optional<std::tuple<>> process_args( std::size_t, yli::ontology::Universe*, yli::ontology::Console*, yli::ontology::Entity*&, const std::vector<std::string>& parameter_vector, std::size_t& parameter_i) { // This case ends the recursion. // No more arguments to bind. if (parameter_i == parameter_vector.size()) { // All parameters were bound. Binding successful. return std::tuple<>(); } // Not all parameters were bound. Binding failed. return std::nullopt; } template<typename Tag, typename T1, typename... RestTypes> std::optional<std::tuple<typename yli::data::WrapAllButStrings<T1>::type, typename yli::data::WrapAllButStrings<RestTypes>::type...>> process_args( std::size_t tag, yli::ontology::Universe* universe, yli::ontology::Console* console, yli::ontology::Entity*& context, const std::vector<std::string>& parameter_vector, std::size_t& parameter_i) { std::optional<typename yli::data::WrapAllButStrings<T1>::type> value = yli::lisp::convert_string_to_value_and_advance_index<T1>( universe, console, context, parameter_vector, parameter_i); if (!value) { // Binding failed. return std::nullopt; } // OK, binding successful for this argument. // Proceed to the next argument. std::optional<std::tuple<typename yli::data::WrapAllButStrings<RestTypes>::type...>> arg_tuple = this->process_args< std::size_t, RestTypes...>( tag, universe, console, context, parameter_vector, parameter_i); if (arg_tuple) { return std::tuple_cat(std::make_tuple(*value), *arg_tuple); // success. } // Binding failed. return std::nullopt; } std::optional<yli::data::AnyValue> process_args_and_call(const std::vector<std::string>& parameter_vector) { // Start processing the arguments. if (this->universe == nullptr) { return std::nullopt; } yli::ontology::LispFunction* const lisp_function = static_cast<yli::ontology::LispFunction*>(this->get_parent()); if (lisp_function == nullptr) { return std::nullopt; } yli::ontology::Console* const console = static_cast<yli::ontology::Console*>(lisp_function->get_parent()); if (console == nullptr) { return std::nullopt; } std::size_t parameter_i = 0; // Start from the first parameter. yli::ontology::Entity* context = this->universe; // `Universe` is the default context. std::size_t tag; std::optional<std::tuple<typename yli::data::Wrap<Types>::type...>> arg_tuple = this->process_args< std::size_t, Types...>( tag, this->universe, console, context, parameter_vector, parameter_i); if (arg_tuple) { return std::apply(this->callback, *arg_tuple); } std::cout << "ERROR: `LispFunctionOverload::process_args_and_call`: binding failed!\n"; return std::nullopt; } public: LispFunctionOverload( yli::ontology::Universe* const universe, yli::ontology::ParentModule* const parent_module, std::function<std::optional<yli::data::AnyValue>(Types...)> callback) : GenericLispFunctionOverload(universe, parent_module), callback(callback) { // constructor. // `yli::ontology::Entity` member variables begin here. this->type_string = "yli::ontology::LispFunctionOverload*"; } LispFunctionOverload(const LispFunctionOverload&) = delete; // Delete copy constructor. LispFunctionOverload& operator=(const LispFunctionOverload&) = delete; // Delete copy assignment. // destructor. virtual ~LispFunctionOverload() { // destructor. } std::optional<yli::data::AnyValue> execute(const std::vector<std::string>& parameter_vector) override { yli::ontology::Universe* const universe = this->get_universe(); if (universe == nullptr) { std::cerr << "ERROR: `LispFunctionOverload::execute`: `universe` is `nullptr`!\n"; return std::nullopt; } yli::ontology::Entity* const lisp_function_entity = this->child_of_lisp_function.get_parent(); yli::ontology::LispFunction* const lisp_function = dynamic_cast<yli::ontology::LispFunction*>(lisp_function_entity); if (lisp_function == nullptr) { std::cerr << "ERROR: `LispFunctionOverload::execute`: `lisp_function` is `nullptr`!\n"; return std::nullopt; } yli::ontology::Entity* const console_entity = lisp_function->get_parent(); if (console_entity == nullptr) { std::cerr << "ERROR: `LispFunctionOverload::execute`: `console_entity` is `nullptr`!\n"; return std::nullopt; } yli::ontology::Console* const console = dynamic_cast<yli::ontology::Console*>(console_entity); if (console == nullptr) { std::cerr << "ERROR: `LispFunctionOverload::execute`: `console` is `nullptr`!\n"; return std::nullopt; } // OK, all preconditions for a successful argument binding are met. // Now, process the arguments and call. return this->process_args_and_call(parameter_vector); } private: // The callback may receive different kinds of arguments. const std::function<std::optional<yli::data::AnyValue>(Types...)> callback; }; } #endif <commit_msg>Cleaning up code.<commit_after>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2021 Antti Nuortimo. // // 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 <https://www.gnu.org/licenses/>. #ifndef __YLIKUUTIO_ONTOLOGY_LISP_FUNCTION_OVERLOAD_HPP_INCLUDED #define __YLIKUUTIO_ONTOLOGY_LISP_FUNCTION_OVERLOAD_HPP_INCLUDED #include "generic_lisp_function_overload.hpp" #include "console.hpp" #include "lisp_function.hpp" #include "code/ylikuutio/data/any_value.hpp" #include "code/ylikuutio/data/tuple_templates.hpp" #include "code/ylikuutio/data/wrap.hpp" #include "code/ylikuutio/lisp/function_arg_extractor.hpp" #include "code/ylikuutio/lisp/lisp_templates.hpp" // Include standard headers #include <cstddef> // std::size_t #include <functional> // std::function, std::invoke #include <iostream> // std::cout, std::cin, std::cerr #include <optional> // std::optional #include <string> // std::string #include <tuple> // std::apply, std::tuple, std::tuple_cat #include <vector> // std::vector // This is a bit complicated, as the callback may receive different kinds of arguments. // // The default context is `Universe`. // // 1. If the callback has `yli::ontology::Universe*` as an argument, then the `Universe*` will be provided. // This does not consume any parameters. The `Universe` is set as context. // // 2. If the callback has `yli::ontology::Console*` as an argument, then this `Console*` will be provided. // This does not consume any parameters. In the future other `Console`s will be made reachable as well, // with `yli::ontology::SomeConsole*`. The `Console` is set as context. // // 3. Otherwise, if the callback has `yli::ontology::Entity*` or some subtype of `Entity` as an argument, // then the string will be looked up and converted into that. The `Entity` is set as context. // // 4. If the callback has `yli::ontology::Variable*` as an argument, then the `Variable` with that name // will be looked up from the current context. // // 5. If the callback has `bool` as an argument, then the string will be converted into that. // // 6. If the callback has `float` as an argument, then the string will be converted into that. // // 7. If the callback has `double` as an argument, then the string will be converted into that. // // 8. If the callback has `int32_t` as an argument, then the string will be converted into that. // // 9. If the callback has `uint32_t` as an argument, then the string will be converted into that. // // If any lookup or conversion fails, the callback will not be called. // If `dynamic_cast` from `yli::ontology::Entity*` into its subtype results in `nullptr`, the callback will not be called. // If there is not enough parameters for all conversions, the callback will not be called. // If not all parameters are consumed, the callback will not be called. // // Therefore, the number of provided parameters must match the following equation: // // number-of-provided-parameters = number-of-function-arguments - number-of-Universe-arguments - number-of-Console-arguments namespace yli::ontology { class Entity; class Universe; class Console; class ParentModule; template<typename... Types> class LispFunctionOverload: public yli::ontology::GenericLispFunctionOverload { public: private: template<typename Tag> std::optional<std::tuple<>> process_args( std::size_t, yli::ontology::Universe*, yli::ontology::Console*, yli::ontology::Entity*&, const std::vector<std::string>& parameter_vector, std::size_t& parameter_i) { // This case ends the recursion. // No more arguments to bind. if (parameter_i == parameter_vector.size()) { // All parameters were bound. Binding successful. return std::tuple<>(); } // Not all parameters were bound. Binding failed. return std::nullopt; } template<typename Tag, typename T1, typename... RestTypes> std::optional<std::tuple<typename yli::data::WrapAllButStrings<T1>::type, typename yli::data::WrapAllButStrings<RestTypes>::type...>> process_args( std::size_t tag, yli::ontology::Universe* universe, yli::ontology::Console* console, yli::ontology::Entity*& context, const std::vector<std::string>& parameter_vector, std::size_t& parameter_i) { std::optional<typename yli::data::WrapAllButStrings<T1>::type> value = yli::lisp::convert_string_to_value_and_advance_index<T1>( universe, console, context, parameter_vector, parameter_i); if (!value) { // Binding failed. return std::nullopt; } // OK, binding successful for this argument. // Proceed to the next argument. std::optional<std::tuple<typename yli::data::WrapAllButStrings<RestTypes>::type...>> arg_tuple = this->process_args< std::size_t, RestTypes...>( tag, universe, console, context, parameter_vector, parameter_i); if (arg_tuple) { return std::tuple_cat(std::make_tuple(*value), *arg_tuple); // success. } // Binding failed. return std::nullopt; } std::optional<yli::data::AnyValue> process_args_and_call(const std::vector<std::string>& parameter_vector) { // Start processing the arguments. if (this->universe == nullptr) { return std::nullopt; } yli::ontology::LispFunction* const lisp_function = static_cast<yli::ontology::LispFunction*>(this->get_parent()); if (lisp_function == nullptr) { return std::nullopt; } yli::ontology::Console* const console = static_cast<yli::ontology::Console*>(lisp_function->get_parent()); if (console == nullptr) { return std::nullopt; } std::size_t parameter_i = 0; // Start from the first parameter. yli::ontology::Entity* context = this->universe; // `Universe` is the default context. std::optional<std::tuple<typename yli::data::Wrap<Types>::type...>> arg_tuple = this->process_args< std::size_t, Types...>( std::size_t {}, this->universe, console, context, parameter_vector, parameter_i); if (arg_tuple) { return std::apply(this->callback, *arg_tuple); } std::cout << "ERROR: `LispFunctionOverload::process_args_and_call`: binding failed!\n"; return std::nullopt; } public: LispFunctionOverload( yli::ontology::Universe* const universe, yli::ontology::ParentModule* const parent_module, std::function<std::optional<yli::data::AnyValue>(Types...)> callback) : GenericLispFunctionOverload(universe, parent_module), callback(callback) { // constructor. // `yli::ontology::Entity` member variables begin here. this->type_string = "yli::ontology::LispFunctionOverload*"; } LispFunctionOverload(const LispFunctionOverload&) = delete; // Delete copy constructor. LispFunctionOverload& operator=(const LispFunctionOverload&) = delete; // Delete copy assignment. // destructor. virtual ~LispFunctionOverload() { // destructor. } std::optional<yli::data::AnyValue> execute(const std::vector<std::string>& parameter_vector) override { yli::ontology::Universe* const universe = this->get_universe(); if (universe == nullptr) { std::cerr << "ERROR: `LispFunctionOverload::execute`: `universe` is `nullptr`!\n"; return std::nullopt; } yli::ontology::Entity* const lisp_function_entity = this->child_of_lisp_function.get_parent(); yli::ontology::LispFunction* const lisp_function = dynamic_cast<yli::ontology::LispFunction*>(lisp_function_entity); if (lisp_function == nullptr) { std::cerr << "ERROR: `LispFunctionOverload::execute`: `lisp_function` is `nullptr`!\n"; return std::nullopt; } yli::ontology::Entity* const console_entity = lisp_function->get_parent(); if (console_entity == nullptr) { std::cerr << "ERROR: `LispFunctionOverload::execute`: `console_entity` is `nullptr`!\n"; return std::nullopt; } yli::ontology::Console* const console = dynamic_cast<yli::ontology::Console*>(console_entity); if (console == nullptr) { std::cerr << "ERROR: `LispFunctionOverload::execute`: `console` is `nullptr`!\n"; return std::nullopt; } // OK, all preconditions for a successful argument binding are met. // Now, process the arguments and call. return this->process_args_and_call(parameter_vector); } private: // The callback may receive different kinds of arguments. const std::function<std::optional<yli::data::AnyValue>(Types...)> callback; }; } #endif <|endoftext|>
<commit_before>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/tests/gpu_codegen_test.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" namespace xla { namespace gpu { namespace { class FusionLogicalIndexTest : public GpuCodegenTest {}; TEST_F(FusionLogicalIndexTest, FusionLogicalIndexStore) { const char* hlo_text = R"( HloModule TestModule fused_computation.18 { select.12 = f32[768000,16]{1,0} parameter(0) select.13 = f32[768000,16]{1,0} parameter(1) maximum.1 = f32[768000,16]{1,0} maximum(select.13, select.12) ROOT reshape.437 = f32[1,480,400,64]{2,1,3,0} reshape(maximum.1) } ENTRY entry { select.12 = f32[768000,16]{1,0} parameter(0) select.13 = f32[768000,16]{1,0} parameter(1) ROOT fusion.18 = f32[1,480,400,64]{2,1,3,0} fusion(select.12, select.13), kind=kLoop, calls=fused_computation.18 } )"; EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5})); auto expected_ir = is_built_with_rocm_ ? R"( ; CHECK: %[[block_id:.*]] = call i32 @llvm.amdgcn.workgroup.id.x(), !range !1 ; CHECK: %[[thread_id:.*]] = call i32 @llvm.amdgcn.workitem.id.x(), !range !2 ; CHECK: %[[block_start_index:.*]] = mul nuw nsw i32 %[[block_id]], [[block_size:.*]] ; CHECK: %[[linear_index:.*]] = add nuw nsw i32 %[[block_start_index]], %[[thread_id]] ; CHECK: %[[index_1:.*]] = urem i32 %[[linear_index]], 64 ; CHECK: %[[base_1:.*]] = udiv i32 %[[linear_index]], 64 ; CHECK: %[[index_3:.*]] = urem i32 %[[base_1]], 400 ; CHECK: %[[base_3:.*]] = udiv i32 %[[base_1]], 400 ; CHECK: %[[index_2:.*]] = urem i32 %[[base_3]], 480 ; CHECK: %[[pointer:.*]] = getelementptr inbounds [1 x [64 x [480 x [400 x float]]]], [1 x [64 x [480 x [400 x float]]]]* %5, i32 0, i32 0, i32 %[[index_1]], i32 %[[index_2]], i32 %[[index_3]] ; CHECK: store float %[[result_value:.*]], float* %[[pointer]], align 4 )" : R"( ; CHECK: %[[block_id:.*]] = call i32 @llvm.nvvm.read.ptx.sreg.ctaid.x() ; CHECK: %[[thread_id:.*]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() ; CHECK: %[[block_start_index:.*]] = mul nuw nsw i32 %[[block_id]], [[block_size:.*]] ; CHECK: %[[linear_index:.*]] = add nuw nsw i32 %[[block_start_index]], %[[thread_id]] ; CHECK: %[[index_1:.*]] = urem i32 %[[linear_index]], 64 ; CHECK: %[[base_1:.*]] = udiv i32 %[[linear_index]], 64 ; CHECK: %[[index_3:.*]] = urem i32 %[[base_1]], 400 ; CHECK: %[[base_3:.*]] = udiv i32 %[[base_1]], 400 ; CHECK: %[[index_2:.*]] = urem i32 %[[base_3]], 480 ; CHECK: %[[pointer:.*]] = getelementptr inbounds [1 x [64 x [480 x [400 x float]]]], ptr %2, i32 0, i32 0, i32 %[[index_1]], i32 %[[index_2]], i32 %[[index_3]] ; CHECK: store float %[[result_value:.*]], ptr %[[pointer]], align 4 )"; CompileAndVerifyIr(hlo_text, expected_ir); } } // namespace } // namespace gpu } // namespace xla <commit_msg>[ROCm] Fix unit test for ROCm.<commit_after>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/tests/gpu_codegen_test.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" namespace xla { namespace gpu { namespace { class FusionLogicalIndexTest : public GpuCodegenTest {}; TEST_F(FusionLogicalIndexTest, FusionLogicalIndexStore) { const char* hlo_text = R"( HloModule TestModule fused_computation.18 { select.12 = f32[768000,16]{1,0} parameter(0) select.13 = f32[768000,16]{1,0} parameter(1) maximum.1 = f32[768000,16]{1,0} maximum(select.13, select.12) ROOT reshape.437 = f32[1,480,400,64]{2,1,3,0} reshape(maximum.1) } ENTRY entry { select.12 = f32[768000,16]{1,0} parameter(0) select.13 = f32[768000,16]{1,0} parameter(1) ROOT fusion.18 = f32[1,480,400,64]{2,1,3,0} fusion(select.12, select.13), kind=kLoop, calls=fused_computation.18 } )"; EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5})); auto expected_ir = is_built_with_rocm_ ? R"( ; CHECK: %[[block_id:.*]] = call i32 @llvm.amdgcn.workgroup.id.x(), !range !1 ; CHECK: %[[thread_id:.*]] = call i32 @llvm.amdgcn.workitem.id.x(), !range !2 ; CHECK: %[[block_start_index:.*]] = mul nuw nsw i32 %[[block_id]], [[block_size:.*]] ; CHECK: %[[linear_index:.*]] = add nuw nsw i32 %[[block_start_index]], %[[thread_id]] ; CHECK: %[[index_1:.*]] = urem i32 %[[linear_index]], 64 ; CHECK: %[[base_1:.*]] = udiv i32 %[[linear_index]], 64 ; CHECK: %[[index_3:.*]] = urem i32 %[[base_1]], 400 ; CHECK: %[[base_3:.*]] = udiv i32 %[[base_1]], 400 ; CHECK: %[[index_2:.*]] = urem i32 %[[base_3]], 480 ; CHECK: %[[pointer:.*]] = getelementptr inbounds [1 x [64 x [480 x [400 x float]]]], ptr %2, i32 0, i32 0, i32 %[[index_1]], i32 %[[index_2]], i32 %[[index_3]] ; CHECK: store float %[[result_value:.*]], ptr %[[pointer]], align 4 )" : R"( ; CHECK: %[[block_id:.*]] = call i32 @llvm.nvvm.read.ptx.sreg.ctaid.x() ; CHECK: %[[thread_id:.*]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() ; CHECK: %[[block_start_index:.*]] = mul nuw nsw i32 %[[block_id]], [[block_size:.*]] ; CHECK: %[[linear_index:.*]] = add nuw nsw i32 %[[block_start_index]], %[[thread_id]] ; CHECK: %[[index_1:.*]] = urem i32 %[[linear_index]], 64 ; CHECK: %[[base_1:.*]] = udiv i32 %[[linear_index]], 64 ; CHECK: %[[index_3:.*]] = urem i32 %[[base_1]], 400 ; CHECK: %[[base_3:.*]] = udiv i32 %[[base_1]], 400 ; CHECK: %[[index_2:.*]] = urem i32 %[[base_3]], 480 ; CHECK: %[[pointer:.*]] = getelementptr inbounds [1 x [64 x [480 x [400 x float]]]], ptr %2, i32 0, i32 0, i32 %[[index_1]], i32 %[[index_2]], i32 %[[index_3]] ; CHECK: store float %[[result_value:.*]], ptr %[[pointer]], align 4 )"; CompileAndVerifyIr(hlo_text, expected_ir); } } // namespace } // namespace gpu } // namespace xla <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file Ethash.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "Ethash.h" #include <boost/detail/endian.hpp> #include <boost/filesystem.hpp> #include <chrono> #include <array> #include <thread> #include <thread> #include <libdevcore/Guards.h> #include <libdevcore/Log.h> #include <libdevcore/Common.h> #include <libdevcore/CommonIO.h> #include <libdevcore/CommonJS.h> #include <libdevcrypto/CryptoPP.h> #include <libdevcore/FileSystem.h> #include <libethash/ethash.h> #include <libethash/internal.h> #include "BlockInfo.h" #include "EthashAux.h" #include "Exceptions.h" #include "Farm.h" #include "Miner.h" #include "Params.h" #include "EthashSealEngine.h" #include "EthashCPUMiner.h" #include "EthashGPUMiner.h" #include "EthashCUDAMiner.h" using namespace std; using namespace std::chrono; namespace dev { namespace eth { h256 const& Ethash::BlockHeaderRaw::seedHash() const { if (!m_seedHash) m_seedHash = EthashAux::seedHash((unsigned)m_number); return m_seedHash; } void Ethash::BlockHeaderRaw::populateFromHeader(RLP const& _header, Strictness _s) { m_mixHash = _header[BlockInfo::BasicFields].toHash<h256>(); m_nonce = _header[BlockInfo::BasicFields + 1].toHash<h64>(); // check it hashes according to proof of work or that it's the genesis block. if (_s == CheckEverything && m_parentHash && !verify()) { InvalidBlockNonce ex; ex << errinfo_nonce(m_nonce); ex << errinfo_mixHash(m_mixHash); ex << errinfo_seedHash(seedHash()); EthashProofOfWork::Result er = EthashAux::eval(seedHash(), hashWithout(), m_nonce); ex << errinfo_ethashResult(make_tuple(er.value, er.mixHash)); ex << errinfo_hash256(hashWithout()); ex << errinfo_difficulty(m_difficulty); ex << errinfo_target(boundary()); BOOST_THROW_EXCEPTION(ex); } else if (_s == QuickNonce && m_parentHash && !preVerify()) { InvalidBlockNonce ex; ex << errinfo_hash256(hashWithout()); ex << errinfo_difficulty(m_difficulty); ex << errinfo_nonce(m_nonce); BOOST_THROW_EXCEPTION(ex); } if (_s != CheckNothing) { if (m_difficulty < c_minimumDifficulty) BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError(bigint(c_minimumDifficulty), bigint(m_difficulty)) ); if (m_gasLimit < c_minGasLimit) BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError(bigint(c_minGasLimit), bigint(m_gasLimit)) ); if (m_number && m_extraData.size() > c_maximumExtraDataSize) BOOST_THROW_EXCEPTION(ExtraDataTooBig() << RequirementError(bigint(c_maximumExtraDataSize), bigint(m_extraData.size())) << errinfo_extraData(m_extraData)); } } void Ethash::BlockHeaderRaw::verifyParent(BlockHeaderRaw const& _parent) { // Check difficulty is correct given the two timestamps. if (m_difficulty != calculateDifficulty(_parent)) BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError((bigint)calculateDifficulty(_parent), (bigint)m_difficulty)); if (m_gasLimit < c_minGasLimit || m_gasLimit <= _parent.m_gasLimit - _parent.m_gasLimit / c_gasLimitBoundDivisor || m_gasLimit >= _parent.m_gasLimit + _parent.m_gasLimit / c_gasLimitBoundDivisor) BOOST_THROW_EXCEPTION(InvalidGasLimit() << errinfo_min((bigint)_parent.m_gasLimit - _parent.m_gasLimit / c_gasLimitBoundDivisor) << errinfo_got((bigint)m_gasLimit) << errinfo_max((bigint)_parent.m_gasLimit + _parent.m_gasLimit / c_gasLimitBoundDivisor)); } void Ethash::BlockHeaderRaw::populateFromParent(BlockHeaderRaw const& _parent) { (void)_parent; } bool Ethash::BlockHeaderRaw::preVerify() const { if (m_number >= ETHASH_EPOCH_LENGTH * 2048) return false; bool ret = !!ethash_quick_check_difficulty( (ethash_h256_t const*)hashWithout().data(), (uint64_t)(u64)m_nonce, (ethash_h256_t const*)m_mixHash.data(), (ethash_h256_t const*)boundary().data()); return ret; } bool Ethash::BlockHeaderRaw::verify() const { bool pre = preVerify(); #if !ETH_DEBUG if (!pre) { cwarn << "Fail on preVerify"; return false; } #endif auto result = EthashAux::eval(seedHash(), hashWithout(), m_nonce); bool slow = result.value <= boundary() && result.mixHash == m_mixHash; // cdebug << (slow ? "VERIFY" : "VERYBAD"); // cdebug << result.value.hex() << _header.boundary().hex(); // cdebug << result.mixHash.hex() << _header.mixHash.hex(); #if ETH_DEBUG || !ETH_TRUE if (!pre && slow) { cwarn << "WARNING: evaluated result gives true whereas ethash_quick_check_difficulty gives false."; cwarn << "headerHash:" << hashWithout(); cwarn << "nonce:" << m_nonce; cwarn << "mixHash:" << m_mixHash; cwarn << "difficulty:" << m_difficulty; cwarn << "boundary:" << boundary(); cwarn << "result.value:" << result.value; cwarn << "result.mixHash:" << result.mixHash; } #endif return slow; } void Ethash::BlockHeaderRaw::prep(std::function<int(unsigned)> const& _f) const { EthashAux::full(seedHash(), true, _f); } StringHashMap Ethash::BlockHeaderRaw::jsInfo() const { return { { "nonce", toJS(m_nonce) }, { "seedHash", toJS(seedHash()) }, { "mixHash", toJS(m_mixHash) } }; } void Ethash::manuallySetWork(SealEngineFace* _engine, BlockHeader const& _work) { // set m_sealing to the current problem. if (EthashSealEngine* e = dynamic_cast<EthashSealEngine*>(_engine)) e->m_sealing = _work; } void Ethash::manuallySubmitWork(SealEngineFace* _engine, h256 const& _mixHash, Nonce _nonce) { if (EthashSealEngine* e = dynamic_cast<EthashSealEngine*>(_engine)) { // Go via the farm since the handler function object is stored as a local within the Farm's lambda. // Has the side effect of stopping local workers, which is good, as long as it only does it for // valid submissions. static_cast<GenericFarmFace<EthashProofOfWork>&>(e->m_farm).submitProof(EthashProofOfWork::Solution{_nonce, _mixHash}, nullptr); } } bool Ethash::isWorking(SealEngineFace* _engine) { if (EthashSealEngine* e = dynamic_cast<EthashSealEngine*>(_engine)) return e->m_farm.isMining(); return false; } WorkingProgress Ethash::workingProgress(SealEngineFace* _engine) { if (EthashSealEngine* e = dynamic_cast<EthashSealEngine*>(_engine)) return e->m_farm.miningProgress(); return WorkingProgress(); } SealEngineFace* Ethash::createSealEngine() { return new EthashSealEngine; } std::string Ethash::name() { return "Ethash"; } unsigned Ethash::revision() { return ETHASH_REVISION; } void Ethash::ensurePrecomputed(unsigned _number) { if (_number % ETHASH_EPOCH_LENGTH > ETHASH_EPOCH_LENGTH * 9 / 10) // 90% of the way to the new epoch EthashAux::computeFull(EthashAux::seedHash(_number + ETHASH_EPOCH_LENGTH), true); } } } <commit_msg>backport of commit https://github.com/ethereum/libethereum/pull/143 for boost 1.60<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file Ethash.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "Ethash.h" #include <boost/detail/endian.hpp> #include <boost/filesystem.hpp> #include <chrono> #include <array> #include <thread> #include <thread> #include <libdevcore/Guards.h> #include <libdevcore/Log.h> #include <libdevcore/Common.h> #include <libdevcore/CommonIO.h> #include <libdevcore/CommonJS.h> #include <libdevcrypto/CryptoPP.h> #include <libdevcore/FileSystem.h> #include <libethash/ethash.h> #include <libethash/internal.h> #include "BlockInfo.h" #include "EthashAux.h" #include "Exceptions.h" #include "Farm.h" #include "Miner.h" #include "Params.h" #include "EthashSealEngine.h" #include "EthashCPUMiner.h" #include "EthashGPUMiner.h" #include "EthashCUDAMiner.h" using namespace std; using namespace std::chrono; namespace dev { namespace eth { h256 const& Ethash::BlockHeaderRaw::seedHash() const { if (!m_seedHash) m_seedHash = EthashAux::seedHash((unsigned)m_number); return m_seedHash; } void Ethash::BlockHeaderRaw::populateFromHeader(RLP const& _header, Strictness _s) { m_mixHash = _header[BlockInfo::BasicFields].toHash<h256>(); m_nonce = _header[BlockInfo::BasicFields + 1].toHash<h64>(); // check it hashes according to proof of work or that it's the genesis block. if (_s == CheckEverything && m_parentHash && !verify()) { InvalidBlockNonce ex; ex << errinfo_nonce(m_nonce); ex << errinfo_mixHash(m_mixHash); ex << errinfo_seedHash(seedHash()); EthashProofOfWork::Result er = EthashAux::eval(seedHash(), hashWithout(), m_nonce); ex << errinfo_ethashResult(make_tuple(er.value, er.mixHash)); ex << errinfo_hash256(hashWithout()); ex << errinfo_difficulty(m_difficulty); ex << errinfo_target(boundary()); BOOST_THROW_EXCEPTION(ex); } else if (_s == QuickNonce && m_parentHash && !preVerify()) { InvalidBlockNonce ex; ex << errinfo_hash256(hashWithout()); ex << errinfo_difficulty(m_difficulty); ex << errinfo_nonce(m_nonce); BOOST_THROW_EXCEPTION(ex); } if (_s != CheckNothing) { if (m_difficulty < c_minimumDifficulty) BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError(bigint(c_minimumDifficulty), bigint(m_difficulty)) ); if (m_gasLimit < c_minGasLimit) BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError(bigint(c_minGasLimit), bigint(m_gasLimit)) ); if (m_number && m_extraData.size() > c_maximumExtraDataSize) BOOST_THROW_EXCEPTION(ExtraDataTooBig() << RequirementError(bigint(c_maximumExtraDataSize), bigint(m_extraData.size())) << errinfo_extraData(m_extraData)); } } void Ethash::BlockHeaderRaw::verifyParent(BlockHeaderRaw const& _parent) { // Check difficulty is correct given the two timestamps. if (m_difficulty != calculateDifficulty(_parent)) BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError((bigint)calculateDifficulty(_parent), (bigint)m_difficulty)); if (m_gasLimit < c_minGasLimit || m_gasLimit <= _parent.m_gasLimit - _parent.m_gasLimit / c_gasLimitBoundDivisor || m_gasLimit >= _parent.m_gasLimit + _parent.m_gasLimit / c_gasLimitBoundDivisor) BOOST_THROW_EXCEPTION(InvalidGasLimit() << errinfo_min((bigint)_parent.m_gasLimit - _parent.m_gasLimit / c_gasLimitBoundDivisor) << errinfo_got((bigint)m_gasLimit) << errinfo_max((bigint)_parent.m_gasLimit + _parent.m_gasLimit / c_gasLimitBoundDivisor)); } void Ethash::BlockHeaderRaw::populateFromParent(BlockHeaderRaw const& _parent) { (void)_parent; } bool Ethash::BlockHeaderRaw::preVerify() const { if (m_number >= ETHASH_EPOCH_LENGTH * 2048) return false; bool ret = !!ethash_quick_check_difficulty( (ethash_h256_t const*)hashWithout().data(), (uint64_t)(u64)m_nonce, (ethash_h256_t const*)m_mixHash.data(), (ethash_h256_t const*)boundary().data()); return ret; } bool Ethash::BlockHeaderRaw::verify() const { bool pre = preVerify(); #if !ETH_DEBUG if (!pre) { cwarn << "Fail on preVerify"; return false; } #endif auto result = EthashAux::eval(seedHash(), hashWithout(), m_nonce); bool slow = result.value <= boundary() && result.mixHash == m_mixHash; // cdebug << (slow ? "VERIFY" : "VERYBAD"); // cdebug << result.value.hex() << _header.boundary().hex(); // cdebug << result.mixHash.hex() << _header.mixHash.hex(); #if ETH_DEBUG || !ETH_TRUE if (!pre && slow) { cwarn << "WARNING: evaluated result gives true whereas ethash_quick_check_difficulty gives false."; cwarn << "headerHash:" << hashWithout(); cwarn << "nonce:" << m_nonce; cwarn << "mixHash:" << m_mixHash; cwarn << "difficulty:" << m_difficulty; cwarn << "boundary:" << boundary(); cwarn << "result.value:" << result.value; cwarn << "result.mixHash:" << result.mixHash; } #endif return slow; } void Ethash::BlockHeaderRaw::prep(std::function<int(unsigned)> const& _f) const { EthashAux::full(seedHash(), true, _f); } StringHashMap Ethash::BlockHeaderRaw::jsInfo() const { return { { "nonce", toJS(m_nonce) }, { "seedHash", toJS(seedHash()) }, { "mixHash", toJS(m_mixHash) } }; } void Ethash::manuallySetWork(SealEngineFace* _engine, BlockHeader const& _work) { // set m_sealing to the current problem. if (EthashSealEngine* e = dynamic_cast<EthashSealEngine*>(_engine)) e->m_sealing = _work; } void Ethash::manuallySubmitWork(SealEngineFace* _engine, h256 const& _mixHash, Nonce _nonce) { if (EthashSealEngine* e = dynamic_cast<EthashSealEngine*>(_engine)) { // Go via the farm since the handler function object is stored as a local within the Farm's lambda. // Has the side effect of stopping local workers, which is good, as long as it only does it for // valid submissions. static_cast<GenericFarmFace<EthashProofOfWork>&>(e->m_farm).submitProof(EthashProofOfWork::Solution{_nonce, _mixHash}, nullptr); } } bool Ethash::isWorking(SealEngineFace* _engine) { if (EthashSealEngine* e = dynamic_cast<EthashSealEngine*>(_engine)) return e->m_farm.isMining(); return false; } WorkingProgress Ethash::workingProgress(SealEngineFace* _engine) { if (EthashSealEngine* e = dynamic_cast<EthashSealEngine*>(_engine)) return e->m_farm.miningProgress(); return WorkingProgress(); } SealEngineFace* Ethash::createSealEngine() { return new EthashSealEngine; } std::string Ethash::name() { return "Ethash"; } unsigned Ethash::revision() { return ETHASH_REVISION; } void Ethash::ensurePrecomputed(unsigned _number) { if (_number % ETHASH_EPOCH_LENGTH > ETHASH_EPOCH_LENGTH * 9 / 10) // 90% of the way to the new epoch EthashAux::computeFull(EthashAux::seedHash(_number + ETHASH_EPOCH_LENGTH), true); } } } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2014-2019 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/python3qt/pythonmenu.h> #include <modules/python3qt/pythoneditorwidget.h> #include <modules/qtwidgets/inviwoqtutils.h> #include <modules/qtwidgets/inviwofiledialog.h> #include <inviwo/core/common/inviwomodule.h> #include <inviwo/core/util/filesystem.h> #include <fmt/format.h> #include <fmt/ostream.h> #include <warn/push> #include <warn/ignore/all> #include <QMenu> #include <QMainWindow> #include <QMenuBar> #include <QAction> #include <QLayout> #include <QDesktopServices> #include <QUrl> #include <warn/pop> namespace inviwo { PythonMenu::PythonMenu(InviwoModule* pymodule, InviwoApplication* app) { if (auto win = utilqt::getApplicationMainWindow()) { menu_.reset(utilqt::addMenu("&Python")); win->connect(menu_.get(), &QMenu::destroyed, [this](QObject*) { menu_.release(); }); auto pythonEditorOpen = menu_->addAction(QIcon(":/icons/python.png"), "&Python Editor"); win->connect(pythonEditorOpen, &QAction::triggered, [this, win, app]() { auto editor = std::make_unique<PythonEditorWidget>(win, app); editor->loadState(); editor->setAttribute(Qt::WA_DeleteOnClose); if (!editors_.empty()) { auto newPos = editors_.back()->pos() + QPoint(40, 40); if (newPos.x() > 800) newPos.setX(350); if (newPos.y() > 800) newPos.setX(100); editor->move(newPos); } win->connect(editor.get(), &PythonEditorWidget::destroyed, [this](QObject* obj) { auto it = std::find_if(editors_.begin(), editors_.end(), [&](auto& elem) { return elem.get() == obj; }); if (it != editors_.end()) { it->release(); editors_.erase(it); } }); editor->setVisible(true); editors_.push_back(std::move(editor)); }); auto pyProperties = menu_->addAction("&List unexposed properties"); win->connect(pyProperties, &QAction::triggered, [app]() { auto mod = app->getModuleByType<Python3Module>(); PythonScriptDisk(mod->getPath() + "/scripts/list_not_exposed_properties.py").run(); }); auto newPythonProcessor = menu_->addAction(QIcon(":/svgicons/processor-new.svg"), "&New Python Processor"); win->connect(newPythonProcessor, &QAction::triggered, [pymodule, app]() { InviwoFileDialog saveFileDialog(nullptr, "Create Python Processor", "PythonProcessor"); saveFileDialog.setFileMode(FileMode::AnyFile); saveFileDialog.setAcceptMode(AcceptMode::Save); saveFileDialog.setConfirmOverwrite(true); saveFileDialog.addExtension("*.py", "Python file"); const auto dir = app->getPath(PathType::Settings) + "/python_processors"; filesystem::createDirectoryRecursively(dir); saveFileDialog.setCurrentDirectory(dir); if (saveFileDialog.exec()) { QString qpath = saveFileDialog.selectedFiles().at(0); const auto path = utilqt::fromQString(qpath); const auto templatePath = pymodule->getPath() + "/templates/templateprocessor.py"; auto ifs = filesystem::ifstream(templatePath); std::stringstream ss; ss << ifs.rdbuf(); const auto script = std::move(ss).str(); const auto name = filesystem::getFileNameWithoutExtension(path); auto ofs = filesystem::ofstream(path); fmt::print(ofs, script, fmt::arg("name", name)); QDesktopServices::openUrl(QUrl("file:///" + qpath, QUrl::TolerantMode)); } }); } } PythonMenu::~PythonMenu() = default; } // namespace inviwo <commit_msg>Python3Qt: python menu fix * fixed file extension when creating a python processor<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2014-2019 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/python3qt/pythonmenu.h> #include <modules/python3qt/pythoneditorwidget.h> #include <modules/qtwidgets/inviwoqtutils.h> #include <modules/qtwidgets/inviwofiledialog.h> #include <inviwo/core/common/inviwomodule.h> #include <inviwo/core/util/filesystem.h> #include <fmt/format.h> #include <fmt/ostream.h> #include <warn/push> #include <warn/ignore/all> #include <QMenu> #include <QMainWindow> #include <QMenuBar> #include <QAction> #include <QLayout> #include <QDesktopServices> #include <QUrl> #include <warn/pop> namespace inviwo { PythonMenu::PythonMenu(InviwoModule* pymodule, InviwoApplication* app) { if (auto win = utilqt::getApplicationMainWindow()) { menu_.reset(utilqt::addMenu("&Python")); win->connect(menu_.get(), &QMenu::destroyed, [this](QObject*) { menu_.release(); }); auto pythonEditorOpen = menu_->addAction(QIcon(":/icons/python.png"), "&Python Editor"); win->connect(pythonEditorOpen, &QAction::triggered, [this, win, app]() { auto editor = std::make_unique<PythonEditorWidget>(win, app); editor->loadState(); editor->setAttribute(Qt::WA_DeleteOnClose); if (!editors_.empty()) { auto newPos = editors_.back()->pos() + QPoint(40, 40); if (newPos.x() > 800) newPos.setX(350); if (newPos.y() > 800) newPos.setX(100); editor->move(newPos); } win->connect(editor.get(), &PythonEditorWidget::destroyed, [this](QObject* obj) { auto it = std::find_if(editors_.begin(), editors_.end(), [&](auto& elem) { return elem.get() == obj; }); if (it != editors_.end()) { it->release(); editors_.erase(it); } }); editor->setVisible(true); editors_.push_back(std::move(editor)); }); auto pyProperties = menu_->addAction("&List unexposed properties"); win->connect(pyProperties, &QAction::triggered, [app]() { auto mod = app->getModuleByType<Python3Module>(); PythonScriptDisk(mod->getPath() + "/scripts/list_not_exposed_properties.py").run(); }); auto newPythonProcessor = menu_->addAction(QIcon(":/svgicons/processor-new.svg"), "&New Python Processor"); win->connect(newPythonProcessor, &QAction::triggered, [pymodule, app]() { InviwoFileDialog saveFileDialog(nullptr, "Create Python Processor", "PythonProcessor"); saveFileDialog.setFileMode(FileMode::AnyFile); saveFileDialog.setAcceptMode(AcceptMode::Save); saveFileDialog.setConfirmOverwrite(true); saveFileDialog.addExtension("py", "Python file"); const auto dir = app->getPath(PathType::Settings) + "/python_processors"; filesystem::createDirectoryRecursively(dir); saveFileDialog.setCurrentDirectory(dir); if (saveFileDialog.exec()) { QString qpath = saveFileDialog.selectedFiles().at(0); const auto path = utilqt::fromQString(qpath); const auto templatePath = pymodule->getPath() + "/templates/templateprocessor.py"; auto ifs = filesystem::ifstream(templatePath); std::stringstream ss; ss << ifs.rdbuf(); const auto script = std::move(ss).str(); const auto name = filesystem::getFileNameWithoutExtension(path); auto ofs = filesystem::ofstream(path); fmt::print(ofs, script, fmt::arg("name", name)); QDesktopServices::openUrl(QUrl("file:///" + qpath, QUrl::TolerantMode)); } }); } } PythonMenu::~PythonMenu() = default; } // namespace inviwo <|endoftext|>
<commit_before> #pragma GCC diagnostic ignored "-Wconversion" #include <libdevcrypto/SHA3.h> #include <libethcore/Params.h> #include <libevm/ExtVMFace.h> #include "Utils.h" extern "C" { #ifdef _MSC_VER #define EXPORT __declspec(dllexport) #else #define EXPORT #endif using namespace dev; using namespace dev::eth; using jit::i256; EXPORT void env_sload(ExtVMFace* _env, i256* _index, i256* o_value) { auto index = llvm2eth(*_index); auto value = _env->store(index); // Interface uses native endianness *o_value = eth2llvm(value); } EXPORT void env_sstore(ExtVMFace* _env, i256* _index, i256* _value) { auto index = llvm2eth(*_index); auto value = llvm2eth(*_value); if (value == 0 && _env->store(index) != 0) // If delete _env->sub.refunds += c_sstoreRefundGas; // Increase refund counter _env->setStore(index, value); // Interface uses native endianness } EXPORT void env_balance(ExtVMFace* _env, h256* _address, i256* o_value) { auto u = _env->balance(right160(*_address)); *o_value = eth2llvm(u); } EXPORT void env_blockhash(ExtVMFace* _env, i256* _number, h256* o_hash) { *o_hash = _env->blockhash(llvm2eth(*_number)); } EXPORT void env_create(ExtVMFace* _env, int64_t* io_gas, i256* _endowment, byte* _initBeg, uint64_t _initSize, h256* o_address) { auto endowment = llvm2eth(*_endowment); if (_env->balance(_env->myAddress) >= endowment && _env->depth < 1024) { _env->subBalance(endowment); u256 gas = *io_gas; h256 address(_env->create(endowment, gas, {_initBeg, _initSize}, {}), h256::AlignRight); *io_gas = static_cast<int64_t>(gas); *o_address = address; } else *o_address = {}; } EXPORT bool env_call(ExtVMFace* _env, int64_t* io_gas, int64_t _callGas, h256* _receiveAddress, i256* _value, byte* _inBeg, uint64_t _inSize, byte* _outBeg, uint64_t _outSize, h256* _codeAddress) { auto value = llvm2eth(*_value); auto receiveAddress = right160(*_receiveAddress); auto codeAddress = right160(*_codeAddress); const auto isCall = receiveAddress == codeAddress; // OPT: The same address pointer can be used if not CODECALL *io_gas -= _callGas; if (*io_gas < 0) return false; if (isCall && !_env->exists(receiveAddress)) *io_gas -= static_cast<int64_t>(c_callNewAccountGas); // no underflow, *io_gas non-negative before if (value > 0) // value transfer { /*static*/ assert(c_callValueTransferGas > c_callStipend && "Overflow possible"); *io_gas -= static_cast<int64_t>(c_callValueTransferGas); // no underflow _callGas += static_cast<int64_t>(c_callStipend); // overflow possibility, but in the same time *io_gas < 0 } if (*io_gas < 0) return false; auto ret = false; auto callGas = u256{_callGas}; if (_env->balance(_env->myAddress) >= value && _env->depth < 1024) { _env->subBalance(value); ret = _env->call(receiveAddress, value, {_inBeg, _inSize}, callGas, {_outBeg, _outSize}, {}, {}, codeAddress); } *io_gas += static_cast<int64_t>(callGas); // it is never more than initial _callGas return ret; } EXPORT void env_sha3(byte* _begin, uint64_t _size, h256* o_hash) { auto hash = sha3({_begin, _size}); *o_hash = hash; } EXPORT byte const* env_extcode(ExtVMFace* _env, h256* _addr256, uint64_t* o_size) { auto addr = right160(*_addr256); auto& code = _env->codeAt(addr); *o_size = code.size(); return code.data(); } EXPORT void env_log(ExtVMFace* _env, byte* _beg, uint64_t _size, h256* _topic1, h256* _topic2, h256* _topic3, h256* _topic4) { dev::h256s topics; if (_topic1) topics.push_back(*_topic1); if (_topic2) topics.push_back(*_topic2); if (_topic3) topics.push_back(*_topic3); if (_topic4) topics.push_back(*_topic4); _env->log(std::move(topics), {_beg, _size}); } } <commit_msg>Do not subbalance twice<commit_after> #pragma GCC diagnostic ignored "-Wconversion" #include <libdevcrypto/SHA3.h> #include <libethcore/Params.h> #include <libevm/ExtVMFace.h> #include "Utils.h" extern "C" { #ifdef _MSC_VER #define EXPORT __declspec(dllexport) #else #define EXPORT #endif using namespace dev; using namespace dev::eth; using jit::i256; EXPORT void env_sload(ExtVMFace* _env, i256* _index, i256* o_value) { auto index = llvm2eth(*_index); auto value = _env->store(index); // Interface uses native endianness *o_value = eth2llvm(value); } EXPORT void env_sstore(ExtVMFace* _env, i256* _index, i256* _value) { auto index = llvm2eth(*_index); auto value = llvm2eth(*_value); if (value == 0 && _env->store(index) != 0) // If delete _env->sub.refunds += c_sstoreRefundGas; // Increase refund counter _env->setStore(index, value); // Interface uses native endianness } EXPORT void env_balance(ExtVMFace* _env, h256* _address, i256* o_value) { auto u = _env->balance(right160(*_address)); *o_value = eth2llvm(u); } EXPORT void env_blockhash(ExtVMFace* _env, i256* _number, h256* o_hash) { *o_hash = _env->blockhash(llvm2eth(*_number)); } EXPORT void env_create(ExtVMFace* _env, int64_t* io_gas, i256* _endowment, byte* _initBeg, uint64_t _initSize, h256* o_address) { auto endowment = llvm2eth(*_endowment); if (_env->balance(_env->myAddress) >= endowment && _env->depth < 1024) { u256 gas = *io_gas; h256 address(_env->create(endowment, gas, {_initBeg, _initSize}, {}), h256::AlignRight); *io_gas = static_cast<int64_t>(gas); *o_address = address; } else *o_address = {}; } EXPORT bool env_call(ExtVMFace* _env, int64_t* io_gas, int64_t _callGas, h256* _receiveAddress, i256* _value, byte* _inBeg, uint64_t _inSize, byte* _outBeg, uint64_t _outSize, h256* _codeAddress) { auto value = llvm2eth(*_value); auto receiveAddress = right160(*_receiveAddress); auto codeAddress = right160(*_codeAddress); const auto isCall = receiveAddress == codeAddress; // OPT: The same address pointer can be used if not CODECALL *io_gas -= _callGas; if (*io_gas < 0) return false; if (isCall && !_env->exists(receiveAddress)) *io_gas -= static_cast<int64_t>(c_callNewAccountGas); // no underflow, *io_gas non-negative before if (value > 0) // value transfer { /*static*/ assert(c_callValueTransferGas > c_callStipend && "Overflow possible"); *io_gas -= static_cast<int64_t>(c_callValueTransferGas); // no underflow _callGas += static_cast<int64_t>(c_callStipend); // overflow possibility, but in the same time *io_gas < 0 } if (*io_gas < 0) return false; auto ret = false; auto callGas = u256{_callGas}; if (_env->balance(_env->myAddress) >= value && _env->depth < 1024) ret = _env->call(receiveAddress, value, {_inBeg, _inSize}, callGas, {_outBeg, _outSize}, {}, {}, codeAddress); *io_gas += static_cast<int64_t>(callGas); // it is never more than initial _callGas return ret; } EXPORT void env_sha3(byte* _begin, uint64_t _size, h256* o_hash) { auto hash = sha3({_begin, _size}); *o_hash = hash; } EXPORT byte const* env_extcode(ExtVMFace* _env, h256* _addr256, uint64_t* o_size) { auto addr = right160(*_addr256); auto& code = _env->codeAt(addr); *o_size = code.size(); return code.data(); } EXPORT void env_log(ExtVMFace* _env, byte* _beg, uint64_t _size, h256* _topic1, h256* _topic2, h256* _topic3, h256* _topic4) { dev::h256s topics; if (_topic1) topics.push_back(*_topic1); if (_topic2) topics.push_back(*_topic2); if (_topic3) topics.push_back(*_topic3); if (_topic4) topics.push_back(*_topic4); _env->log(std::move(topics), {_beg, _size}); } } <|endoftext|>
<commit_before><commit_msg>alerts: fix alpha blending<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved. // // ______ __ ___ // /\__ _\ /\ \ /\_ \ // \/_/\ \/ __ \_\ \ _____ ___\//\ \ __ // \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\ // \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/ // \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\ // \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/ // \ \_\ // \/_/ // // 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 ofconditions 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 materialsprovided 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 "harness.hh" #include "token.hh" TADPOLE_TEST(TadpoleToken) { using TK = tadpole::TokenKind; #define NEWTK2(k, s) tadpole::Token(k, s, 0) #define NEWTK3(k, s, l) tadpole::Token(k, s, l) #define TESTEQ(a, b) TADPOLE_CHECK_EQ(a, b) #define TESTTK(k, s) do {\ auto t = NEWTK2(k, s);\ TESTEQ(t.kind(), k);\ TESTEQ(t.literal(), s);\ TESTEQ(t.lineno(), 0);\ } while (false) #define TESTID(id) TESTTK(TK::TK_IDENTIFIER, id) #define TESTNUM(n) do {\ auto t = NEWTK2(TK::TK_NUMERIC, #n);\ TESTEQ(t.kind(), TK::TK_NUMERIC);\ TESTEQ(t.as_numeric(), n);\ TESTEQ(t.lineno(), 0);\ } while (false) #define TESTSTR(s, l) do {\ auto t = NEWTK3(TK::TK_STRING, s, l);\ TESTEQ(t.kind(), TK::TK_STRING);\ TESTEQ(t.literal(), s);\ TESTEQ(t.lineno(), l);\ } while (false) TESTTK(TK::TK_LPAREN, "("); TESTTK(TK::TK_RPAREN, ")"); TESTTK(TK::TK_LBRACE, "{"); TESTTK(TK::TK_RBRACE, "}"); TESTTK(TK::TK_COMMA, ","); TESTTK(TK::TK_MINUS, "-"); TESTTK(TK::TK_PLUS, "+"); TESTTK(TK::TK_SEMI, ";"); TESTTK(TK::TK_SLASH, "/"); TESTTK(TK::TK_STAR, "*"); TESTTK(TK::TK_EQ, "="); TESTTK(TK::KW_FALSE, "false"); TESTTK(TK::KW_FN, "fn"); TESTTK(TK::KW_NIL, "nil"); TESTTK(TK::KW_TRUE, "true"); TESTTK(TK::KW_VAR, "var"); TESTTK(TK::TK_EOF, "EOF"); TESTTK(TK::TK_ERR, "ERR"); { // test for IDENTIFIER TESTID("foo"); TESTID("Foo"); TESTID("_foo"); TESTID("_Foo"); TESTID("__foo"); TESTID("__Foo"); TESTID("foo_"); TESTID("Foo_"); TESTID("foo__"); TESTID("Foo__"); TESTID("__foo__"); TESTID("__Foo__"); TESTID("foo1"); TESTID("Foo1"); TESTID("_foo1"); TESTID("_Foo1"); TESTID("__foo1"); TESTID("__Foo1"); TESTID("foo_1"); TESTID("Foo_1"); TESTID("foo__1"); TESTID("Foo__1"); TESTID("_foo_1"); TESTID("_Foo_1"); TESTID("__foo__1__Foo__1"); } { // test for NUMERIC TESTNUM(100); TESTNUM(-100); TESTNUM(1.2345); TESTNUM(-1.2345); TESTNUM(100.0); TESTNUM(-100.0); } #undef TESTSTR #undef TESTNUM #undef TESTTK #undef TESTEQ #undef NEWTK3 #undef NEWTK2 } <commit_msg>:white_check_mark: test(token): updated the test for token<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved. // // ______ __ ___ // /\__ _\ /\ \ /\_ \ // \/_/\ \/ __ \_\ \ _____ ___\//\ \ __ // \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\ // \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/ // \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\ // \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/ // \ \_\ // \/_/ // // 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 ofconditions 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 materialsprovided 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 "harness.hh" #include "token.hh" TADPOLE_TEST(TadpoleToken) { using TK = tadpole::TokenKind; #define NEWTK2(k, s) tadpole::Token(k, s, 0) #define NEWTK3(k, s, l) tadpole::Token(k, s, l) #define TESTEQ(a, b) TADPOLE_CHECK_EQ(a, b) #define TESTTK(k, s) do {\ auto t = NEWTK2(k, s);\ TESTEQ(t.kind(), k);\ TESTEQ(t.literal(), s);\ TESTEQ(t.lineno(), 0);\ } while (false) #define TESTID(id) TESTTK(TK::TK_IDENTIFIER, id) #define TESTNUM(n) do {\ auto t = NEWTK2(TK::TK_NUMERIC, #n);\ TESTEQ(t.kind(), TK::TK_NUMERIC);\ TESTEQ(t.as_numeric(), n);\ TESTEQ(t.lineno(), 0);\ } while (false) #define TESTSTR(s, l) do {\ auto t = NEWTK3(TK::TK_STRING, s, l);\ TESTEQ(t.kind(), TK::TK_STRING);\ TESTEQ(t.literal(), s);\ TESTEQ(t.lineno(), l);\ } while (false) TESTTK(TK::TK_LPAREN, "("); TESTTK(TK::TK_RPAREN, ")"); TESTTK(TK::TK_LBRACE, "{"); TESTTK(TK::TK_RBRACE, "}"); TESTTK(TK::TK_COMMA, ","); TESTTK(TK::TK_MINUS, "-"); TESTTK(TK::TK_PLUS, "+"); TESTTK(TK::TK_SEMI, ";"); TESTTK(TK::TK_SLASH, "/"); TESTTK(TK::TK_STAR, "*"); TESTTK(TK::TK_EQ, "="); TESTTK(TK::KW_FALSE, "false"); TESTTK(TK::KW_FN, "fn"); TESTTK(TK::KW_NIL, "nil"); TESTTK(TK::KW_TRUE, "true"); TESTTK(TK::KW_VAR, "var"); TESTTK(TK::TK_EOF, "EOF"); TESTTK(TK::TK_ERR, "ERR"); { // test for IDENTIFIER TESTID("foo"); TESTID("Foo"); TESTID("_foo"); TESTID("_Foo"); TESTID("__foo"); TESTID("__Foo"); TESTID("foo_"); TESTID("Foo_"); TESTID("foo__"); TESTID("Foo__"); TESTID("__foo__"); TESTID("__Foo__"); TESTID("foo1"); TESTID("Foo1"); TESTID("_foo1"); TESTID("_Foo1"); TESTID("__foo1"); TESTID("__Foo1"); TESTID("foo_1"); TESTID("Foo_1"); TESTID("foo__1"); TESTID("Foo__1"); TESTID("_foo_1"); TESTID("_Foo_1"); TESTID("__foo__1__Foo__1"); } { // test for NUMERIC TESTNUM(100); TESTNUM(-100); TESTNUM(1.2345); TESTNUM(-1.2345); TESTNUM(100.0); TESTNUM(-100.0); } { // test for STRING TESTSTR("111", 0); TESTSTR("Hello", 34); TESTSTR("COME BACK", 56); TESTSTR("============================", 89); TESTSTR("****************************", 91); TESTSTR("THIS IS A DUMMY STRING", 101); TESTSTR("TEST FOR TADPOLE TOKEN STRING", 137); } #undef TESTSTR #undef TESTNUM #undef TESTTK #undef TESTEQ #undef NEWTK3 #undef NEWTK2 } <|endoftext|>
<commit_before>/** \file apply_differential_update.cc * \brief A tool for applying a differential update to a complete MARC dump. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2018 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 <map> #include <stdexcept> #include <unordered_set> #include <cassert> #include <cstdlib> #include <cstring> #include "unistd.h" #include "Archive.h" #include "BSZUtil.h" #include "Compiler.h" #include "File.h" #include "FileUtil.h" #include "MARC.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--min-log-level=log_level] [--keep-intermediate-files] input_archive " << "difference_archive output_archive\n" << " Log levels are DEBUG, INFO, WARNING and ERROR with INFO being the default.\n\n"; std::exit(EXIT_FAILURE); } void CopyAndCollectPPNs(MARC::Reader * const reader, MARC::Writer * const writer, std::unordered_set<std::string> * const previously_seen_ppns) { while (auto record = reader->read()) { if (previously_seen_ppns->find(record.getControlNumber()) == previously_seen_ppns->end()) { previously_seen_ppns->emplace(record.getControlNumber()); if (record.getFirstField("ORI") == record.end()) record.appendField("ORI", FileUtil::GetLastPathComponent(reader->getPath())); writer->write(record); } } } void CopySelectedTypes(const std::vector<std::string> &archive_members, MARC::Writer * const writer, const std::set<BSZUtil::ArchiveType> &selected_types, std::unordered_set<std::string> * const previously_seen_ppns) { for (const auto &archive_member : archive_members) { if (selected_types.find(BSZUtil::GetArchiveType(archive_member)) != selected_types.cend()) { const auto reader(MARC::Reader::Factory(archive_member, MARC::FileType::BINARY)); CopyAndCollectPPNs(reader.get(), writer, previously_seen_ppns); } } } void PatchArchiveMembersAndCreateOutputArchive(const std::vector<std::string> &input_archive_members, const std::vector<std::string> &difference_archive_members, const std::string &output_archive) { if (input_archive_members.empty()) LOG_ERROR("no input archive members!"); if (difference_archive_members.empty()) LOG_WARNING("no difference archive members!"); // // We process title data first and combine all inferior and superior records. // const auto title_writer(MARC::Writer::Factory(output_archive + "/tit.mrc", MARC::FileType::BINARY)); std::unordered_set<std::string> previously_seen_title_ppns; CopySelectedTypes(difference_archive_members, title_writer.get(), { BSZUtil::TITLE_RECORDS, BSZUtil::SUPERIOR_TITLES }, &previously_seen_title_ppns); CopySelectedTypes(input_archive_members, title_writer.get(), { BSZUtil::TITLE_RECORDS, BSZUtil::SUPERIOR_TITLES }, &previously_seen_title_ppns); const auto authority_writer(MARC::Writer::Factory(output_archive + "/aut.mrc", MARC::FileType::BINARY)); std::unordered_set<std::string> previously_seen_authority_ppns; CopySelectedTypes(difference_archive_members, authority_writer.get(), { BSZUtil::AUTHORITY_RECORDS }, &previously_seen_authority_ppns); CopySelectedTypes(input_archive_members, authority_writer.get(), { BSZUtil::AUTHORITY_RECORDS }, &previously_seen_authority_ppns); } void GetDirectoryContentsWithRelativepath(const std::string &archive_name, std::vector<std::string> * const archive_members) { const std::string directory_name(archive_name); FileUtil::GetFileNameList(".(raw|mrc)$", archive_members, directory_name); for (auto &archive_member : *archive_members) archive_member = directory_name + "/" + archive_member; } std::string RemoveSuffix(const std::string &s, const std::string &suffix) { if (unlikely(not StringUtil::EndsWith(s, suffix))) LOG_ERROR("\"" + s + "\" does not end w/ \"" + suffix + "\"!"); return s.substr(0, s.length() - suffix.length()); } inline std::string StripTarGz(const std::string &archive_filename) { return RemoveSuffix(archive_filename, ".tar.gz"); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 4) Usage(); bool keep_intermediate_files(false); if (std::strcmp(argv[1], "--keep-intermediate-files") == 0) { keep_intermediate_files = true; --argc, ++argv; } if (argc != 4) Usage(); const std::string input_archive(FileUtil::MakeAbsolutePath(argv[1])); const std::string difference_archive(FileUtil::MakeAbsolutePath(argv[2])); const std::string output_archive(FileUtil::MakeAbsolutePath(argv[3])); if (input_archive == difference_archive or input_archive == output_archive or difference_archive == output_archive) LOG_ERROR("all archive names must be distinct!"); std::unique_ptr<FileUtil::AutoTempDirectory> working_directory; Archive::UnpackArchive(difference_archive, StripTarGz(difference_archive)); const auto directory_name(output_archive); if (not FileUtil::MakeDirectory(directory_name)) LOG_ERROR("failed to create directory: \"" + directory_name + "\"!"); std::vector<std::string> input_archive_members, difference_archive_members; GetDirectoryContentsWithRelativepath(input_archive, &input_archive_members); GetDirectoryContentsWithRelativepath(StripTarGz(difference_archive), &difference_archive_members); PatchArchiveMembersAndCreateOutputArchive(input_archive_members, difference_archive_members, output_archive); if (not keep_intermediate_files and not FileUtil::RemoveDirectory(difference_archive)) LOG_ERROR("failed to remove directory: \"" + difference_archive + "\"!"); return EXIT_SUCCESS; } <commit_msg>Fix adding ORI contents<commit_after>/** \file apply_differential_update.cc * \brief A tool for applying a differential update to a complete MARC dump. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2018 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 <map> #include <stdexcept> #include <unordered_set> #include <cassert> #include <cstdlib> #include <cstring> #include "unistd.h" #include "Archive.h" #include "BSZUtil.h" #include "Compiler.h" #include "File.h" #include "FileUtil.h" #include "MARC.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--min-log-level=log_level] [--keep-intermediate-files] input_archive " << "difference_archive output_archive\n" << " Log levels are DEBUG, INFO, WARNING and ERROR with INFO being the default.\n\n"; std::exit(EXIT_FAILURE); } void CopyAndCollectPPNs(MARC::Reader * const reader, MARC::Writer * const writer, std::unordered_set<std::string> * const previously_seen_ppns) { while (auto record = reader->read()) { if (previously_seen_ppns->find(record.getControlNumber()) == previously_seen_ppns->end()) { previously_seen_ppns->emplace(record.getControlNumber()); if (record.getFirstField("ORI") == record.end()) record.appendField("ORI", MARC::Subfields(MARC::Subfield('a', FileUtil::GetLastPathComponent(reader->getPath())).toString())); writer->write(record); } } } void CopySelectedTypes(const std::vector<std::string> &archive_members, MARC::Writer * const writer, const std::set<BSZUtil::ArchiveType> &selected_types, std::unordered_set<std::string> * const previously_seen_ppns) { for (const auto &archive_member : archive_members) { if (selected_types.find(BSZUtil::GetArchiveType(archive_member)) != selected_types.cend()) { const auto reader(MARC::Reader::Factory(archive_member, MARC::FileType::BINARY)); CopyAndCollectPPNs(reader.get(), writer, previously_seen_ppns); } } } void PatchArchiveMembersAndCreateOutputArchive(const std::vector<std::string> &input_archive_members, const std::vector<std::string> &difference_archive_members, const std::string &output_archive) { if (input_archive_members.empty()) LOG_ERROR("no input archive members!"); if (difference_archive_members.empty()) LOG_WARNING("no difference archive members!"); // // We process title data first and combine all inferior and superior records. // const auto title_writer(MARC::Writer::Factory(output_archive + "/tit.mrc", MARC::FileType::BINARY)); std::unordered_set<std::string> previously_seen_title_ppns; CopySelectedTypes(difference_archive_members, title_writer.get(), { BSZUtil::TITLE_RECORDS, BSZUtil::SUPERIOR_TITLES }, &previously_seen_title_ppns); CopySelectedTypes(input_archive_members, title_writer.get(), { BSZUtil::TITLE_RECORDS, BSZUtil::SUPERIOR_TITLES }, &previously_seen_title_ppns); const auto authority_writer(MARC::Writer::Factory(output_archive + "/aut.mrc", MARC::FileType::BINARY)); std::unordered_set<std::string> previously_seen_authority_ppns; CopySelectedTypes(difference_archive_members, authority_writer.get(), { BSZUtil::AUTHORITY_RECORDS }, &previously_seen_authority_ppns); CopySelectedTypes(input_archive_members, authority_writer.get(), { BSZUtil::AUTHORITY_RECORDS }, &previously_seen_authority_ppns); } void GetDirectoryContentsWithRelativepath(const std::string &archive_name, std::vector<std::string> * const archive_members) { const std::string directory_name(archive_name); FileUtil::GetFileNameList(".(raw|mrc)$", archive_members, directory_name); for (auto &archive_member : *archive_members) archive_member = directory_name + "/" + archive_member; } std::string RemoveSuffix(const std::string &s, const std::string &suffix) { if (unlikely(not StringUtil::EndsWith(s, suffix))) LOG_ERROR("\"" + s + "\" does not end w/ \"" + suffix + "\"!"); return s.substr(0, s.length() - suffix.length()); } inline std::string StripTarGz(const std::string &archive_filename) { return RemoveSuffix(archive_filename, ".tar.gz"); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 4) Usage(); bool keep_intermediate_files(false); if (std::strcmp(argv[1], "--keep-intermediate-files") == 0) { keep_intermediate_files = true; --argc, ++argv; } if (argc != 4) Usage(); const std::string input_archive(FileUtil::MakeAbsolutePath(argv[1])); const std::string difference_archive(FileUtil::MakeAbsolutePath(argv[2])); const std::string output_archive(FileUtil::MakeAbsolutePath(argv[3])); if (input_archive == difference_archive or input_archive == output_archive or difference_archive == output_archive) LOG_ERROR("all archive names must be distinct!"); std::unique_ptr<FileUtil::AutoTempDirectory> working_directory; Archive::UnpackArchive(difference_archive, StripTarGz(difference_archive)); const auto directory_name(output_archive); if (not FileUtil::MakeDirectory(directory_name)) LOG_ERROR("failed to create directory: \"" + directory_name + "\"!"); std::vector<std::string> input_archive_members, difference_archive_members; GetDirectoryContentsWithRelativepath(input_archive, &input_archive_members); GetDirectoryContentsWithRelativepath(StripTarGz(difference_archive), &difference_archive_members); PatchArchiveMembersAndCreateOutputArchive(input_archive_members, difference_archive_members, output_archive); if (not keep_intermediate_files and not FileUtil::RemoveDirectory(difference_archive)) LOG_ERROR("failed to remove directory: \"" + difference_archive + "\"!"); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*! \file * * \brief Python exports for module base classes * \author Benjamin Pritchard (ben@bennyp.org) */ #include "bpmodule/modulebase/All.hpp" #include "bpmodule/datastore/Wavefunction.hpp" #include "bpmodule/modulemanager/ModuleManager.hpp" using bpmodule::modulemanager::ModuleManager; using bpmodule::modulemanager::ModuleInfo; using bpmodule::datastore::OptionMap; namespace bpmodule { namespace modulebase { namespace export_python { template<typename T> using ModuleBasePtr = std::shared_ptr<T>; PYBIND11_PLUGIN(modulebase) { pybind11::module m("modulebase", "Base classes for all modules"); /////////////////////// // Module Base classes /////////////////////// // CallFunc doesn't need to be exported pybind11::class_<ModuleBase, ModuleBasePtr<ModuleBase>> mbase(m, "ModuleBase"); mbase.def("ID", &ModuleBase::ID) .def("Key", &ModuleBase::Key) .def("Name", &ModuleBase::Name) .def("Version", &ModuleBase::Version) .def("Print", &ModuleBase::Print) .def("Options", static_cast<OptionMap &(ModuleBase::*)(void)>(&ModuleBase::Options), pybind11::return_value_policy::reference_internal) .def("Wfn", static_cast<datastore::Wavefunction &(ModuleBase::*)(void)>(&ModuleBase::Wfn), pybind11::return_value_policy::reference_internal) .def("CreateChildModule", &ModuleBase::CreateChildModulePy) //.def("MManager", static_cast<ModuleManager &(ModuleBase::*)(void) const>(&ModuleBase::MManager), pybind11::return_value_policy::reference_internal) ; ///////////////////////// // Test class ///////////////////////// pybind11::class_<Test_Base_Py, ModuleBasePtr<Test_Base>> testbase(m, "Test_Base", mbase); testbase.alias<Test_Base>() .def(pybind11::init<unsigned long>()) .def("Cache", &Test_Base_Py::Cache, pybind11::return_value_policy::reference_internal) .def("RunTest", &Test_Base::RunTest) .def("CallRunTest", &Test_Base::CallRunTest) .def("TestThrow", &Test_Base::TestThrow) .def("CallThrow", &Test_Base::CallThrow) ; ///////////////////////// // System Fragmenters ///////////////////////// pybind11::class_<SystemFragmenter_Py, ModuleBasePtr<SystemFragmenter>> sysfrag(m, "SystemFragmenter", mbase); sysfrag.alias<SystemFragmenter>() .def(pybind11::init<unsigned long>()) .def("Fragmentize", &SystemFragmenter::Fragmentize) ; ///////////////////////// // One electron integral implementation ///////////////////////// //! \todo Don't know about from Calculate to python pybind11::class_<OneElectronIntegralIMPL_Py, ModuleBasePtr<OneElectronIntegralIMPL>> oneelimpl(m, "OneElectronIntegralIMPL", mbase); oneelimpl.alias<OneElectronIntegralIMPL>() .def(pybind11::init<unsigned long>()) .def("Cache", &OneElectronIntegralIMPL_Py::Cache, pybind11::return_value_policy::reference_internal) .def("SetBases", &OneElectronIntegralIMPL::SetBases) .def("Calculate", &OneElectronIntegralIMPL::Calculate) .def("GetIntegralCount", &OneElectronIntegralIMPL::GetIntegralCount) .def("GetBuf", &OneElectronIntegralIMPL::GetBufPy) ; /* ///////////////////////// // One electron integral builder ///////////////////////// register_ptr_to_python<boost::shared_ptr<OneElectronIntegral>>(); //! \todo Don't know about from Calculate to python class_<OneElectronIntegral, bases<ModuleBase>, boost::noncopyable>("OneElectronIntegral", init<PyObject *, unsigned long>()) .def("SetBases", &OneElectronIntegral::SetBases) .def("Calculate", &OneElectronIntegral::Calculate) .def("GetIntegralCount", &OneElectronIntegral::GetIntegralCount) .def("GetBuf", &OneElectronIntegral::GetBufPy) ; */ ///////////////////////// // Two electron integral implementation ///////////////////////// pybind11::class_<TwoElectronIntegralIMPL_Py, ModuleBasePtr<TwoElectronIntegralIMPL>> twoelimpl(m, "TwoElectronIntegralIMPL", mbase); twoelimpl.alias<TwoElectronIntegralIMPL>() .def(pybind11::init<unsigned long>()) .def("Cache", &TwoElectronIntegralIMPL_Py::Cache, pybind11::return_value_policy::reference_internal) .def("SetBases", &TwoElectronIntegralIMPL::SetBases) .def("Calculate", &TwoElectronIntegralIMPL::Calculate) .def("GetIntegralCount", &TwoElectronIntegralIMPL::GetIntegralCount) .def("GetBuf", &TwoElectronIntegralIMPL::GetBufPy) ; /* ///////////////////////// // Two electron integral builder ///////////////////////// register_ptr_to_python<boost::shared_ptr<TwoElectronIntegral>>(); class_<TwoElectronIntegral, bases<ModuleBase>, boost::noncopyable>("TwoElectronIntegral", init<PyObject *, unsigned long>()) .def("SetBases", &TwoElectronIntegral::SetBases) .def("Calculate", &TwoElectronIntegral::Calculate) .def("GetIntegralCount", &TwoElectronIntegral::GetIntegralCount) .def("GetBuf", &TwoElectronIntegral::GetBufPy) ; */ return m.ptr(); } } // close namespace export_python } // close namespace modulebase } // close namespace bpmodule <commit_msg>No need for declaring pointers to pybind11 for modules. This is handled by ModulePtr<commit_after>/*! \file * * \brief Python exports for module base classes * \author Benjamin Pritchard (ben@bennyp.org) */ #include "bpmodule/modulebase/All.hpp" #include "bpmodule/datastore/Wavefunction.hpp" #include "bpmodule/modulemanager/ModuleManager.hpp" using bpmodule::modulemanager::ModuleManager; using bpmodule::modulemanager::ModuleInfo; using bpmodule::datastore::OptionMap; namespace bpmodule { namespace modulebase { namespace export_python { PYBIND11_PLUGIN(modulebase) { pybind11::module m("modulebase", "Base classes for all modules"); /////////////////////// // Module Base classes /////////////////////// // CallFunc doesn't need to be exported pybind11::class_<ModuleBase> mbase(m, "ModuleBase"); mbase.def("ID", &ModuleBase::ID) .def("Key", &ModuleBase::Key) .def("Name", &ModuleBase::Name) .def("Version", &ModuleBase::Version) .def("Print", &ModuleBase::Print) .def("Options", static_cast<OptionMap &(ModuleBase::*)(void)>(&ModuleBase::Options), pybind11::return_value_policy::reference_internal) .def("Wfn", static_cast<datastore::Wavefunction &(ModuleBase::*)(void)>(&ModuleBase::Wfn), pybind11::return_value_policy::reference_internal) .def("CreateChildModule", &ModuleBase::CreateChildModulePy) //.def("MManager", static_cast<ModuleManager &(ModuleBase::*)(void) const>(&ModuleBase::MManager), pybind11::return_value_policy::reference_internal) ; ///////////////////////// // Test class ///////////////////////// pybind11::class_<Test_Base_Py> testbase(m, "Test_Base", mbase); testbase.alias<Test_Base>() .def(pybind11::init<unsigned long>()) .def("Cache", &Test_Base_Py::Cache, pybind11::return_value_policy::reference_internal) .def("RunTest", &Test_Base::RunTest) .def("CallRunTest", &Test_Base::CallRunTest) .def("TestThrow", &Test_Base::TestThrow) .def("CallThrow", &Test_Base::CallThrow) ; ///////////////////////// // System Fragmenters ///////////////////////// pybind11::class_<SystemFragmenter_Py> sysfrag(m, "SystemFragmenter", mbase); sysfrag.alias<SystemFragmenter>() .def(pybind11::init<unsigned long>()) .def("Fragmentize", &SystemFragmenter::Fragmentize) ; ///////////////////////// // One electron integral implementation ///////////////////////// //! \todo Don't know about from Calculate to python pybind11::class_<OneElectronIntegralIMPL_Py> oneelimpl(m, "OneElectronIntegralIMPL", mbase); oneelimpl.alias<OneElectronIntegralIMPL>() .def(pybind11::init<unsigned long>()) .def("Cache", &OneElectronIntegralIMPL_Py::Cache, pybind11::return_value_policy::reference_internal) .def("SetBases", &OneElectronIntegralIMPL::SetBases) .def("Calculate", &OneElectronIntegralIMPL::Calculate) .def("GetIntegralCount", &OneElectronIntegralIMPL::GetIntegralCount) .def("GetBuf", &OneElectronIntegralIMPL::GetBufPy) ; /* ///////////////////////// // One electron integral builder ///////////////////////// register_ptr_to_python<boost::shared_ptr<OneElectronIntegral>>(); //! \todo Don't know about from Calculate to python class_<OneElectronIntegral, bases<ModuleBase>, boost::noncopyable>("OneElectronIntegral", init<PyObject *, unsigned long>()) .def("SetBases", &OneElectronIntegral::SetBases) .def("Calculate", &OneElectronIntegral::Calculate) .def("GetIntegralCount", &OneElectronIntegral::GetIntegralCount) .def("GetBuf", &OneElectronIntegral::GetBufPy) ; */ ///////////////////////// // Two electron integral implementation ///////////////////////// pybind11::class_<TwoElectronIntegralIMPL_Py> twoelimpl(m, "TwoElectronIntegralIMPL", mbase); twoelimpl.alias<TwoElectronIntegralIMPL>() .def(pybind11::init<unsigned long>()) .def("Cache", &TwoElectronIntegralIMPL_Py::Cache, pybind11::return_value_policy::reference_internal) .def("SetBases", &TwoElectronIntegralIMPL::SetBases) .def("Calculate", &TwoElectronIntegralIMPL::Calculate) .def("GetIntegralCount", &TwoElectronIntegralIMPL::GetIntegralCount) .def("GetBuf", &TwoElectronIntegralIMPL::GetBufPy) ; /* ///////////////////////// // Two electron integral builder ///////////////////////// register_ptr_to_python<boost::shared_ptr<TwoElectronIntegral>>(); class_<TwoElectronIntegral, bases<ModuleBase>, boost::noncopyable>("TwoElectronIntegral", init<PyObject *, unsigned long>()) .def("SetBases", &TwoElectronIntegral::SetBases) .def("Calculate", &TwoElectronIntegral::Calculate) .def("GetIntegralCount", &TwoElectronIntegral::GetIntegralCount) .def("GetBuf", &TwoElectronIntegral::GetBufPy) ; */ return m.ptr(); } } // close namespace export_python } // close namespace modulebase } // close namespace bpmodule <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com> */ #pragma once #include <algorithm> #include <limits> #include <uavcan/stdint.hpp> #include <uavcan/error.hpp> #include <uavcan/transport/frame.hpp> #include <uavcan/linked_list.hpp> #include <uavcan/dynamic_memory.hpp> #include <uavcan/impl_constants.hpp> #include <uavcan/debug.hpp> namespace uavcan { UAVCAN_PACKED_BEGIN /** * API for transfer buffer users. */ class UAVCAN_EXPORT ITransferBuffer { public: virtual ~ITransferBuffer() { } virtual int read(unsigned offset, uint8_t* data, unsigned len) const = 0; virtual int write(unsigned offset, const uint8_t* data, unsigned len) = 0; }; /** * Internal for TransferBufferManager */ class UAVCAN_EXPORT TransferBufferManagerKey { NodeID node_id_; uint8_t transfer_type_; public: TransferBufferManagerKey() : transfer_type_(TransferType(0)) { assert(isEmpty()); } TransferBufferManagerKey(NodeID node_id, TransferType ttype) : node_id_(node_id) , transfer_type_(ttype) { assert(!isEmpty()); } bool operator==(const TransferBufferManagerKey& rhs) const { return node_id_ == rhs.node_id_ && transfer_type_ == rhs.transfer_type_; } bool isEmpty() const { return !node_id_.isValid(); } NodeID getNodeID() const { return node_id_; } TransferType getTransferType() const { return TransferType(transfer_type_); } #if UAVCAN_TOSTRING std::string toString() const; #endif }; /** * Internal for TransferBufferManager */ class UAVCAN_EXPORT TransferBufferManagerEntry : public ITransferBuffer, Noncopyable { TransferBufferManagerKey key_; protected: virtual void resetImpl() = 0; public: TransferBufferManagerEntry() { } TransferBufferManagerEntry(const TransferBufferManagerKey& key) : key_(key) { } const TransferBufferManagerKey& getKey() const { return key_; } bool isEmpty() const { return key_.isEmpty(); } void reset(const TransferBufferManagerKey& key = TransferBufferManagerKey()) { key_ = key; resetImpl(); } }; /** * Resizable gather/scatter storage. * reset() call releases all memory blocks. * Supports unordered write operations - from higher to lower offsets */ class UAVCAN_EXPORT DynamicTransferBufferManagerEntry : public TransferBufferManagerEntry , public LinkedListNode<DynamicTransferBufferManagerEntry> { struct Block : LinkedListNode<Block> { enum { Size = MemPoolBlockSize - sizeof(LinkedListNode<Block>) }; uint8_t data[Size]; static Block* instantiate(IPoolAllocator& allocator); static void destroy(Block*& obj, IPoolAllocator& allocator); void read(uint8_t*& outptr, unsigned target_offset, unsigned& total_offset, unsigned& left_to_read); void write(const uint8_t*& inptr, unsigned target_offset, unsigned& total_offset, unsigned& left_to_write); }; IPoolAllocator& allocator_; LinkedListRoot<Block> blocks_; // Blocks are ordered from lower to higher buffer offset uint16_t max_write_pos_; const uint16_t max_size_; void resetImpl(); public: DynamicTransferBufferManagerEntry(IPoolAllocator& allocator, uint16_t max_size) : allocator_(allocator) , max_write_pos_(0) , max_size_(max_size) { StaticAssert<(Block::Size > 8)>::check(); IsDynamicallyAllocatable<Block>::check(); IsDynamicallyAllocatable<DynamicTransferBufferManagerEntry>::check(); } ~DynamicTransferBufferManagerEntry() { resetImpl(); } static DynamicTransferBufferManagerEntry* instantiate(IPoolAllocator& allocator, uint16_t max_size); static void destroy(DynamicTransferBufferManagerEntry*& obj, IPoolAllocator& allocator); int read(unsigned offset, uint8_t* data, unsigned len) const; int write(unsigned offset, const uint8_t* data, unsigned len); }; UAVCAN_PACKED_END /** * Standalone static buffer */ class StaticTransferBufferImpl : public ITransferBuffer { uint8_t* const data_; const uint16_t size_; uint16_t max_write_pos_; public: StaticTransferBufferImpl(uint8_t* buf, uint16_t buf_size) : data_(buf) , size_(buf_size) , max_write_pos_(0) { } int read(unsigned offset, uint8_t* data, unsigned len) const; int write(unsigned offset, const uint8_t* data, unsigned len); void reset(); uint16_t getSize() const { return size_; } uint8_t* getRawPtr() { return data_; } const uint8_t* getRawPtr() const { return data_; } uint16_t getMaxWritePos() const { return max_write_pos_; } void setMaxWritePos(uint16_t value) { max_write_pos_ = value; } }; template <uint16_t Size> class UAVCAN_EXPORT StaticTransferBuffer : public StaticTransferBufferImpl { uint8_t buffer_[Size]; public: StaticTransferBuffer() : StaticTransferBufferImpl(buffer_, Size) { StaticAssert<(Size > 0)>::check(); } }; /** * Statically allocated storage for the buffer manager */ class StaticTransferBufferManagerEntryImpl : public TransferBufferManagerEntry { StaticTransferBufferImpl buf_; void resetImpl(); public: StaticTransferBufferManagerEntryImpl(uint8_t* buf, uint16_t buf_size) : buf_(buf, buf_size) { } int read(unsigned offset, uint8_t* data, unsigned len) const; int write(unsigned offset, const uint8_t* data, unsigned len); bool migrateFrom(const TransferBufferManagerEntry* tbme); }; template <uint16_t Size> class UAVCAN_EXPORT StaticTransferBufferManagerEntry : public StaticTransferBufferManagerEntryImpl { uint8_t buffer_[Size]; public: StaticTransferBufferManagerEntry() : StaticTransferBufferManagerEntryImpl(buffer_, Size) { } }; /** * Manages different storage types (static/dynamic) for transfer reception logic. */ class UAVCAN_EXPORT ITransferBufferManager { public: virtual ~ITransferBufferManager() { } virtual ITransferBuffer* access(const TransferBufferManagerKey& key) = 0; virtual ITransferBuffer* create(const TransferBufferManagerKey& key) = 0; virtual void remove(const TransferBufferManagerKey& key) = 0; virtual bool isEmpty() const = 0; }; /** * Convinience class. */ class UAVCAN_EXPORT TransferBufferAccessor { ITransferBufferManager& bufmgr_; const TransferBufferManagerKey key_; public: TransferBufferAccessor(ITransferBufferManager& bufmgr, TransferBufferManagerKey key) : bufmgr_(bufmgr) , key_(key) { assert(!key.isEmpty()); } ITransferBuffer* access() { return bufmgr_.access(key_); } ITransferBuffer* create() { return bufmgr_.create(key_); } void remove() { bufmgr_.remove(key_); } }; /** * Buffer manager implementation. */ class TransferBufferManagerImpl : public ITransferBufferManager, Noncopyable { LinkedListRoot<DynamicTransferBufferManagerEntry> dynamic_buffers_; IPoolAllocator& allocator_; const uint16_t max_buf_size_; virtual StaticTransferBufferManagerEntryImpl* getStaticByIndex(uint16_t index) const = 0; StaticTransferBufferManagerEntryImpl* findFirstStatic(const TransferBufferManagerKey& key); DynamicTransferBufferManagerEntry* findFirstDynamic(const TransferBufferManagerKey& key); void optimizeStorage(); public: TransferBufferManagerImpl(uint16_t max_buf_size, IPoolAllocator& allocator) : allocator_(allocator) , max_buf_size_(max_buf_size) { } ~TransferBufferManagerImpl(); ITransferBuffer* access(const TransferBufferManagerKey& key); ITransferBuffer* create(const TransferBufferManagerKey& key); void remove(const TransferBufferManagerKey& key); bool isEmpty() const; unsigned getNumDynamicBuffers() const; unsigned getNumStaticBuffers() const; }; template <uint16_t MaxBufSize, uint8_t NumStaticBufs> class UAVCAN_EXPORT TransferBufferManager : public TransferBufferManagerImpl { mutable StaticTransferBufferManagerEntry<MaxBufSize> static_buffers_[NumStaticBufs]; // TODO: zero buffers support StaticTransferBufferManagerEntry<MaxBufSize>* getStaticByIndex(uint16_t index) const { return (index < NumStaticBufs) ? &static_buffers_[index] : NULL; } public: TransferBufferManager(IPoolAllocator& allocator) : TransferBufferManagerImpl(MaxBufSize, allocator) { StaticAssert<(MaxBufSize > 0)>::check(); } }; template <> class UAVCAN_EXPORT TransferBufferManager<0, 0> : public ITransferBufferManager { public: TransferBufferManager() { } TransferBufferManager(IPoolAllocator&) { } ITransferBuffer* access(const TransferBufferManagerKey&) { return NULL; } ITransferBuffer* create(const TransferBufferManagerKey&) { return NULL; } void remove(const TransferBufferManagerKey&) { } bool isEmpty() const { return true; } }; } <commit_msg>Support for zero static buffers<commit_after>/* * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com> */ #pragma once #include <algorithm> #include <limits> #include <uavcan/stdint.hpp> #include <uavcan/error.hpp> #include <uavcan/transport/frame.hpp> #include <uavcan/linked_list.hpp> #include <uavcan/dynamic_memory.hpp> #include <uavcan/impl_constants.hpp> #include <uavcan/debug.hpp> namespace uavcan { UAVCAN_PACKED_BEGIN /** * API for transfer buffer users. */ class UAVCAN_EXPORT ITransferBuffer { public: virtual ~ITransferBuffer() { } virtual int read(unsigned offset, uint8_t* data, unsigned len) const = 0; virtual int write(unsigned offset, const uint8_t* data, unsigned len) = 0; }; /** * Internal for TransferBufferManager */ class UAVCAN_EXPORT TransferBufferManagerKey { NodeID node_id_; uint8_t transfer_type_; public: TransferBufferManagerKey() : transfer_type_(TransferType(0)) { assert(isEmpty()); } TransferBufferManagerKey(NodeID node_id, TransferType ttype) : node_id_(node_id) , transfer_type_(ttype) { assert(!isEmpty()); } bool operator==(const TransferBufferManagerKey& rhs) const { return node_id_ == rhs.node_id_ && transfer_type_ == rhs.transfer_type_; } bool isEmpty() const { return !node_id_.isValid(); } NodeID getNodeID() const { return node_id_; } TransferType getTransferType() const { return TransferType(transfer_type_); } #if UAVCAN_TOSTRING std::string toString() const; #endif }; /** * Internal for TransferBufferManager */ class UAVCAN_EXPORT TransferBufferManagerEntry : public ITransferBuffer, Noncopyable { TransferBufferManagerKey key_; protected: virtual void resetImpl() = 0; public: TransferBufferManagerEntry() { } TransferBufferManagerEntry(const TransferBufferManagerKey& key) : key_(key) { } const TransferBufferManagerKey& getKey() const { return key_; } bool isEmpty() const { return key_.isEmpty(); } void reset(const TransferBufferManagerKey& key = TransferBufferManagerKey()) { key_ = key; resetImpl(); } }; /** * Resizable gather/scatter storage. * reset() call releases all memory blocks. * Supports unordered write operations - from higher to lower offsets */ class UAVCAN_EXPORT DynamicTransferBufferManagerEntry : public TransferBufferManagerEntry , public LinkedListNode<DynamicTransferBufferManagerEntry> { struct Block : LinkedListNode<Block> { enum { Size = MemPoolBlockSize - sizeof(LinkedListNode<Block>) }; uint8_t data[Size]; static Block* instantiate(IPoolAllocator& allocator); static void destroy(Block*& obj, IPoolAllocator& allocator); void read(uint8_t*& outptr, unsigned target_offset, unsigned& total_offset, unsigned& left_to_read); void write(const uint8_t*& inptr, unsigned target_offset, unsigned& total_offset, unsigned& left_to_write); }; IPoolAllocator& allocator_; LinkedListRoot<Block> blocks_; // Blocks are ordered from lower to higher buffer offset uint16_t max_write_pos_; const uint16_t max_size_; void resetImpl(); public: DynamicTransferBufferManagerEntry(IPoolAllocator& allocator, uint16_t max_size) : allocator_(allocator) , max_write_pos_(0) , max_size_(max_size) { StaticAssert<(Block::Size > 8)>::check(); IsDynamicallyAllocatable<Block>::check(); IsDynamicallyAllocatable<DynamicTransferBufferManagerEntry>::check(); } ~DynamicTransferBufferManagerEntry() { resetImpl(); } static DynamicTransferBufferManagerEntry* instantiate(IPoolAllocator& allocator, uint16_t max_size); static void destroy(DynamicTransferBufferManagerEntry*& obj, IPoolAllocator& allocator); int read(unsigned offset, uint8_t* data, unsigned len) const; int write(unsigned offset, const uint8_t* data, unsigned len); }; UAVCAN_PACKED_END /** * Standalone static buffer */ class StaticTransferBufferImpl : public ITransferBuffer { uint8_t* const data_; const uint16_t size_; uint16_t max_write_pos_; public: StaticTransferBufferImpl(uint8_t* buf, uint16_t buf_size) : data_(buf) , size_(buf_size) , max_write_pos_(0) { } int read(unsigned offset, uint8_t* data, unsigned len) const; int write(unsigned offset, const uint8_t* data, unsigned len); void reset(); uint16_t getSize() const { return size_; } uint8_t* getRawPtr() { return data_; } const uint8_t* getRawPtr() const { return data_; } uint16_t getMaxWritePos() const { return max_write_pos_; } void setMaxWritePos(uint16_t value) { max_write_pos_ = value; } }; template <uint16_t Size> class UAVCAN_EXPORT StaticTransferBuffer : public StaticTransferBufferImpl { uint8_t buffer_[Size]; public: StaticTransferBuffer() : StaticTransferBufferImpl(buffer_, Size) { StaticAssert<(Size > 0)>::check(); } }; /** * Statically allocated storage for the buffer manager */ class StaticTransferBufferManagerEntryImpl : public TransferBufferManagerEntry { StaticTransferBufferImpl buf_; void resetImpl(); public: StaticTransferBufferManagerEntryImpl(uint8_t* buf, uint16_t buf_size) : buf_(buf, buf_size) { } int read(unsigned offset, uint8_t* data, unsigned len) const; int write(unsigned offset, const uint8_t* data, unsigned len); bool migrateFrom(const TransferBufferManagerEntry* tbme); }; template <uint16_t Size> class UAVCAN_EXPORT StaticTransferBufferManagerEntry : public StaticTransferBufferManagerEntryImpl { uint8_t buffer_[Size]; public: StaticTransferBufferManagerEntry() : StaticTransferBufferManagerEntryImpl(buffer_, Size) { } }; /** * Manages different storage types (static/dynamic) for transfer reception logic. */ class UAVCAN_EXPORT ITransferBufferManager { public: virtual ~ITransferBufferManager() { } virtual ITransferBuffer* access(const TransferBufferManagerKey& key) = 0; virtual ITransferBuffer* create(const TransferBufferManagerKey& key) = 0; virtual void remove(const TransferBufferManagerKey& key) = 0; virtual bool isEmpty() const = 0; }; /** * Convinience class. */ class UAVCAN_EXPORT TransferBufferAccessor { ITransferBufferManager& bufmgr_; const TransferBufferManagerKey key_; public: TransferBufferAccessor(ITransferBufferManager& bufmgr, TransferBufferManagerKey key) : bufmgr_(bufmgr) , key_(key) { assert(!key.isEmpty()); } ITransferBuffer* access() { return bufmgr_.access(key_); } ITransferBuffer* create() { return bufmgr_.create(key_); } void remove() { bufmgr_.remove(key_); } }; /** * Buffer manager implementation. */ class TransferBufferManagerImpl : public ITransferBufferManager, Noncopyable { LinkedListRoot<DynamicTransferBufferManagerEntry> dynamic_buffers_; IPoolAllocator& allocator_; const uint16_t max_buf_size_; virtual StaticTransferBufferManagerEntryImpl* getStaticByIndex(uint16_t index) const = 0; StaticTransferBufferManagerEntryImpl* findFirstStatic(const TransferBufferManagerKey& key); DynamicTransferBufferManagerEntry* findFirstDynamic(const TransferBufferManagerKey& key); void optimizeStorage(); public: TransferBufferManagerImpl(uint16_t max_buf_size, IPoolAllocator& allocator) : allocator_(allocator) , max_buf_size_(max_buf_size) { } ~TransferBufferManagerImpl(); ITransferBuffer* access(const TransferBufferManagerKey& key); ITransferBuffer* create(const TransferBufferManagerKey& key); void remove(const TransferBufferManagerKey& key); bool isEmpty() const; unsigned getNumDynamicBuffers() const; unsigned getNumStaticBuffers() const; }; template <uint16_t MaxBufSize, uint8_t NumStaticBufs> class UAVCAN_EXPORT TransferBufferManager : public TransferBufferManagerImpl { mutable StaticTransferBufferManagerEntry<MaxBufSize> static_buffers_[NumStaticBufs]; StaticTransferBufferManagerEntry<MaxBufSize>* getStaticByIndex(uint16_t index) const { return (index < NumStaticBufs) ? &static_buffers_[index] : NULL; } public: TransferBufferManager(IPoolAllocator& allocator) : TransferBufferManagerImpl(MaxBufSize, allocator) { StaticAssert<(MaxBufSize > 0)>::check(); } }; template <uint16_t MaxBufSize> class UAVCAN_EXPORT TransferBufferManager<MaxBufSize, 0> : public TransferBufferManagerImpl { StaticTransferBufferManagerEntry<MaxBufSize>* getStaticByIndex(uint16_t index) const { return NULL; } public: TransferBufferManager(IPoolAllocator& allocator) : TransferBufferManagerImpl(MaxBufSize, allocator) { StaticAssert<(MaxBufSize > 0)>::check(); } }; template <> class UAVCAN_EXPORT TransferBufferManager<0, 0> : public ITransferBufferManager { public: TransferBufferManager() { } TransferBufferManager(IPoolAllocator&) { } ITransferBuffer* access(const TransferBufferManagerKey&) { return NULL; } ITransferBuffer* create(const TransferBufferManagerKey&) { return NULL; } void remove(const TransferBufferManagerKey&) { } bool isEmpty() const { return true; } }; } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief MAX7219 ドライバー Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include <cstring> #include "common/iica_io.hpp" #include "common/time.h" namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief MAX7219 テンプレートクラス @param[in] SPI SPI クラス @param[in] SELECT デバイス選択 @param[in] CHAIN デージー・チェイン数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class SPI, class SELECT, uint32_t CHAIN = 1> class MAX7219 { SPI& spi_; uint16_t limit_; uint8_t data_[CHAIN * 8]; enum class command : uint8_t { NO_OP = 0x00, DIGIT_0 = 0x01, DIGIT_1 = 0x02, DIGIT_2 = 0x03, DIGIT_3 = 0x04, DIGIT_4 = 0x05, DIGIT_5 = 0x06, DIGIT_6 = 0x07, DIGIT_7 = 0x08, DECODE_MODE = 0x09, INTENSITY = 0x0A, SCAN_LIMIT = 0x0B, SHUTDOWN = 0x0C, DISPLAY_TEST = 0x0F, }; // MAX7212 MSB first, 2 bytes void out_(command cmd, uint8_t dat) { SELECT::P = 0; uint8_t tmp[2]; tmp[0] = static_cast<uint8_t>(cmd); tmp[1] = dat; spi_.send(tmp, 2); SELECT::P = 1; // load } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] spi SPI クラスを参照で渡す */ //-----------------------------------------------------------------// MAX7219(SPI& spi) : spi_(spi), limit_(0) { } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] limit スキャン・リミット @return エラーなら「false」を返す */ //-----------------------------------------------------------------// bool start(uint8_t limit = (CHAIN * 8)) { if(limit_ > (8 * CHAIN) || limit == 0) { return false; } limit_ = limit; SELECT::DIR = 1; // output; SELECT::PU = 0; // pull-up disable SELECT::P = 1; // /CS = H for(uint8_t i = 0; i < sizeof(data_); ++i) { data_[i] = 0; } out_(command::SHUTDOWN, 0x01); // ノーマル・モード out_(command::DECODE_MODE, 0x00); // デコード・モード out_(command::SCAN_LIMIT, limit - 1); // 表示桁設定 set_intensity(0); // 輝度(最低) service(); return true; } //-----------------------------------------------------------------// /*! @brief 輝度の設定 @param[in] inten 輝度値(最小:0、最大:15) @return エラー(初期化不良)なら「false」 */ //-----------------------------------------------------------------// bool set_intensity(uint8_t inten) { if(limit_ == 0) return false; out_(command::INTENSITY, inten); return true; } //-----------------------------------------------------------------// /*! @brief データ転送 @return エラー(初期化不良)なら「false」 */ //-----------------------------------------------------------------// bool service() { if(limit_ == 0) return false; for(uint8_t i = 0; i < limit_; ++i) { out_(static_cast<command>(static_cast<uint8_t>(command::DIGIT_0) + i), data_[i]); } return true; } //-----------------------------------------------------------------// /*! @brief 値の取得 @param[in] idx インデックス(0~7) @return 値 */ //-----------------------------------------------------------------// uint8_t get(uint8_t idx) { if(idx < limit_) { return data_[idx]; } return 0; } //-----------------------------------------------------------------// /*! @brief 値の設定 @param[in] idx インデックス(0~7) @param[in] dat データ */ //-----------------------------------------------------------------// void set(uint8_t idx, uint8_t dat) { if(idx < limit_) { data_[idx] = dat; } } //-----------------------------------------------------------------// /*! @brief キャラクターの設定 @param[in] idx インデックス(0~7) @param[in] cha キャラクターコード @param[in] dp 小数点 */ //-----------------------------------------------------------------// void set_cha(uint8_t idx, char cha, bool dp = false) { uint8_t d = 0; switch(cha) { case ' ': break; case '-': d = 0b0000001; break; case '_': d = 0b0001000; break; case '~': d = 0b1000000; break; case '0': d = 0b1111110; break; case '1': d = 0b0110000; break; case '2': d = 0b1101101; break; case '3': d = 0b1111001; break; case '4': d = 0b0110011; break; case '5': d = 0b1011011; break; case '6': d = 0b1011111; break; case '7': d = 0b1110000; break; case '8': d = 0b1111111; break; case '9': d = 0b1111011; break; case 'A': case 'a': d = 0b1110111; break; case 'B': case 'b': d = 0b0011111; break; case 'C': d = 0b1001110; break; case 'c': d = 0b0001101; break; case 'D': case 'd': d = 0b0111101; break; case 'E': case 'e': d = 0b1001111; break; case 'F': case 'f': d = 0b1000111; break; case 'G': case 'g': d = 0b1011110; break; case 'H': case 'h': d = 0b0010111; break; case 'I': case 'i': d = 0b0000100; break; case 'J': case 'j': d = 0b0111100; break; case 'K': case 'k': d = 0b1010111; break; case 'L': case 'l': d = 0b0001110; break; case 'M': case 'm': d = 0b1110110; break; case 'N': case 'n': d = 0b0010101; break; case 'O': case 'o': d = 0b0011101; break; case 'P': case 'p': d = 0b1100111; break; case 'Q': case 'q': d = 0b1101111; break; case 'R': case 'r': d = 0b0000101; break; case 'S': case 's': d = 0b0011011; break; case 'T': case 't': d = 0b0001111; break; case 'U': case 'u': d = 0b0011100; break; case 'V': case 'v': d = 0b0111110; break; case 'W': case 'w': d = 0b0111111; break; case 'X': case 'x': d = 0b0110111; break; case 'Y': case 'y': d = 0b0111011; break; case 'Z': case 'z': d = 0b1101100; break; default: break; } if(dp) d |= 0x80; set(idx, d); } //-----------------------------------------------------------------// /*! @brief シフト、バッファ先頭 @param[in] fill 埋めるデータ */ //-----------------------------------------------------------------// uint8_t shift_top(uint8_t fill = 0) { uint8_t full = data_[0]; std::memmove(&data_[1], &data_[0], 7); data_[0] = fill; return full; } //-----------------------------------------------------------------// /*! @brief シフト、バッファ終端 @param[in] fill 埋めるデータ */ //-----------------------------------------------------------------// uint8_t shift_end(uint8_t fill = 0) { uint8_t full = data_[7]; std::memmove(&data_[0], &data_[1], 7); data_[7] = fill; return full; } }; } <commit_msg>update spi_io template param<commit_after>#pragma once //=====================================================================// /*! @file @brief MAX7219 ドライバー Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include <cstring> #include "common/iica_io.hpp" #include "common/time.h" namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief MAX7219 テンプレートクラス @param[in] SPI SPI クラス @param[in] SELECT デバイス選択 @param[in] CHAIN デージー・チェイン数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class SPI, class SELECT, uint32_t CHAIN = 1> class MAX7219 { SPI& spi_; uint16_t limit_; uint8_t data_[CHAIN * 8]; enum class command : uint8_t { NO_OP = 0x00, DIGIT_0 = 0x01, DIGIT_1 = 0x02, DIGIT_2 = 0x03, DIGIT_3 = 0x04, DIGIT_4 = 0x05, DIGIT_5 = 0x06, DIGIT_6 = 0x07, DIGIT_7 = 0x08, DECODE_MODE = 0x09, INTENSITY = 0x0A, SCAN_LIMIT = 0x0B, SHUTDOWN = 0x0C, DISPLAY_TEST = 0x0F, }; // MAX7212 MSB first, 2 bytes void out_(command cmd, uint8_t dat) { SELECT::P = 0; uint8_t tmp[2]; tmp[0] = static_cast<uint8_t>(cmd); tmp[1] = dat; spi_.xchg(tmp[0]); spi_.xchg(tmp[1]); // spi_.send(tmp, 2); SELECT::P = 1; // load } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] spi SPI クラスを参照で渡す */ //-----------------------------------------------------------------// MAX7219(SPI& spi) : spi_(spi), limit_(0) { } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] limit スキャン・リミット @return エラーなら「false」を返す */ //-----------------------------------------------------------------// bool start(uint8_t limit = (CHAIN * 8)) { if(limit_ > (8 * CHAIN) || limit == 0) { return false; } limit_ = limit; SELECT::DIR = 1; // output; SELECT::PU = 0; // pull-up disable SELECT::P = 1; // /CS = H for(uint8_t i = 0; i < sizeof(data_); ++i) { data_[i] = 0; } out_(command::SHUTDOWN, 0x01); // ノーマル・モード out_(command::DECODE_MODE, 0x00); // デコード・モード out_(command::SCAN_LIMIT, limit - 1); // 表示桁設定 set_intensity(0); // 輝度(最低) service(); return true; } //-----------------------------------------------------------------// /*! @brief 輝度の設定 @param[in] inten 輝度値(最小:0、最大:15) @return エラー(初期化不良)なら「false」 */ //-----------------------------------------------------------------// bool set_intensity(uint8_t inten) { if(limit_ == 0) return false; out_(command::INTENSITY, inten); return true; } //-----------------------------------------------------------------// /*! @brief データ転送 @return エラー(初期化不良)なら「false」 */ //-----------------------------------------------------------------// bool service() { if(limit_ == 0) return false; for(uint8_t i = 0; i < limit_; ++i) { out_(static_cast<command>(static_cast<uint8_t>(command::DIGIT_0) + i), data_[i]); } return true; } //-----------------------------------------------------------------// /*! @brief 値の取得 @param[in] idx インデックス(0~7) @return 値 */ //-----------------------------------------------------------------// uint8_t get(uint8_t idx) { if(idx < limit_) { return data_[idx]; } return 0; } //-----------------------------------------------------------------// /*! @brief 値の設定 @param[in] idx インデックス(0~7) @param[in] dat データ */ //-----------------------------------------------------------------// void set(uint8_t idx, uint8_t dat) { if(idx < limit_) { data_[idx] = dat; } } //-----------------------------------------------------------------// /*! @brief キャラクターの設定 @param[in] idx インデックス(0~7) @param[in] cha キャラクターコード @param[in] dp 小数点 */ //-----------------------------------------------------------------// void set_cha(uint8_t idx, char cha, bool dp = false) { uint8_t d = 0; switch(cha) { case ' ': break; case '-': d = 0b0000001; break; case '_': d = 0b0001000; break; case '~': d = 0b1000000; break; case '0': d = 0b1111110; break; case '1': d = 0b0110000; break; case '2': d = 0b1101101; break; case '3': d = 0b1111001; break; case '4': d = 0b0110011; break; case '5': d = 0b1011011; break; case '6': d = 0b1011111; break; case '7': d = 0b1110000; break; case '8': d = 0b1111111; break; case '9': d = 0b1111011; break; case 'A': case 'a': d = 0b1110111; break; case 'B': case 'b': d = 0b0011111; break; case 'C': d = 0b1001110; break; case 'c': d = 0b0001101; break; case 'D': case 'd': d = 0b0111101; break; case 'E': case 'e': d = 0b1001111; break; case 'F': case 'f': d = 0b1000111; break; case 'G': case 'g': d = 0b1011110; break; case 'H': case 'h': d = 0b0010111; break; case 'I': case 'i': d = 0b0000100; break; case 'J': case 'j': d = 0b0111100; break; case 'K': case 'k': d = 0b1010111; break; case 'L': case 'l': d = 0b0001110; break; case 'M': case 'm': d = 0b1110110; break; case 'N': case 'n': d = 0b0010101; break; case 'O': case 'o': d = 0b0011101; break; case 'P': case 'p': d = 0b1100111; break; case 'Q': case 'q': d = 0b1101111; break; case 'R': case 'r': d = 0b0000101; break; case 'S': case 's': d = 0b0011011; break; case 'T': case 't': d = 0b0001111; break; case 'U': case 'u': d = 0b0011100; break; case 'V': case 'v': d = 0b0111110; break; case 'W': case 'w': d = 0b0111111; break; case 'X': case 'x': d = 0b0110111; break; case 'Y': case 'y': d = 0b0111011; break; case 'Z': case 'z': d = 0b1101100; break; default: break; } if(dp) d |= 0x80; set(idx, d); } //-----------------------------------------------------------------// /*! @brief シフト、バッファ先頭 @param[in] fill 埋めるデータ */ //-----------------------------------------------------------------// uint8_t shift_top(uint8_t fill = 0) { uint8_t full = data_[0]; std::memmove(&data_[1], &data_[0], 7); data_[0] = fill; return full; } //-----------------------------------------------------------------// /*! @brief シフト、バッファ終端 @param[in] fill 埋めるデータ */ //-----------------------------------------------------------------// uint8_t shift_end(uint8_t fill = 0) { uint8_t full = data_[7]; std::memmove(&data_[0], &data_[1], 7); data_[7] = fill; return full; } }; } <|endoftext|>
<commit_before>/* * Copyright (c) 2009, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "StringLengthRenderer.h" #include "Dbg.h" RegisterRenderer(StringLengthRenderer); void StringLengthRenderer::RenderAll(std::ostream &reply, Context &ctx, const ROAnything &config) { StartTrace(StringLengthRenderer.RenderAll); ROAnything roaSlotConfig; String strValue, strLength; if (config.LookupPath(roaSlotConfig, "Value")) { RenderOnString(strValue, ctx, roaSlotConfig); } else { Trace("Error in StringLengthRenderer::RenderAll, Value not defined"); reply << ""; return; } Trace("Value: [" << strValue << "]"); reply << strValue.Length(); } <commit_msg>changed to using whole config if Value slot not given<commit_after>/* * Copyright (c) 2009, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "StringLengthRenderer.h" RegisterRenderer(StringLengthRenderer); void StringLengthRenderer::RenderAll(std::ostream &reply, Context &ctx, const ROAnything &config) { StartTrace(StringLengthRenderer.RenderAll); ROAnything roaSlotConfig; String strValue; if (config.LookupPath(roaSlotConfig, "Value")) { RenderOnString(strValue, ctx, roaSlotConfig); } else { RenderOnString(strValue, ctx, config); } Trace("Value: [" << strValue << "]"); reply << strValue.Length(); } <|endoftext|>
<commit_before>/* * * This source file is a part of the Berlin Project. * Copyright (C) 2002 Tobias Hunger <tobias@fresco.org> * http://www.fresco.org * * 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; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #include <Prague/Sys/Env.hh> #include <Prague/config.hh> #include <iostream> #ifndef HAVE_SETENV #ifdef HAVE_PUTENV #include <map> namespace Prague { namespace Environment { std::map<std::string, char *> my_vars; }; }; #endif #endif bool Prague::putenv(const std::string & name, const std::string & value) { #ifdef HAVE_SETENV return setenv(name.c_str(), value.c_str(), 1) == 0; #elif HAVE_PUTENV char * env_var = new char[name.length() + value.length() + 2]; strncpy(env_var, name.c_str(), name.length()); env_var[name.length()] = '='; strncpy((env_var + name.length() + 1), value.c_str(), value.length()); env_var[name.length() + value.length() + 1] = '\0'; // make sure there's a \0 if (::putenv(env_var) == 0) { Environment::my_vars[name] = env_var; return true; } #else std::cerr << "ERROR: Prague::putenv misconfiguration!" << std::endl; exit(1); #endif return false; } bool Prague::putenv(const std::string & name) { #ifdef HAVE_UNSETENV return unsetenv(name.c_str()); #elif HAVE_PUTENV char * env_var = new char[name.length() + 1]; strncpy(env_var, name.c_str(), name.length()); env_var[name.length()] = '\0'; // make sure there's a \0 if (::putenv(env_var) == 0) { if (Environment::my_vars[name] != 0) delete[] Environment::my_vars[name]; Environment::my_vars.erase(name); // it was either there or // just got created. return true; } #else std::cerr << "ERROR: Prague::putenv misconfiguration!" << std::endl; exit(1); #endif return false; } std::string Prague::getenv(const std::string & name) { char const * const s = ::getenv(name.c_str()); std::string const value((s!=0)?s:""); return value; } <commit_msg>unsetenv doesn't return anything<commit_after>/* * * This source file is a part of the Berlin Project. * Copyright (C) 2002 Tobias Hunger <tobias@fresco.org> * http://www.fresco.org * * 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; if not, write to the * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, * MA 02139, USA. */ #include <Prague/Sys/Env.hh> #include <Prague/config.hh> #include <iostream> #ifndef HAVE_SETENV #ifdef HAVE_PUTENV #include <map> namespace Prague { namespace Environment { std::map<std::string, char *> my_vars; }; }; #endif #endif bool Prague::putenv(const std::string & name, const std::string & value) { #ifdef HAVE_SETENV return setenv(name.c_str(), value.c_str(), 1) == 0; #elif HAVE_PUTENV char * env_var = new char[name.length() + value.length() + 2]; strncpy(env_var, name.c_str(), name.length()); env_var[name.length()] = '='; strncpy((env_var + name.length() + 1), value.c_str(), value.length()); env_var[name.length() + value.length() + 1] = '\0'; // make sure there's a \0 if (::putenv(env_var) == 0) { Environment::my_vars[name] = env_var; return true; } #else std::cerr << "ERROR: Prague::putenv misconfiguration!" << std::endl; exit(1); #endif return false; } bool Prague::putenv(const std::string & name) { #ifdef HAVE_UNSETENV unsetenv(name.c_str()); return true; #elif HAVE_PUTENV char * env_var = new char[name.length() + 1]; strncpy(env_var, name.c_str(), name.length()); env_var[name.length()] = '\0'; // make sure there's a \0 if (::putenv(env_var) == 0) { if (Environment::my_vars[name] != 0) delete[] Environment::my_vars[name]; Environment::my_vars.erase(name); // it was either there or // just got created. return true; } #else std::cerr << "ERROR: Prague::putenv misconfiguration!" << std::endl; exit(1); #endif return false; } std::string Prague::getenv(const std::string & name) { char const * const s = ::getenv(name.c_str()); std::string const value((s!=0)?s:""); return value; } <|endoftext|>
<commit_before>/** @file tutorialCommandLineArg.cpp @brief Tutorial on how to use command line parser in G+Smo. This file is part of the G+Smo library. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Author(s): J. Speh */ #include <iostream> #include <string> #include <gismo.h> using namespace gismo; int main(int argc, char* argv[]) { // Variables that will take values from the command line std::string string("none"); // string variable default value real_t flNumber = 1.0; // flNumber variable default value int number = 1; // number variable default value bool boolean = false; // boolean variable default value std::string plainString; // argument of reading plain string // ----------------------------------------------------------------- // First we Initialize the object that sets up and parses command line arguments // // This defines by default 3 arguments that can be readily used: // // --, --ignore_rest // Ignores the rest of the labeled arguments following this flag. // // --version // Displays version information and exits. // // -h, --help // Displays usage information for all other arguments and exits. // gsCmdLine cmd("Tutorial Command Line Arguments"); // ----------------------------------------------------------------- // General syntax to add an argument: // cmd.addType("f", "--flag", "Description", destination) // "f" is the short flag: -f // "flag" is the long flag: --flag (same effect as "-f" // "Description" describes what this argument is about // destination is the variable that will have the value of the input argument // ----------------------------------------------------------------- // Adding a string argument, given by the "-s" (or "--stringArg") flag // If set, string is updated to the input value, otherwise string remains untouched cmd.addString("s", "stringArg", "Description of string command line argument.", string); // ----------------------------------------------------------------- // Adding a string argument, given by the "-i" (or "--num") flag // If set, number is updated to the input value, otherwise number remains untouched cmd.addInt ("i", "num", "Description of int command line argument", number); // ----------------------------------------------------------------- // Adding a float argument, given by the "-r" (or "--real") flag // If set, flNumber is updated to the input value, otherwise flNumber remains untouched cmd.addReal ("r", "real", "Description of float command line argument", flNumber); // ----------------------------------------------------------------- // Adding a switch argument, given by the "--bool" flag // If set, boolean is updated to the input value, otherwise flNumber boolean untouched cmd.addSwitch("bool","Description of the switch argument.", boolean); // ----------------------------------------------------------------- // Extra plain argument (manually defined): // Plain arguments are given without a flag. They need to be // defined by making a "gsArgValPlain" argument object, taking the // cmd object in the constructor std::string name = "plain"; std::string desc = "Description of the plain command line argument."; bool req = false; // whether the argument is required std::string value = "default_plain_value"; std::string typeDesc = "string"; // type description gsArgValPlain<std::string> plainArg(name, desc, req, value, typeDesc, cmd); // ----------------------------------------------------------------- // Reading the arguments: values string, number, flNumber, boolean // are updated with the inputs, if given. If "true" is returned, then reading succeeded. bool ok = cmd.getValues(argc,argv); // ----------------------------------------------------------------- // The extra (manually defined) arguments are not fetched with the //above command. The user must call "getValue" for each manually //defined argument. plainString = plainArg.getValue(); if ( !ok ) { std::cout << "Something went wrong when reading the command line. Exiting.\n"; return 0; } std::cout << "Printing command line arguments:\n\n\n" << "Plain string: " << plainString << "\n\n" << "String: " << string << "\n\n" << "Float: " << flNumber << "\n\n" << "Integer: " << number << "\n\n" << "Switch: " << boolean << "\n" << std::endl; return 0; } <commit_msg>comment fixes<commit_after>/** @file tutorialCommandLineArg.cpp @brief Tutorial on how to use command line parser in G+Smo. This file is part of the G+Smo library. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Author(s): J. Speh */ #include <iostream> #include <string> #include <gismo.h> using namespace gismo; int main(int argc, char* argv[]) { // Variables that will take values from the command line std::string string("none"); // string variable default value real_t flNumber = 1.0; // flNumber variable default value int number = 1; // number variable default value bool boolean = false; // boolean variable default value std::string plainString; // argument of reading plain string // ----------------------------------------------------------------- // First we Initialize the object that sets up and parses command line arguments // // This defines by default 3 arguments that can be readily used: // // --, --ignore_rest // Ignores the rest of the labeled arguments following this flag. // // --version // Displays version information and exits. // // -h, --help // Displays usage information for all other arguments and exits. // gsCmdLine cmd("Tutorial Command Line Arguments"); // ----------------------------------------------------------------- // General syntax to add an argument: // cmd.addType("f", "--flag", "Description", destination) // "f" is the short flag: -f // "flag" is the long flag: --flag (same effect as "-f") // "Description" describes what this argument is about // destination is the variable that will have the value of the input argument // ----------------------------------------------------------------- // Adding a string argument, given by the "-s" (or "--stringArg") flag // If set, string is updated to the input value, otherwise string remains untouched cmd.addString("s", "stringArg", "Description of string command line argument.", string); // ----------------------------------------------------------------- // Adding a string argument, given by the "-i" (or "--num") flag // If set, number is updated to the input value, otherwise number remains untouched cmd.addInt ("i", "num", "Description of int command line argument", number); // ----------------------------------------------------------------- // Adding a float argument, given by the "-r" (or "--real") flag // If set, flNumber is updated to the input value, otherwise flNumber remains untouched cmd.addReal ("r", "real", "Description of float command line argument", flNumber); // ----------------------------------------------------------------- // Adding a switch argument, given by the "--bool" flag // If set, boolean is updated to the input value, otherwise boolean remains untouched cmd.addSwitch("bool","Description of the switch argument.", boolean); // ----------------------------------------------------------------- // Extra plain argument (manually defined): // Plain arguments are given without a flag. They need to be // defined by making a "gsArgValPlain" argument object, taking the // cmd object in the constructor std::string name = "plain"; std::string desc = "Description of the plain command line argument."; bool req = false; // whether the argument is required std::string value = "default_plain_value"; std::string typeDesc = "string"; // type description gsArgValPlain<std::string> plainArg(name, desc, req, value, typeDesc, cmd); // Note: Another manually defined argument is // gsArgMultiVal // which reads several values (i.e. a vector) with one flag // ----------------------------------------------------------------- // Reading the arguments: values string, number, flNumber, boolean // are updated with the inputs, if given. If "true" is returned, then reading succeeded. bool ok = cmd.getValues(argc,argv); // ----------------------------------------------------------------- // The extra (manually defined) arguments are not fetched with the //above command. The user must call "getValue" for each manually //defined argument. plainString = plainArg.getValue(); if ( !ok ) { std::cout << "Something went wrong when reading the command line. Exiting.\n"; return 0; } std::cout << "Printing command line arguments:\n\n\n" << "Plain string: " << plainString << "\n\n" << "String: " << string << "\n\n" << "Float: " << flNumber << "\n\n" << "Integer: " << number << "\n\n" << "Switch: " << boolean << "\n" << std::endl; return 0; } <|endoftext|>
<commit_before><commit_msg>Rename variables.<commit_after><|endoftext|>
<commit_before>#include <cstdio> #include "acmacs-base/acmacsd.hh" #include "acmacs-base/argv.hh" #include "acmacs-base/filesystem.hh" #include "acmacs-base/timeit.hh" #include "acmacs-base/string.hh" #include "acmacs-base/quicklook.hh" #include "hidb-5/hidb.hh" #include "acmacs-chart-2/factory-import.hh" #include "acmacs-map-draw/draw.hh" #include "acmacs-map-draw/mod-applicator.hh" #include "acmacs-map-draw/setup-dbs.hh" static std::string draw(std::shared_ptr<acmacs::chart::ChartModify> chart, const std::vector<std::string_view>& settings_files, std::string_view output_pdf, bool name_after_mod); static std::string mod_name(const rjson::value& aMods); // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } option<str> db_dir{*this, "db-dir"}; // option<str> seqdb{*this, "seqdb"}; option<str_array> settings_files{*this, 's'}; option<size_t> projection{*this, 'p', "projection", dflt{0UL}}; option<bool> name_after_mod{*this, "name-after-mod"}; option<str> preview_pos{*this, "pos"}; option<str> previous{*this, "previous"}; option<str> previous_pos{*this, "previous-pos"}; argument<str> chart{*this, arg_name{"chart.ace"}, mandatory}; argument<str> output_pdf{*this, arg_name{"mdi-output.pdf"}}; }; int main(int argc, char* const argv[]) { int exit_code = 1; try { Options opt(argc, argv); setup_dbs(opt.db_dir, false); if (std::count_if(opt.settings_files->begin(), opt.settings_files->end(), [](std::string_view fn) { if (!fs::exists(fn)) { fmt::print(stderr, "ERROR: \"{}\" does not exist\n", fn); return true; } else return false; }) > 0) throw std::runtime_error("not all settings files exist"); std::string_view output_pdf; if (opt.output_pdf) output_pdf = opt.output_pdf; else if (opt.name_after_mod) { output_pdf = opt.chart->substr(0, opt.chart->rfind('.') + 1); } else throw std::runtime_error("not output_pdf provided and no --name-after-mod"); const auto cmd = fmt::format("fswatch --latency=0.1 '{}'", acmacs::string::join(acmacs::string::join_sep_t{"' '"}, *opt.settings_files)); std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"), pclose); Timeit ti_chart(fmt::format("DEBUG: chart loading from {}: ", *opt.chart), report_time::yes); auto chart = std::make_shared<acmacs::chart::ChartModify>(acmacs::chart::import_from_file(opt.chart)); ti_chart.report(); [[maybe_unused]] const auto& hidb = hidb::get(chart->info()->virus_type(), report_time::yes); acmacs::seqdb::get(); if (opt.previous) { if (opt.previous_pos) acmacs::run_and_detach({"preview", "-p", opt.previous_pos->data(), opt.previous->data()}, 0); else acmacs::run_and_detach({"preview", opt.previous->data()}, 0); } std::array<char, 1024> buffer; for (;;) { if (const auto output_name = draw(chart, *opt.settings_files, output_pdf, opt.name_after_mod); !output_name.empty()) { acmacs::run_and_detach({"tink"}, 0); if (opt.preview_pos) acmacs::run_and_detach({"preview", "-p", opt.preview_pos->data(), output_name.data()}, 0); else acmacs::run_and_detach({"preview", output_name.data()}, 0); // acmacs::open_or_quicklook(true, false, "/Applications/Emacs.app", 0); // for (auto sf = opt.settings_files->rbegin(); sf != opt.settings_files->rend(); ++sf) { // std::string name{*sf}; // name.push_back('\0'); // acmacs::run_and_detach({"emacsclient", "-n", name.data()}, 0); // } } else acmacs::run_and_detach({"submarine"}, 0); fmt::print("\nSETTINGS:\n"); for (const auto& sf : *opt.settings_files) fmt::print(" {}\n", sf); (void)fgets(buffer.data(), buffer.size(), pipe.get()); acmacs::run_and_detach({"tink"}, 0); } } catch (std::exception& err) { fmt::print(stderr, "ERROR: {}\n", err); exit_code = 2; } return exit_code; } // ---------------------------------------------------------------------- std::string draw(std::shared_ptr<acmacs::chart::ChartModify> chart, const std::vector<std::string_view>& settings_files, std::string_view output_pdf, bool name_after_mod) { using namespace std::string_view_literals; Timeit ti_chart("DEBUG: drawing: ", report_time::yes); try { const size_t projection_no = 0; const acmacs::Layout orig_layout(*chart->projection_modify(projection_no)->layout()); const auto orig_transformation = chart->projection_modify(projection_no)->transformation(); ChartDraw chart_draw(chart, projection_no); rjson::value settings{rjson::object{{"apply", rjson::array{"title"}}}}; for (const auto& settings_file_name : {"acmacs-map-draw.json"sv}) { if (const auto filename = fmt::format("{}/share/conf/{}", acmacs::acmacsd_root(), settings_file_name); fs::exists(filename)) settings.update(rjson::parse_file(filename, rjson::remove_comments::no)); else fmt::print(stderr, "WARNING: cannot load \"{}\": file not found\n", filename); } for (auto fn : settings_files) settings.update(rjson::parse_file(fn, rjson::remove_comments::no)); std::string output{output_pdf}; if (name_after_mod) output += mod_name(settings["apply"]) + ".pdf"; settings["output_pdf"] = output; apply_mods(chart_draw, settings["apply"], settings); chart_draw.calculate_viewport(); chart_draw.draw(output, 800, report_time::yes); chart->projection_modify(projection_no)->transformation(orig_transformation); return output; } catch (std::exception& err) { fmt::print(stderr, "ERROR: {}\n", err); } return std::string{}; } // draw // ---------------------------------------------------------------------- std::string mod_name(const rjson::value& aMods) { std::string name; rjson::for_each(aMods, [&name](const rjson::value& mod_desc) { if (const std::string_view mod_desc_s{mod_desc.to<std::string_view>()}; name.empty() && mod_desc_s[0] != '?' && mod_desc_s[0] != '_') name = mod_desc_s; }); return name; } // mod_name // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>minor fix<commit_after>#include <cstdio> #include "acmacs-base/acmacsd.hh" #include "acmacs-base/argv.hh" #include "acmacs-base/filesystem.hh" #include "acmacs-base/timeit.hh" #include "acmacs-base/string.hh" #include "acmacs-base/quicklook.hh" #include "hidb-5/hidb.hh" #include "acmacs-chart-2/factory-import.hh" #include "acmacs-map-draw/draw.hh" #include "acmacs-map-draw/mod-applicator.hh" #include "acmacs-map-draw/setup-dbs.hh" static std::string draw(std::shared_ptr<acmacs::chart::ChartModify> chart, const std::vector<std::string_view>& settings_files, std::string_view output_pdf, bool name_after_mod); static std::string mod_name(const rjson::value& aMods); // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } option<str> db_dir{*this, "db-dir"}; // option<str> seqdb{*this, "seqdb"}; option<str_array> settings_files{*this, 's'}; option<size_t> projection{*this, 'p', "projection", dflt{0UL}}; option<bool> name_after_mod{*this, "name-after-mod"}; option<str> preview_pos{*this, "pos"}; option<str> previous{*this, "previous"}; option<str> previous_pos{*this, "previous-pos"}; argument<str> chart{*this, arg_name{"chart.ace"}, mandatory}; argument<str> output_pdf{*this, arg_name{"mdi-output.pdf"}}; }; int main(int argc, char* const argv[]) { int exit_code = 1; try { Options opt(argc, argv); setup_dbs(opt.db_dir, false); if (std::count_if(opt.settings_files->begin(), opt.settings_files->end(), [](std::string_view fn) { if (!fs::exists(fn)) { fmt::print(stderr, "ERROR: \"{}\" does not exist\n", fn); return true; } else return false; }) > 0) throw std::runtime_error("not all settings files exist"); std::string_view output_pdf; if (opt.output_pdf) output_pdf = opt.output_pdf; else if (opt.name_after_mod) { output_pdf = opt.chart->substr(0, opt.chart->rfind('.') + 1); } else throw std::runtime_error("not output_pdf provided and no --name-after-mod"); const auto cmd = fmt::format("fswatch --latency=0.1 '{}'", acmacs::string::join(acmacs::string::join_sep_t{"' '"}, *opt.settings_files)); std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"), pclose); Timeit ti_chart(fmt::format("DEBUG: chart loading from {}: ", *opt.chart), report_time::yes); auto chart = std::make_shared<acmacs::chart::ChartModify>(acmacs::chart::import_from_file(opt.chart)); ti_chart.report(); [[maybe_unused]] const auto& hidb = hidb::get(chart->info()->virus_type(), report_time::yes); acmacs::seqdb::get(); if (opt.previous) { if (opt.previous_pos) acmacs::run_and_detach({"preview", "-p", opt.previous_pos->data(), opt.previous->data()}, 0); else acmacs::run_and_detach({"preview", opt.previous->data()}, 0); } std::array<char, 1024> buffer; for (;;) { if (const auto output_name = draw(chart, *opt.settings_files, output_pdf, opt.name_after_mod); !output_name.empty()) { acmacs::run_and_detach({"tink"}, 0); if (opt.preview_pos) acmacs::run_and_detach({"preview", "-p", opt.preview_pos->data(), output_name.data()}, 0); else acmacs::run_and_detach({"preview", output_name.data()}, 0); // acmacs::open_or_quicklook(true, false, "/Applications/Emacs.app", 0); // for (auto sf = opt.settings_files->rbegin(); sf != opt.settings_files->rend(); ++sf) { // std::string name{*sf}; // name.push_back('\0'); // acmacs::run_and_detach({"emacsclient", "-n", name.data()}, 0); // } } else acmacs::run_and_detach({"submarine"}, 0); fmt::print("\nSETTINGS:\n"); for (const auto& sf : *opt.settings_files) fmt::print(" {}\n", sf); if (!fgets(buffer.data(), buffer.size(), pipe.get())) throw std::runtime_error{"fgets error"}; acmacs::run_and_detach({"tink"}, 0); } } catch (std::exception& err) { fmt::print(stderr, "ERROR: {}\n", err); exit_code = 2; } return exit_code; } // ---------------------------------------------------------------------- std::string draw(std::shared_ptr<acmacs::chart::ChartModify> chart, const std::vector<std::string_view>& settings_files, std::string_view output_pdf, bool name_after_mod) { using namespace std::string_view_literals; Timeit ti_chart("DEBUG: drawing: ", report_time::yes); try { const size_t projection_no = 0; const acmacs::Layout orig_layout(*chart->projection_modify(projection_no)->layout()); const auto orig_transformation = chart->projection_modify(projection_no)->transformation(); ChartDraw chart_draw(chart, projection_no); rjson::value settings{rjson::object{{"apply", rjson::array{"title"}}}}; for (const auto& settings_file_name : {"acmacs-map-draw.json"sv}) { if (const auto filename = fmt::format("{}/share/conf/{}", acmacs::acmacsd_root(), settings_file_name); fs::exists(filename)) settings.update(rjson::parse_file(filename, rjson::remove_comments::no)); else fmt::print(stderr, "WARNING: cannot load \"{}\": file not found\n", filename); } for (auto fn : settings_files) settings.update(rjson::parse_file(fn, rjson::remove_comments::no)); std::string output{output_pdf}; if (name_after_mod) output += mod_name(settings["apply"]) + ".pdf"; settings["output_pdf"] = output; apply_mods(chart_draw, settings["apply"], settings); chart_draw.calculate_viewport(); chart_draw.draw(output, 800, report_time::yes); chart->projection_modify(projection_no)->transformation(orig_transformation); return output; } catch (std::exception& err) { fmt::print(stderr, "ERROR: {}\n", err); } return std::string{}; } // draw // ---------------------------------------------------------------------- std::string mod_name(const rjson::value& aMods) { std::string name; rjson::for_each(aMods, [&name](const rjson::value& mod_desc) { if (const std::string_view mod_desc_s{mod_desc.to<std::string_view>()}; name.empty() && mod_desc_s[0] != '?' && mod_desc_s[0] != '_') name = mod_desc_s; }); return name; } // mod_name // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|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 examples 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 <QtGui> #include <QNetworkProxyFactory> #include "googlechat.h" #ifndef QT_NO_OPENSSL #include <QSslSocket> #endif int main(int argc, char * argv[]) { QApplication app(argc, argv); #ifndef QT_NO_OPENSSL if (!QSslSocket::supportsSsl()) { #endif QMessageBox::information(0, "Google Talk client", "Your system does not support SSL, " "which is required to run this example."); return -1; #ifndef QT_NO_OPENSSL } #endif QNetworkProxyFactory::setUseSystemConfigurationEnabled(true); GoogleChat *chat = new GoogleChat; chat->show(); return app.exec(); } <commit_msg>Revert "Google Chat example: state that SSL is required"<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 examples 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 <QtGui> #include <QNetworkProxyFactory> #include "googlechat.h" int main(int argc, char * argv[]) { QApplication app(argc, argv); QNetworkProxyFactory::setUseSystemConfigurationEnabled(true); GoogleChat *chat = new GoogleChat; chat->show(); return app.exec(); } <|endoftext|>
<commit_before>// // Created by Ray Jenkins on 4/20/15. // #include "ConservatorFramework.h" #include "SetDataBuilderImpl.h" #include "GetChildrenBuilderImpl.h" #include "GetACLBuilderImpl.h" #include "SetACLBuilderImpl.h" void watcher(zhandle_t *zzh, int type, int state, const char *path, void *watcherCtx) { ConservatorFramework* framework = (ConservatorFramework *) watcherCtx; if(state == ZOO_CONNECTED_STATE) { unique_lock<std::mutex> connectLock(framework->connectMutex); framework->connected = true; framework->connectCondition.notify_all(); connectLock.unlock(); } }; ConservatorFramework::ConservatorFramework(string connectString) { this->connectString = connectString; } ConservatorFramework::ConservatorFramework(string connectString, int timeout) { this->connectString = connectString; this->timeout = timeout; } ConservatorFramework::ConservatorFramework(string connectString, int timeout, clientid_t *cid) { this->connectString = connectString; this->timeout = timeout; this->cid = cid; } ConservatorFramework::ConservatorFramework(string connectString, int timeout, clientid_t *cid, int znode_size) { this->connectString = connectString; this->timeout = timeout; this->cid = cid; this->znode_size = znode_size; } void ConservatorFramework::start() { this->zk = zookeeper_init(connectString.c_str(), watcher, timeout, cid, (void *) this, 0); while(!connected) { unique_lock<std::mutex> connectLock(connectMutex); if(connectCondition.wait_for(connectLock, chrono::seconds(15)) == cv_status::timeout) { throw "timed out waiting to connect to zookeeper"; } connectLock.unlock(); } started = true; } void ConservatorFramework::close() { zookeeper_close(this->zk); started = false; } ZOOAPI int ConservatorFramework::getState() { return zoo_state(zk); } bool ConservatorFramework::isStarted() { return started; } unique_ptr<GetDataBuilder<string>> ConservatorFramework::getData() { unique_ptr<GetDataBuilder<string>> p(new GetDataBuilderImpl(zk, znode_size)); return p; } unique_ptr<SetDataBuilder<int>> ConservatorFramework::setData() { unique_ptr<SetDataBuilder<int>> p(new SetDataBuilderImpl(zk)); return p; } unique_ptr<ExistsBuilder<int>> ConservatorFramework::checkExists() { unique_ptr<ExistsBuilder<int>> p(new ExistsBuilderImpl(zk)); return p; } unique_ptr<CreateBuilder<int>> ConservatorFramework::create() { unique_ptr<CreateBuilder<int>> p(new CreateBuilderImpl(zk)); return p; } unique_ptr<DeleteBuilder<int>> ConservatorFramework::deleteNode() { unique_ptr<DeleteBuilder<int>> p(new DeleteBuilderImpl(zk)); return p; } unique_ptr<GetChildrenBuilder<string>> ConservatorFramework::getChildren() { unique_ptr<GetChildrenBuilder<string>> p(new GetChildrenBuilderImpl(zk)); return p; } unique_ptr<GetACLBuilder<int>> ConservatorFramework::getACL(ACL_vector *vector) { unique_ptr<GetACLBuilder<int>> p(new GetACLBuilderImpl(zk, vector)); return p; } unique_ptr<SetACLBuilder<int>> ConservatorFramework::setACL(ACL_vector *vector) { unique_ptr<SetACLBuilder<int>> p(new SetACLBuilderImpl(zk, vector)); return p; } string ConservatorFramework::get(string path) { return get(path, znode_size); } string ConservatorFramework::get(string path, int length) { char buff[length]; struct Stat stat; zoo_get(zk, path.c_str(), 0, buff, &length, &stat); return string(buff); } <commit_msg>move lock outside of if connected check<commit_after>// // Created by Ray Jenkins on 4/20/15. // #include "ConservatorFramework.h" #include "SetDataBuilderImpl.h" #include "GetChildrenBuilderImpl.h" #include "GetACLBuilderImpl.h" #include "SetACLBuilderImpl.h" void watcher(zhandle_t *zzh, int type, int state, const char *path, void *watcherCtx) { ConservatorFramework* framework = (ConservatorFramework *) watcherCtx; if(state == ZOO_CONNECTED_STATE) { unique_lock<std::mutex> connectLock(framework->connectMutex); framework->connected = true; framework->connectCondition.notify_all(); connectLock.unlock(); } }; ConservatorFramework::ConservatorFramework(string connectString) { this->connectString = connectString; } ConservatorFramework::ConservatorFramework(string connectString, int timeout) { this->connectString = connectString; this->timeout = timeout; } ConservatorFramework::ConservatorFramework(string connectString, int timeout, clientid_t *cid) { this->connectString = connectString; this->timeout = timeout; this->cid = cid; } ConservatorFramework::ConservatorFramework(string connectString, int timeout, clientid_t *cid, int znode_size) { this->connectString = connectString; this->timeout = timeout; this->cid = cid; this->znode_size = znode_size; } void ConservatorFramework::start() { this->zk = zookeeper_init(connectString.c_str(), watcher, timeout, cid, (void *) this, 0); unique_lock<std::mutex> connectLock(connectMutex); while(!connected) { if(connectCondition.wait_for(connectLock, chrono::seconds(15)) == cv_status::timeout) { throw "timed out waiting to connect to zookeeper"; } } started = true; } void ConservatorFramework::close() { zookeeper_close(this->zk); started = false; } ZOOAPI int ConservatorFramework::getState() { return zoo_state(zk); } bool ConservatorFramework::isStarted() { return started; } unique_ptr<GetDataBuilder<string>> ConservatorFramework::getData() { unique_ptr<GetDataBuilder<string>> p(new GetDataBuilderImpl(zk, znode_size)); return p; } unique_ptr<SetDataBuilder<int>> ConservatorFramework::setData() { unique_ptr<SetDataBuilder<int>> p(new SetDataBuilderImpl(zk)); return p; } unique_ptr<ExistsBuilder<int>> ConservatorFramework::checkExists() { unique_ptr<ExistsBuilder<int>> p(new ExistsBuilderImpl(zk)); return p; } unique_ptr<CreateBuilder<int>> ConservatorFramework::create() { unique_ptr<CreateBuilder<int>> p(new CreateBuilderImpl(zk)); return p; } unique_ptr<DeleteBuilder<int>> ConservatorFramework::deleteNode() { unique_ptr<DeleteBuilder<int>> p(new DeleteBuilderImpl(zk)); return p; } unique_ptr<GetChildrenBuilder<string>> ConservatorFramework::getChildren() { unique_ptr<GetChildrenBuilder<string>> p(new GetChildrenBuilderImpl(zk)); return p; } unique_ptr<GetACLBuilder<int>> ConservatorFramework::getACL(ACL_vector *vector) { unique_ptr<GetACLBuilder<int>> p(new GetACLBuilderImpl(zk, vector)); return p; } unique_ptr<SetACLBuilder<int>> ConservatorFramework::setACL(ACL_vector *vector) { unique_ptr<SetACLBuilder<int>> p(new SetACLBuilderImpl(zk, vector)); return p; } string ConservatorFramework::get(string path) { return get(path, znode_size); } string ConservatorFramework::get(string path, int length) { char buff[length]; struct Stat stat; zoo_get(zk, path.c_str(), 0, buff, &length, &stat); return string(buff); } <|endoftext|>
<commit_before>/* * MCore Extensions for TTBlue * Creates a wrapper for TTAudioObjects that can be used to build an audio processing graph. * Copyright © 2008, Timothy Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "multicore.h" #define thisTTClass MCoreObject MCoreObject::MCoreObject(const TTValue& arguments) : TTObject("multicore.object"), flags(kMCoreProcessor), alwaysProcessSidechain(false), audioSources(NULL), sidechainSources(NULL), numSources(0), numSidechainSources(0), audioInput(NULL), audioOutput(NULL), sidechainInput(NULL), sidechainOutput(NULL), audioObject(NULL) { TTErr err; TTSymbolPtr wrappedObjectName; TTUInt16 initialNumChannels; TT_ASSERT(multicore_correct_instantiation_args, arguments.getSize() == 2); arguments.get(0, &wrappedObjectName); arguments.get(1, initialNumChannels); inChansToOutChansRatio[0] = 1; inChansToOutChansRatio[1] = 1; err = TTObjectInstantiate(wrappedObjectName, &audioObject, initialNumChannels); err = TTObjectInstantiate(kTTSym_audiosignal, &audioInput, initialNumChannels); err = TTObjectInstantiate(kTTSym_audiosignal, &audioOutput, initialNumChannels * TTLimitMin<TTFloat32>(inChansToOutChansRatio[1] / inChansToOutChansRatio[0], 1)); registerMessageWithArgument(objectFreeing); // called when one of our input source objects is deleted } MCoreObject::~MCoreObject() { for(TTUInt16 i=0; i<numSources; i++) audioSources[i]->unregisterObserverForNotifications(*this); TTObjectRelease(&audioObject); TTObjectRelease(&audioInput); TTObjectRelease(&audioOutput); TTObjectRelease(&sidechainInput); TTObjectRelease(&sidechainOutput); } TTErr MCoreObject::objectFreeing(const TTValue& theObjectBeingDeleted) { TTObjectPtr o = theObjectBeingDeleted; TTBoolean found = NO; TTBoolean oldValid = valid; // This is an ugly operation // the problem is that we don't want to traverse a linked-list in the processing chain valid = false; while(getlock()) ; for(TTUInt16 i=0; i<(numSources-1); i++){ if(audioSources[i] == o) found = YES; if(found) audioSources[i] = audioSources[i+1]; } audioSources[numSources-1] = 0; numSources--; valid = oldValid; return kTTErrNone; } TTErr MCoreObject::setAudioOutputPtr(TTAudioSignalPtr newOutputPtr) { if(audioOutput) TTObjectRelease(&audioOutput); audioOutput = (TTAudioSignalPtr)TTObjectReference(newOutputPtr); return kTTErrNone; } TTErr MCoreObject::setInChansToOutChansRatio(TTUInt16 numInputChannels, TTUInt16 numOutputChannels) { inChansToOutChansRatio[0] = numInputChannels; inChansToOutChansRatio[1] = numOutputChannels; return kTTErrNone; } TTErr MCoreObject::setAlwaysProcessSidechain(TTBoolean newValue) { alwaysProcessSidechain = newValue; return kTTErrNone; } TTErr MCoreObject::prepareToProcess() { lock(); if(valid){ processStatus = kProcessNotStarted; for(TTUInt16 i=0; i<numSources; i++) audioSources[i]->prepareToProcess(); for(TTUInt16 i=0; i<numSidechainSources; i++) sidechainSources[i]->prepareToProcess(); } unlock(); return kTTErrNone; } TTErr MCoreObject::resetSources(TTUInt16 vs) { // go through all of the sources and tell them we don't want to watch them any more for(TTUInt16 i=0; i<numSources; i++) audioSources[i]->unregisterObserverForNotifications(*this); if(audioSources && numSources) free(audioSources); audioSources = NULL; numSources = 0; if(sidechainSources && numSidechainSources) free(sidechainSources); sidechainSources = NULL; numSidechainSources = 0; // Generators will not receive an 'addSource' call, // so we set them with the 'default' vector size provided by the global reset if(flags & kMCoreGenerator){ audioOutput->allocWithVectorSize(vs); } return kTTErrNone; } TTErr MCoreObject::addSource(MCoreObjectPtr anObject, TTUInt16 sourceOutletNumber, TTUInt16 anInletNumber) { if(anInletNumber){ // A sidechain source numSidechainSources++; if(numSidechainSources == 1){ sidechainSources = (MCoreObjectPtr*)malloc(sizeof(MCoreObjectPtr) * numSidechainSources); sidechainOutletIndices = (TTUInt16*)malloc(sizeof(TTUInt16) * numSources); } else{ sidechainSources = (MCoreObjectPtr*)realloc(sidechainSources, sizeof(MCoreObjectPtr) * numSidechainSources); sidechainOutletIndices = (TTUInt16*)realloc(sidechainOutletIndices, sizeof(TTUInt16) * numSources); } sidechainSources[numSidechainSources-1] = anObject; sidechainOutletIndices[numSidechainSources-1] = sourceOutletNumber; if(!sidechainInput) TTObjectInstantiate(kTTSym_audiosignal, &sidechainInput, 1); if(!sidechainOutput) TTObjectInstantiate(kTTSym_audiosignal, &sidechainOutput, TTLimitMin<TTFloat32>(inChansToOutChansRatio[1] / inChansToOutChansRatio[0], 1)); } else{ // A normal audio source numSources++; if(numSources == 1){ audioSources = (MCoreObjectPtr*)malloc(sizeof(MCoreObjectPtr) * numSources); audioSourceOutletIndices = (TTUInt16*)malloc(sizeof(TTUInt16) * numSources); } else{ audioSources = (MCoreObjectPtr*)realloc(audioSources, sizeof(MCoreObjectPtr) * numSources); audioSourceOutletIndices = (TTUInt16*)realloc(audioSourceOutletIndices, sizeof(TTUInt16) * numSources); } audioSources[numSources-1] = anObject; audioSourceOutletIndices[numSources-1] = sourceOutletNumber; } // tell the source that is passed in that we want to watch it anObject->registerObserverForNotifications(*this); return kTTErrNone; } TTUInt16 MCoreObject::initAudioSignal(TTAudioSignalPtr aSignal, MCoreObjectPtr aSource) { TTUInt16 numChannels; TTUInt16 sourceProducesNumChannels; numChannels = aSignal->getNumChannels(); sourceProducesNumChannels = aSource->audioOutput->getNumChannels(); // currently we only up-size a signal, but perhaps we should also down-size them as appropriate? if(sourceProducesNumChannels > numChannels) aSignal->setmaxNumChannels(sourceProducesNumChannels); aSignal->setnumChannels(sourceProducesNumChannels); return sourceProducesNumChannels; } TTErr MCoreObject::init() { TTUInt16 sourceProducesNumChannels; TTUInt16 sidechainSourceProducesNumChannels; TTUInt16 weDeliverNumChannels; lock(); // init objects higher up in the chain first for(TTUInt16 i=0; i<numSources; i++) audioSources[i]->init(); for(TTUInt16 i=0; i<numSidechainSources; i++) sidechainSources[i]->init(); // What follows is a bit ugly (including code duplication) and should be reviewed: // The sidechain situation makes this even more complex... // For now we make the dubious assumption that sidechains are going to follow along // and be set up just like the normal audio inputs. if(numSources && audioSources){ // match our source's vector size and number of channels sourceProducesNumChannels = initAudioSignal(audioInput, audioSources[0]); // while it make sense to always match the input of this object to the output of the previous object (as above) // we might want to have a different number of outputs here -- how should we handle that? // for now we are just matching them more or less... weDeliverNumChannels = sourceProducesNumChannels * TTLimitMin<TTFloat32>(inChansToOutChansRatio[1] / inChansToOutChansRatio[0], 1); audioOutput->setmaxNumChannels(weDeliverNumChannels); audioOutput->setnumChannels(weDeliverNumChannels); // for generators, these are already alloc'd in the reset method audioInput->allocWithVectorSize(audioSources[0]->audioOutput->getVectorSize()); audioOutput->allocWithVectorSize(audioSources[0]->audioOutput->getVectorSize()); if(numSidechainSources){ sidechainSourceProducesNumChannels = initAudioSignal(sidechainInput, sidechainSources[0]); sidechainInput->allocWithVectorSize(sidechainSources[0]->audioOutput->getVectorSize()); } if(alwaysProcessSidechain){ if(!sidechainOutput) TTObjectInstantiate(kTTSym_audiosignal, &sidechainOutput, sourceProducesNumChannels * TTLimitMin<TTFloat32>(inChansToOutChansRatio[1] / inChansToOutChansRatio[0], 1)); sidechainOutput->allocWithVectorSize(audioSources[0]->audioOutput->getVectorSize()); } } else{ sourceProducesNumChannels = 0; weDeliverNumChannels = getNumOutputChannels(); } // Even more ambiguous, what do we do for the acual audio object? // For now we are setting it to the higher of the two options to be safe. // (and we are not taking sidechains into account at all if(weDeliverNumChannels > sourceProducesNumChannels) audioObject->setMaxNumChannels(weDeliverNumChannels); else audioObject->setMaxNumChannels(sourceProducesNumChannels); unlock(); return kTTErrNone; } TTErr MCoreObject::getAudioOutput(TTAudioSignalPtr& returnedSignal, TTBoolean getSidechain) { TTAudioSignalPtr pulledInput = NULL; TTAudioSignalPtr pulledSidechainInput = NULL; TTErr err; lock(); switch(processStatus){ // we have not processed anything yet, so let's get started case kProcessNotStarted: processStatus = kProcessingCurrently; // zero the samples audioInput->clear(); // sum the sources for(TTUInt16 i=0; i<numSources; i++){ // if there is a non-zero source outlet index, that means we are supposed to request the sidechain signal err = audioSources[i]->getAudioOutput(pulledInput, audioSourceOutletIndices[i]); if(!err) (*audioInput) += (*pulledInput); } if(numSidechainSources){ sidechainInput->clear(); // zero the samples // sum the sidechain sources for(TTUInt16 i=0; i<numSidechainSources; i++){ err = sidechainSources[i]->getAudioOutput(pulledSidechainInput); if(!err) (*sidechainInput) += (*pulledSidechainInput); } audioObject->process(audioInput, sidechainInput, audioOutput); // a processor with sidechain input } else if(alwaysProcessSidechain){ audioObject->process(audioInput, audioInput, audioOutput, sidechainOutput); // a processor with sidechain output } else if(numSources){ audioObject->process(audioInput, audioOutput); // a processor } else{ audioObject->process(audioOutput); // a generator (or no input) } // return if(getSidechain) returnedSignal = sidechainOutput; else returnedSignal = audioOutput; processStatus = kProcessComplete; break; // we already processed everything that needs to be processed, so just set the pointer case kProcessComplete: if(getSidechain) returnedSignal = sidechainOutput; else returnedSignal = audioOutput; break; // to prevent feedback / infinite loops, we just hand back the last calculated output here case kProcessingCurrently: if(getSidechain) returnedSignal = sidechainOutput; else returnedSignal = audioOutput; break; // we should never get here default: unlock(); return kTTErrGeneric; } unlock(); return kTTErrNone; } <commit_msg>safety improvements for setting audio pointer<commit_after>/* * MCore Extensions for TTBlue * Creates a wrapper for TTAudioObjects that can be used to build an audio processing graph. * Copyright © 2008, Timothy Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "multicore.h" #define thisTTClass MCoreObject MCoreObject::MCoreObject(const TTValue& arguments) : TTObject("multicore.object"), flags(kMCoreProcessor), alwaysProcessSidechain(false), audioSources(NULL), sidechainSources(NULL), numSources(0), numSidechainSources(0), audioInput(NULL), audioOutput(NULL), sidechainInput(NULL), sidechainOutput(NULL), audioObject(NULL) { TTErr err; TTSymbolPtr wrappedObjectName; TTUInt16 initialNumChannels; TT_ASSERT(multicore_correct_instantiation_args, arguments.getSize() == 2); arguments.get(0, &wrappedObjectName); arguments.get(1, initialNumChannels); inChansToOutChansRatio[0] = 1; inChansToOutChansRatio[1] = 1; err = TTObjectInstantiate(wrappedObjectName, &audioObject, initialNumChannels); err = TTObjectInstantiate(kTTSym_audiosignal, &audioInput, initialNumChannels); err = TTObjectInstantiate(kTTSym_audiosignal, &audioOutput, initialNumChannels * TTLimitMin<TTFloat32>(inChansToOutChansRatio[1] / inChansToOutChansRatio[0], 1)); registerMessageWithArgument(objectFreeing); // called when one of our input source objects is deleted } MCoreObject::~MCoreObject() { for(TTUInt16 i=0; i<numSources; i++) audioSources[i]->unregisterObserverForNotifications(*this); TTObjectRelease(&audioObject); TTObjectRelease(&audioInput); TTObjectRelease(&audioOutput); TTObjectRelease(&sidechainInput); TTObjectRelease(&sidechainOutput); } TTErr MCoreObject::objectFreeing(const TTValue& theObjectBeingDeleted) { TTObjectPtr o = theObjectBeingDeleted; TTBoolean found = NO; TTBoolean oldValid = valid; // This is an ugly operation // the problem is that we don't want to traverse a linked-list in the processing chain valid = false; while(getlock()) ; for(TTUInt16 i=0; i<(numSources-1); i++){ if(audioSources[i] == o) found = YES; if(found) audioSources[i] = audioSources[i+1]; } audioSources[numSources-1] = 0; numSources--; valid = oldValid; return kTTErrNone; } TTErr MCoreObject::setAudioOutputPtr(TTAudioSignalPtr newOutputPtr) { TTObjectPtr oldAudioOutput = audioOutput; audioOutput = (TTAudioSignalPtr)TTObjectReference(newOutputPtr); if(oldAudioOutput) TTObjectRelease(&oldAudioOutput); return kTTErrNone; } TTErr MCoreObject::setInChansToOutChansRatio(TTUInt16 numInputChannels, TTUInt16 numOutputChannels) { inChansToOutChansRatio[0] = numInputChannels; inChansToOutChansRatio[1] = numOutputChannels; return kTTErrNone; } TTErr MCoreObject::setAlwaysProcessSidechain(TTBoolean newValue) { alwaysProcessSidechain = newValue; return kTTErrNone; } TTErr MCoreObject::prepareToProcess() { lock(); if(valid){ processStatus = kProcessNotStarted; for(TTUInt16 i=0; i<numSources; i++) audioSources[i]->prepareToProcess(); for(TTUInt16 i=0; i<numSidechainSources; i++) sidechainSources[i]->prepareToProcess(); } unlock(); return kTTErrNone; } TTErr MCoreObject::resetSources(TTUInt16 vs) { // go through all of the sources and tell them we don't want to watch them any more for(TTUInt16 i=0; i<numSources; i++) audioSources[i]->unregisterObserverForNotifications(*this); if(audioSources && numSources) free(audioSources); audioSources = NULL; numSources = 0; if(sidechainSources && numSidechainSources) free(sidechainSources); sidechainSources = NULL; numSidechainSources = 0; // Generators will not receive an 'addSource' call, // so we set them with the 'default' vector size provided by the global reset if(flags & kMCoreGenerator){ audioOutput->allocWithVectorSize(vs); } return kTTErrNone; } TTErr MCoreObject::addSource(MCoreObjectPtr anObject, TTUInt16 sourceOutletNumber, TTUInt16 anInletNumber) { if(anInletNumber){ // A sidechain source numSidechainSources++; if(numSidechainSources == 1){ sidechainSources = (MCoreObjectPtr*)malloc(sizeof(MCoreObjectPtr) * numSidechainSources); sidechainOutletIndices = (TTUInt16*)malloc(sizeof(TTUInt16) * numSources); } else{ sidechainSources = (MCoreObjectPtr*)realloc(sidechainSources, sizeof(MCoreObjectPtr) * numSidechainSources); sidechainOutletIndices = (TTUInt16*)realloc(sidechainOutletIndices, sizeof(TTUInt16) * numSources); } sidechainSources[numSidechainSources-1] = anObject; sidechainOutletIndices[numSidechainSources-1] = sourceOutletNumber; if(!sidechainInput) TTObjectInstantiate(kTTSym_audiosignal, &sidechainInput, 1); if(!sidechainOutput) TTObjectInstantiate(kTTSym_audiosignal, &sidechainOutput, TTLimitMin<TTFloat32>(inChansToOutChansRatio[1] / inChansToOutChansRatio[0], 1)); } else{ // A normal audio source numSources++; if(numSources == 1){ audioSources = (MCoreObjectPtr*)malloc(sizeof(MCoreObjectPtr) * numSources); audioSourceOutletIndices = (TTUInt16*)malloc(sizeof(TTUInt16) * numSources); } else{ audioSources = (MCoreObjectPtr*)realloc(audioSources, sizeof(MCoreObjectPtr) * numSources); audioSourceOutletIndices = (TTUInt16*)realloc(audioSourceOutletIndices, sizeof(TTUInt16) * numSources); } audioSources[numSources-1] = anObject; audioSourceOutletIndices[numSources-1] = sourceOutletNumber; } // tell the source that is passed in that we want to watch it anObject->registerObserverForNotifications(*this); return kTTErrNone; } TTUInt16 MCoreObject::initAudioSignal(TTAudioSignalPtr aSignal, MCoreObjectPtr aSource) { TTUInt16 numChannels; TTUInt16 sourceProducesNumChannels; numChannels = aSignal->getNumChannels(); sourceProducesNumChannels = aSource->audioOutput->getNumChannels(); // currently we only up-size a signal, but perhaps we should also down-size them as appropriate? if(sourceProducesNumChannels > numChannels) aSignal->setmaxNumChannels(sourceProducesNumChannels); aSignal->setnumChannels(sourceProducesNumChannels); return sourceProducesNumChannels; } TTErr MCoreObject::init() { TTUInt16 sourceProducesNumChannels; TTUInt16 sidechainSourceProducesNumChannels; TTUInt16 weDeliverNumChannels; lock(); // init objects higher up in the chain first for(TTUInt16 i=0; i<numSources; i++) audioSources[i]->init(); for(TTUInt16 i=0; i<numSidechainSources; i++) sidechainSources[i]->init(); // What follows is a bit ugly (including code duplication) and should be reviewed: // The sidechain situation makes this even more complex... // For now we make the dubious assumption that sidechains are going to follow along // and be set up just like the normal audio inputs. if(numSources && audioSources){ // match our source's vector size and number of channels sourceProducesNumChannels = initAudioSignal(audioInput, audioSources[0]); // while it make sense to always match the input of this object to the output of the previous object (as above) // we might want to have a different number of outputs here -- how should we handle that? // for now we are just matching them more or less... weDeliverNumChannels = sourceProducesNumChannels * TTLimitMin<TTFloat32>(inChansToOutChansRatio[1] / inChansToOutChansRatio[0], 1); audioOutput->setmaxNumChannels(weDeliverNumChannels); audioOutput->setnumChannels(weDeliverNumChannels); // for generators, these are already alloc'd in the reset method audioInput->allocWithVectorSize(audioSources[0]->audioOutput->getVectorSize()); audioOutput->allocWithVectorSize(audioSources[0]->audioOutput->getVectorSize()); if(numSidechainSources){ sidechainSourceProducesNumChannels = initAudioSignal(sidechainInput, sidechainSources[0]); sidechainInput->allocWithVectorSize(sidechainSources[0]->audioOutput->getVectorSize()); } if(alwaysProcessSidechain){ if(!sidechainOutput) TTObjectInstantiate(kTTSym_audiosignal, &sidechainOutput, sourceProducesNumChannels * TTLimitMin<TTFloat32>(inChansToOutChansRatio[1] / inChansToOutChansRatio[0], 1)); sidechainOutput->allocWithVectorSize(audioSources[0]->audioOutput->getVectorSize()); } } else{ sourceProducesNumChannels = 0; weDeliverNumChannels = getNumOutputChannels(); } // Even more ambiguous, what do we do for the acual audio object? // For now we are setting it to the higher of the two options to be safe. // (and we are not taking sidechains into account at all if(weDeliverNumChannels > sourceProducesNumChannels) audioObject->setMaxNumChannels(weDeliverNumChannels); else audioObject->setMaxNumChannels(sourceProducesNumChannels); unlock(); return kTTErrNone; } TTErr MCoreObject::getAudioOutput(TTAudioSignalPtr& returnedSignal, TTBoolean getSidechain) { TTAudioSignalPtr pulledInput = NULL; TTAudioSignalPtr pulledSidechainInput = NULL; TTErr err; lock(); switch(processStatus){ // we have not processed anything yet, so let's get started case kProcessNotStarted: processStatus = kProcessingCurrently; // zero the samples audioInput->clear(); // sum the sources for(TTUInt16 i=0; i<numSources; i++){ // if there is a non-zero source outlet index, that means we are supposed to request the sidechain signal err = audioSources[i]->getAudioOutput(pulledInput, audioSourceOutletIndices[i]); if(!err) (*audioInput) += (*pulledInput); } if(numSidechainSources){ sidechainInput->clear(); // zero the samples // sum the sidechain sources for(TTUInt16 i=0; i<numSidechainSources; i++){ err = sidechainSources[i]->getAudioOutput(pulledSidechainInput); if(!err) (*sidechainInput) += (*pulledSidechainInput); } audioObject->process(audioInput, sidechainInput, audioOutput); // a processor with sidechain input } else if(alwaysProcessSidechain){ audioObject->process(audioInput, audioInput, audioOutput, sidechainOutput); // a processor with sidechain output } else if(numSources){ audioObject->process(audioInput, audioOutput); // a processor } else{ audioObject->process(audioOutput); // a generator (or no input) } // return if(getSidechain) returnedSignal = sidechainOutput; else returnedSignal = audioOutput; processStatus = kProcessComplete; break; // we already processed everything that needs to be processed, so just set the pointer case kProcessComplete: if(getSidechain) returnedSignal = sidechainOutput; else returnedSignal = audioOutput; break; // to prevent feedback / infinite loops, we just hand back the last calculated output here case kProcessingCurrently: if(getSidechain) returnedSignal = sidechainOutput; else returnedSignal = audioOutput; break; // we should never get here default: unlock(); return kTTErrGeneric; } unlock(); return kTTErrNone; } <|endoftext|>
<commit_before>/* Copyright 2014-2015 Adam Grandquist 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. */ /** * @author Adam Grandquist * @copyright Apache */ #include "ReQL-new.hpp" namespace ReQL { static ReQL_Obj_t ** reql_alloc_arr(size_t size) { return new ReQL_Obj_t *[size](); } static ReQL_Pair_t * reql_alloc_pair(size_t size) { return new ReQL_Pair_t[size](); } static ReQL_Obj_t * reql_alloc_term() { return new ReQL_Obj_t(); } static ReQL_Obj_t * reql_new_array(uint32_t size) { ReQL_Obj_t *obj = reql_alloc_term(); ReQL_Obj_t **arr = reql_alloc_arr(size); reql_array_init(obj, arr, size); return obj; } static ReQL_Obj_t * reql_new(bool val) { ReQL_Obj_t *obj = reql_alloc_term(); reql_bool_init(obj, val); return obj; } static ReQL_Obj_t * reql_new_make_array(ReQL_Obj_t *arg) { ReQL_Obj_t *obj = reql_alloc_term(); reql_ast_make_array(obj, arg, NULL); return obj; } static ReQL_Obj_t * reql_new_make_obj(ReQL_Obj_t *arg) { ReQL_Obj_t *obj = reql_alloc_term(); reql_ast_make_obj(obj, NULL, arg); return obj; } static ReQL_Obj_t * reql_new() { ReQL_Obj_t *obj = reql_alloc_term(); reql_null_init(obj); return obj; } static ReQL_Obj_t * reql_new(double val) { ReQL_Obj_t *obj = reql_alloc_term(); reql_number_init(obj, val); return obj; } static ReQL_Obj_t * reql_new_object(uint32_t size) { ReQL_Obj_t *obj = reql_alloc_term(); ReQL_Pair_t *pair = reql_alloc_pair(size); reql_object_init(obj, pair, size); return obj; } static ReQL_Obj_t * reql_new(std::string val) { size_t size = val.size(); if (size > UINT32_MAX) { return NULL; } uint8_t *str = new uint8_t[size](); val.copy((char *)str, size); ReQL_Obj_t *obj = reql_alloc_term(); reql_string_init(obj, str, (uint32_t)size); return obj; } ReQL::ReQL() { query = reql_new(); } ReQL::ReQL(ReQL_AST_Function f, std::vector<ReQL> args, std::map<ReQL, ReQL> kwargs) { query = reql_alloc_term(); } ReQL::ReQL(std::string val) { query = reql_new(val); } ReQL::ReQL(double val) { query = reql_new(val); } ReQL::ReQL(bool val) { query = reql_new(val); } ReQL::ReQL(std::vector<ReQL> val) { std::size_t size = val.size(); if (size > std::numeric_limits<std::uint32_t>::max()) { return; } array = reql_new_array(static_cast<std::uint32_t>(size)); query = reql_new_make_array(array); for (auto q : val) { reql_array_append(query, q.query); } } ReQL::ReQL(std::map<ReQL, ReQL> val) { std::size_t size = val.size(); if (size > std::numeric_limits<std::uint32_t>::max()) { return; } object = reql_new_object(static_cast<std::uint32_t>(size)); query = reql_new_make_obj(object); for (auto q : val) { reql_object_add(query, q.first.query, q.second.query); } } ReQL::ReQL(const ReQL &other) { query = other.query; array = other.array; object = other.object; } ReQL::ReQL(ReQL &&other) { query = other.query; other.query = nullptr; array = other.array; other.array = nullptr; object = other.object; other.object = nullptr; } ReQL &ReQL::operator=(const ReQL &other) { if (this != &other) { query = other.query; array = other.array; object = other.object; } return *this; } ReQL &ReQL::operator=(ReQL &&other) { if (this != &other) { query = other.query; other.query = nullptr; array = other.array; other.array = nullptr; object = other.object; other.object = nullptr; } return *this; } bool ReQL::operator<(const ReQL &other) const { ReQL_Datum_t ltype = reql_datum_type(query), rtype = reql_datum_type(other.query); if (ltype == rtype) { switch (ltype) { case REQL_R_ARRAY: case REQL_R_BOOL: case REQL_R_JSON: case REQL_R_NULL: case REQL_R_NUM: case REQL_R_OBJECT: case REQL_R_REQL: { return query < other.query; } case REQL_R_STR: { std::string same((char *)reql_string_buf(query), reql_string_size(query)); std::string diff((char *)reql_string_buf(other.query), reql_string_size(other.query)); return same < diff; } } } return ltype < rtype; } ReQL::~ReQL() { if (query != nullptr) { delete query; } if (array != nullptr) { delete [] array->obj.datum.json.array; delete array; } if (object != nullptr) { delete object->obj.datum.json.pair; delete object; } } } <commit_msg>Fix missing include for array size checking.<commit_after>/* Copyright 2014-2015 Adam Grandquist 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. */ /** * @author Adam Grandquist * @copyright Apache */ #include "ReQL-new.hpp" #include <limits> namespace ReQL { static ReQL_Obj_t ** reql_alloc_arr(size_t size) { return new ReQL_Obj_t *[size](); } static ReQL_Pair_t * reql_alloc_pair(size_t size) { return new ReQL_Pair_t[size](); } static ReQL_Obj_t * reql_alloc_term() { return new ReQL_Obj_t(); } static ReQL_Obj_t * reql_new_array(uint32_t size) { ReQL_Obj_t *obj = reql_alloc_term(); ReQL_Obj_t **arr = reql_alloc_arr(size); reql_array_init(obj, arr, size); return obj; } static ReQL_Obj_t * reql_new(bool val) { ReQL_Obj_t *obj = reql_alloc_term(); reql_bool_init(obj, val); return obj; } static ReQL_Obj_t * reql_new_make_array(ReQL_Obj_t *arg) { ReQL_Obj_t *obj = reql_alloc_term(); reql_ast_make_array(obj, arg, NULL); return obj; } static ReQL_Obj_t * reql_new_make_obj(ReQL_Obj_t *arg) { ReQL_Obj_t *obj = reql_alloc_term(); reql_ast_make_obj(obj, NULL, arg); return obj; } static ReQL_Obj_t * reql_new() { ReQL_Obj_t *obj = reql_alloc_term(); reql_null_init(obj); return obj; } static ReQL_Obj_t * reql_new(double val) { ReQL_Obj_t *obj = reql_alloc_term(); reql_number_init(obj, val); return obj; } static ReQL_Obj_t * reql_new_object(uint32_t size) { ReQL_Obj_t *obj = reql_alloc_term(); ReQL_Pair_t *pair = reql_alloc_pair(size); reql_object_init(obj, pair, size); return obj; } static ReQL_Obj_t * reql_new(std::string val) { size_t size = val.size(); if (size > UINT32_MAX) { return NULL; } uint8_t *str = new uint8_t[size](); val.copy((char *)str, size); ReQL_Obj_t *obj = reql_alloc_term(); reql_string_init(obj, str, (uint32_t)size); return obj; } ReQL::ReQL() { query = reql_new(); } ReQL::ReQL(ReQL_AST_Function f, std::vector<ReQL> args, std::map<ReQL, ReQL> kwargs) { query = reql_alloc_term(); } ReQL::ReQL(std::string val) { query = reql_new(val); } ReQL::ReQL(double val) { query = reql_new(val); } ReQL::ReQL(bool val) { query = reql_new(val); } ReQL::ReQL(std::vector<ReQL> val) { std::size_t size = val.size(); if (size > std::numeric_limits<std::uint32_t>::max()) { return; } array = reql_new_array(static_cast<std::uint32_t>(size)); query = reql_new_make_array(array); for (auto q : val) { reql_array_append(query, q.query); } } ReQL::ReQL(std::map<ReQL, ReQL> val) { std::size_t size = val.size(); if (size > std::numeric_limits<std::uint32_t>::max()) { return; } object = reql_new_object(static_cast<std::uint32_t>(size)); query = reql_new_make_obj(object); for (auto q : val) { reql_object_add(query, q.first.query, q.second.query); } } ReQL::ReQL(const ReQL &other) { query = other.query; array = other.array; object = other.object; } ReQL::ReQL(ReQL &&other) { query = other.query; other.query = nullptr; array = other.array; other.array = nullptr; object = other.object; other.object = nullptr; } ReQL &ReQL::operator=(const ReQL &other) { if (this != &other) { query = other.query; array = other.array; object = other.object; } return *this; } ReQL &ReQL::operator=(ReQL &&other) { if (this != &other) { query = other.query; other.query = nullptr; array = other.array; other.array = nullptr; object = other.object; other.object = nullptr; } return *this; } bool ReQL::operator<(const ReQL &other) const { ReQL_Datum_t ltype = reql_datum_type(query), rtype = reql_datum_type(other.query); if (ltype == rtype) { switch (ltype) { case REQL_R_ARRAY: case REQL_R_BOOL: case REQL_R_JSON: case REQL_R_NULL: case REQL_R_NUM: case REQL_R_OBJECT: case REQL_R_REQL: { return query < other.query; } case REQL_R_STR: { std::string same((char *)reql_string_buf(query), reql_string_size(query)); std::string diff((char *)reql_string_buf(other.query), reql_string_size(other.query)); return same < diff; } } } return ltype < rtype; } ReQL::~ReQL() { if (query != nullptr) { delete query; } if (array != nullptr) { delete [] array->obj.datum.json.array; delete array; } if (object != nullptr) { delete object->obj.datum.json.pair; delete object; } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/dom/shadow/InsertionPoint.h" #include "HTMLNames.h" #include "core/dom/ElementTraversal.h" #include "core/dom/QualifiedName.h" #include "core/dom/StaticNodeList.h" #include "core/dom/shadow/ElementShadow.h" namespace WebCore { using namespace HTMLNames; InsertionPoint::InsertionPoint(const QualifiedName& tagName, Document& document) : HTMLElement(tagName, document, CreateInsertionPoint) , m_registeredWithShadowRoot(false) { setHasCustomStyleCallbacks(); } InsertionPoint::~InsertionPoint() { } void InsertionPoint::setDistribution(ContentDistribution& distribution) { if (shouldUseFallbackElements()) { for (Node* child = firstChild(); child; child = child->nextSibling()) child->lazyReattachIfAttached(); } // Attempt not to reattach nodes that would be distributed to the exact same // location by comparing the old and new distributions. size_t i = 0; size_t j = 0; for ( ; i < m_distribution.size() && j < distribution.size(); ++i, ++j) { if (m_distribution.size() < distribution.size()) { // If the new distribution is larger than the old one, reattach all nodes in // the new distribution that were inserted. for ( ; j < distribution.size() && m_distribution.at(i) != distribution.at(j); ++j) distribution.at(j)->lazyReattachIfAttached(); } else if (m_distribution.size() > distribution.size()) { // If the old distribution is larger than the new one, reattach all nodes in // the old distribution that were removed. for ( ; i < m_distribution.size() && m_distribution.at(i) != distribution.at(j); ++i) m_distribution.at(i)->lazyReattachIfAttached(); } else if (m_distribution.at(i) != distribution.at(j)) { // If both distributions are the same length reattach both old and new. m_distribution.at(i)->lazyReattachIfAttached(); distribution.at(j)->lazyReattachIfAttached(); } } // If we hit the end of either list above we need to reattach all remaining nodes. for ( ; i < m_distribution.size(); ++i) m_distribution.at(i)->lazyReattachIfAttached(); for ( ; j < distribution.size(); ++j) distribution.at(j)->lazyReattachIfAttached(); m_distribution.swap(distribution); m_distribution.shrinkToFit(); } void InsertionPoint::attach(const AttachContext& context) { // We need to attach the distribution here so that they're inserted in the right order // otherwise the n^2 protection inside RenderTreeBuilder will cause them to be // inserted in the wrong place later. This also lets distributed nodes benefit from // the n^2 protection. for (size_t i = 0; i < m_distribution.size(); ++i) { if (m_distribution.at(i)->needsAttach()) m_distribution.at(i)->attach(context); } HTMLElement::attach(context); } void InsertionPoint::detach(const AttachContext& context) { for (size_t i = 0; i < m_distribution.size(); ++i) m_distribution.at(i)->lazyReattachIfAttached(); HTMLElement::detach(context); } void InsertionPoint::willRecalcStyle(StyleRecalcChange change) { if (change < Inherit) return; for (size_t i = 0; i < m_distribution.size(); ++i) m_distribution.at(i)->setNeedsStyleRecalc(LocalStyleChange); } bool InsertionPoint::shouldUseFallbackElements() const { return isActive() && !hasDistribution(); } bool InsertionPoint::canBeActive() const { if (!isInShadowTree()) return false; for (Node* node = parentNode(); node; node = node->parentNode()) { if (node->isInsertionPoint()) return false; } return true; } bool InsertionPoint::isActive() const { if (!canBeActive()) return false; ShadowRoot* shadowRoot = containingShadowRoot(); ASSERT(shadowRoot); if (!hasTagName(shadowTag) || shadowRoot->descendantShadowElementCount() <= 1) return true; // Slow path only when there are more than one shadow elements in a shadow tree. That should be a rare case. const Vector<RefPtr<InsertionPoint> >& insertionPoints = shadowRoot->descendantInsertionPoints(); for (size_t i = 0; i < insertionPoints.size(); ++i) { InsertionPoint* point = insertionPoints[i].get(); if (point->hasTagName(shadowTag)) return point == this; } return true; } bool InsertionPoint::isShadowInsertionPoint() const { return hasTagName(shadowTag) && isActive(); } bool InsertionPoint::isContentInsertionPoint() const { return hasTagName(contentTag) && isActive(); } PassRefPtr<NodeList> InsertionPoint::getDistributedNodes() { document().updateDistributionForNodeIfNeeded(this); Vector<RefPtr<Node> > nodes; nodes.reserveInitialCapacity(m_distribution.size()); for (size_t i = 0; i < m_distribution.size(); ++i) nodes.uncheckedAppend(m_distribution.at(i)); return StaticNodeList::adopt(nodes); } bool InsertionPoint::rendererIsNeeded(const RenderStyle& style) { return !isActive() && HTMLElement::rendererIsNeeded(style); } void InsertionPoint::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) { HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta); if (ShadowRoot* root = containingShadowRoot()) { if (ElementShadow* rootOwner = root->owner()) rootOwner->setNeedsDistributionRecalc(); } } Node::InsertionNotificationRequest InsertionPoint::insertedInto(ContainerNode* insertionPoint) { HTMLElement::insertedInto(insertionPoint); if (ShadowRoot* root = containingShadowRoot()) { if (ElementShadow* rootOwner = root->owner()) { rootOwner->setNeedsDistributionRecalc(); if (canBeActive() && !m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) { m_registeredWithShadowRoot = true; root->didAddInsertionPoint(this); rootOwner->didAffectApplyAuthorStyles(); if (canAffectSelector()) rootOwner->willAffectSelector(); } } } return InsertionDone; } void InsertionPoint::removedFrom(ContainerNode* insertionPoint) { ShadowRoot* root = containingShadowRoot(); if (!root) root = insertionPoint->containingShadowRoot(); if (root) { if (ElementShadow* rootOwner = root->owner()) rootOwner->setNeedsDistributionRecalc(); } // host can be null when removedFrom() is called from ElementShadow destructor. ElementShadow* rootOwner = root ? root->owner() : 0; // Since this insertion point is no longer visible from the shadow subtree, it need to clean itself up. clearDistribution(); if (m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) { ASSERT(root); m_registeredWithShadowRoot = false; root->didRemoveInsertionPoint(this); if (rootOwner) { rootOwner->didAffectApplyAuthorStyles(); if (canAffectSelector()) rootOwner->willAffectSelector(); } } HTMLElement::removedFrom(insertionPoint); } void InsertionPoint::parseAttribute(const QualifiedName& name, const AtomicString& value) { if (name == reset_style_inheritanceAttr) { if (!inDocument() || !isActive()) return; containingShadowRoot()->host()->setNeedsStyleRecalc(); } else HTMLElement::parseAttribute(name, value); } bool InsertionPoint::resetStyleInheritance() const { return fastHasAttribute(reset_style_inheritanceAttr); } void InsertionPoint::setResetStyleInheritance(bool value) { setBooleanAttribute(reset_style_inheritanceAttr, value); } const InsertionPoint* resolveReprojection(const Node* projectedNode) { ASSERT(projectedNode); const InsertionPoint* insertionPoint = 0; const Node* current = projectedNode; ElementShadow* lastElementShadow = 0; while (true) { ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*current); if (!shadow || shadow == lastElementShadow) break; lastElementShadow = shadow; const InsertionPoint* insertedTo = shadow->finalDestinationInsertionPointFor(projectedNode); if (!insertedTo) break; ASSERT(current != insertedTo); current = insertedTo; insertionPoint = insertedTo; } return insertionPoint; } void collectDestinationInsertionPoints(const Node& node, Vector<InsertionPoint*, 8>& results) { const Node* current = &node; ElementShadow* lastElementShadow = 0; while (true) { ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*current); if (!shadow || shadow == lastElementShadow) return; lastElementShadow = shadow; const DestinationInsertionPoints* insertionPoints = shadow->destinationInsertionPointsFor(&node); if (!insertionPoints) return; for (size_t i = 0; i < insertionPoints->size(); ++i) results.append(insertionPoints->at(i).get()); ASSERT(current != insertionPoints->last().get()); current = insertionPoints->last().get(); } } } // namespace WebCore <commit_msg>Fix a crash by removing an assertion in InsertionPoint::isActive().<commit_after>/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/dom/shadow/InsertionPoint.h" #include "HTMLNames.h" #include "core/dom/ElementTraversal.h" #include "core/dom/QualifiedName.h" #include "core/dom/StaticNodeList.h" #include "core/dom/shadow/ElementShadow.h" namespace WebCore { using namespace HTMLNames; InsertionPoint::InsertionPoint(const QualifiedName& tagName, Document& document) : HTMLElement(tagName, document, CreateInsertionPoint) , m_registeredWithShadowRoot(false) { setHasCustomStyleCallbacks(); } InsertionPoint::~InsertionPoint() { } void InsertionPoint::setDistribution(ContentDistribution& distribution) { if (shouldUseFallbackElements()) { for (Node* child = firstChild(); child; child = child->nextSibling()) child->lazyReattachIfAttached(); } // Attempt not to reattach nodes that would be distributed to the exact same // location by comparing the old and new distributions. size_t i = 0; size_t j = 0; for ( ; i < m_distribution.size() && j < distribution.size(); ++i, ++j) { if (m_distribution.size() < distribution.size()) { // If the new distribution is larger than the old one, reattach all nodes in // the new distribution that were inserted. for ( ; j < distribution.size() && m_distribution.at(i) != distribution.at(j); ++j) distribution.at(j)->lazyReattachIfAttached(); } else if (m_distribution.size() > distribution.size()) { // If the old distribution is larger than the new one, reattach all nodes in // the old distribution that were removed. for ( ; i < m_distribution.size() && m_distribution.at(i) != distribution.at(j); ++i) m_distribution.at(i)->lazyReattachIfAttached(); } else if (m_distribution.at(i) != distribution.at(j)) { // If both distributions are the same length reattach both old and new. m_distribution.at(i)->lazyReattachIfAttached(); distribution.at(j)->lazyReattachIfAttached(); } } // If we hit the end of either list above we need to reattach all remaining nodes. for ( ; i < m_distribution.size(); ++i) m_distribution.at(i)->lazyReattachIfAttached(); for ( ; j < distribution.size(); ++j) distribution.at(j)->lazyReattachIfAttached(); m_distribution.swap(distribution); m_distribution.shrinkToFit(); } void InsertionPoint::attach(const AttachContext& context) { // We need to attach the distribution here so that they're inserted in the right order // otherwise the n^2 protection inside RenderTreeBuilder will cause them to be // inserted in the wrong place later. This also lets distributed nodes benefit from // the n^2 protection. for (size_t i = 0; i < m_distribution.size(); ++i) { if (m_distribution.at(i)->needsAttach()) m_distribution.at(i)->attach(context); } HTMLElement::attach(context); } void InsertionPoint::detach(const AttachContext& context) { for (size_t i = 0; i < m_distribution.size(); ++i) m_distribution.at(i)->lazyReattachIfAttached(); HTMLElement::detach(context); } void InsertionPoint::willRecalcStyle(StyleRecalcChange change) { if (change < Inherit) return; for (size_t i = 0; i < m_distribution.size(); ++i) m_distribution.at(i)->setNeedsStyleRecalc(LocalStyleChange); } bool InsertionPoint::shouldUseFallbackElements() const { return isActive() && !hasDistribution(); } bool InsertionPoint::canBeActive() const { if (!isInShadowTree()) return false; for (Node* node = parentNode(); node; node = node->parentNode()) { if (node->isInsertionPoint()) return false; } return true; } bool InsertionPoint::isActive() const { if (!canBeActive()) return false; ShadowRoot* shadowRoot = containingShadowRoot(); if (!shadowRoot) return false; if (!hasTagName(shadowTag) || shadowRoot->descendantShadowElementCount() <= 1) return true; // Slow path only when there are more than one shadow elements in a shadow tree. That should be a rare case. const Vector<RefPtr<InsertionPoint> >& insertionPoints = shadowRoot->descendantInsertionPoints(); for (size_t i = 0; i < insertionPoints.size(); ++i) { InsertionPoint* point = insertionPoints[i].get(); if (point->hasTagName(shadowTag)) return point == this; } return true; } bool InsertionPoint::isShadowInsertionPoint() const { return hasTagName(shadowTag) && isActive(); } bool InsertionPoint::isContentInsertionPoint() const { return hasTagName(contentTag) && isActive(); } PassRefPtr<NodeList> InsertionPoint::getDistributedNodes() { document().updateDistributionForNodeIfNeeded(this); Vector<RefPtr<Node> > nodes; nodes.reserveInitialCapacity(m_distribution.size()); for (size_t i = 0; i < m_distribution.size(); ++i) nodes.uncheckedAppend(m_distribution.at(i)); return StaticNodeList::adopt(nodes); } bool InsertionPoint::rendererIsNeeded(const RenderStyle& style) { return !isActive() && HTMLElement::rendererIsNeeded(style); } void InsertionPoint::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) { HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta); if (ShadowRoot* root = containingShadowRoot()) { if (ElementShadow* rootOwner = root->owner()) rootOwner->setNeedsDistributionRecalc(); } } Node::InsertionNotificationRequest InsertionPoint::insertedInto(ContainerNode* insertionPoint) { HTMLElement::insertedInto(insertionPoint); if (ShadowRoot* root = containingShadowRoot()) { if (ElementShadow* rootOwner = root->owner()) { rootOwner->setNeedsDistributionRecalc(); if (canBeActive() && !m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) { m_registeredWithShadowRoot = true; root->didAddInsertionPoint(this); rootOwner->didAffectApplyAuthorStyles(); if (canAffectSelector()) rootOwner->willAffectSelector(); } } } return InsertionDone; } void InsertionPoint::removedFrom(ContainerNode* insertionPoint) { ShadowRoot* root = containingShadowRoot(); if (!root) root = insertionPoint->containingShadowRoot(); if (root) { if (ElementShadow* rootOwner = root->owner()) rootOwner->setNeedsDistributionRecalc(); } // host can be null when removedFrom() is called from ElementShadow destructor. ElementShadow* rootOwner = root ? root->owner() : 0; // Since this insertion point is no longer visible from the shadow subtree, it need to clean itself up. clearDistribution(); if (m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) { ASSERT(root); m_registeredWithShadowRoot = false; root->didRemoveInsertionPoint(this); if (rootOwner) { rootOwner->didAffectApplyAuthorStyles(); if (canAffectSelector()) rootOwner->willAffectSelector(); } } HTMLElement::removedFrom(insertionPoint); } void InsertionPoint::parseAttribute(const QualifiedName& name, const AtomicString& value) { if (name == reset_style_inheritanceAttr) { if (!inDocument() || !isActive()) return; containingShadowRoot()->host()->setNeedsStyleRecalc(); } else HTMLElement::parseAttribute(name, value); } bool InsertionPoint::resetStyleInheritance() const { return fastHasAttribute(reset_style_inheritanceAttr); } void InsertionPoint::setResetStyleInheritance(bool value) { setBooleanAttribute(reset_style_inheritanceAttr, value); } const InsertionPoint* resolveReprojection(const Node* projectedNode) { ASSERT(projectedNode); const InsertionPoint* insertionPoint = 0; const Node* current = projectedNode; ElementShadow* lastElementShadow = 0; while (true) { ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*current); if (!shadow || shadow == lastElementShadow) break; lastElementShadow = shadow; const InsertionPoint* insertedTo = shadow->finalDestinationInsertionPointFor(projectedNode); if (!insertedTo) break; ASSERT(current != insertedTo); current = insertedTo; insertionPoint = insertedTo; } return insertionPoint; } void collectDestinationInsertionPoints(const Node& node, Vector<InsertionPoint*, 8>& results) { const Node* current = &node; ElementShadow* lastElementShadow = 0; while (true) { ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*current); if (!shadow || shadow == lastElementShadow) return; lastElementShadow = shadow; const DestinationInsertionPoints* insertionPoints = shadow->destinationInsertionPointsFor(&node); if (!insertionPoints) return; for (size_t i = 0; i < insertionPoints->size(); ++i) results.append(insertionPoints->at(i).get()); ASSERT(current != insertionPoints->last().get()); current = insertionPoints->last().get(); } } } // namespace WebCore <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2016-present ScyllaDB * * Modified by 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 <chrono> #include "cql3/statements/prepared_statement.hh" #include "tracing/trace_state.hh" #include "tracing/trace_keyspace_helper.hh" #include "service/storage_proxy.hh" #include "to_string.hh" #include "timestamp.hh" #include "cql3/values.hh" #include "cql3/query_options.hh" #include "utils/UUID_gen.hh" namespace tracing { logging::logger trace_state_logger("trace_state"); struct trace_state::params_values { std::optional<inet_address_vector_replica_set> batchlog_endpoints; std::optional<api::timestamp_type> user_timestamp; std::vector<sstring> queries; std::optional<db::consistency_level> cl; std::optional<db::consistency_level> serial_cl; std::optional<int32_t> page_size; std::vector<prepared_checked_weak_ptr> prepared_statements; std::vector<std::optional<std::vector<sstring_view>>> query_option_names; std::vector<std::vector<cql3::raw_value_view>> query_option_values; }; trace_state::params_values* trace_state::params_ptr::get_ptr_safe() { if (!_vals) { _vals = std::unique_ptr<params_values, params_values_deleter>(new params_values, params_values_deleter()); } return _vals.get(); } void trace_state::params_values_deleter::operator()(params_values* pv) { delete pv; } void trace_state::init_session_records( trace_type type, std::chrono::seconds slow_query_ttl, std::optional<utils::UUID> session_id, span_id parent_id) { _records = make_lw_shared<one_session_records>(); _records->session_id = session_id ? *session_id : utils::UUID_gen::get_time_UUID(); if (full_tracing()) { if (!log_slow_query()) { _records->ttl = ttl_by_type(type); } else { _records->ttl = std::max(ttl_by_type(type), slow_query_ttl); } } else { _records->ttl = slow_query_ttl; } _records->session_rec.command = type; _records->session_rec.slow_query_record_ttl = slow_query_ttl; _records->my_span_id = span_id::make_span_id(); _records->parent_id = parent_id; } void trace_state::set_batchlog_endpoints(const inet_address_vector_replica_set& val) { _params_ptr->batchlog_endpoints.emplace(val); } void trace_state::set_consistency_level(db::consistency_level val) { _params_ptr->cl.emplace(val); } void trace_state::set_optional_serial_consistency_level(const std::optional<db::consistency_level>& val) { if (val) { _params_ptr->serial_cl.emplace(*val); } } void trace_state::set_page_size(int32_t val) { if (val > 0) { _params_ptr->page_size.emplace(val); } } void trace_state::set_request_size(size_t s) noexcept { _records->session_rec.request_size = s; } void trace_state::set_response_size(size_t s) noexcept { _records->session_rec.response_size = s; } void trace_state::add_query(sstring_view val) { _params_ptr->queries.emplace_back(std::move(val)); } void trace_state::add_session_param(sstring_view key, sstring_view val) { _records->session_rec.parameters.emplace(std::move(key), std::move(val)); } void trace_state::set_user_timestamp(api::timestamp_type val) { _params_ptr->user_timestamp.emplace(val); } void trace_state::add_prepared_statement(prepared_checked_weak_ptr& prepared) { _params_ptr->prepared_statements.emplace_back(prepared->checked_weak_from_this()); } void trace_state::add_prepared_query_options(const cql3::query_options& prepared_options_ptr) { if (_params_ptr->prepared_statements.empty()) { throw std::logic_error("Tracing a prepared statement but no prepared statement is stored"); } _params_ptr->query_option_names.reserve(_params_ptr->prepared_statements.size()); _params_ptr->query_option_values.reserve(_params_ptr->prepared_statements.size()); for (size_t i = 0; i < _params_ptr->prepared_statements.size(); ++i) { _params_ptr->query_option_names.emplace_back(prepared_options_ptr.for_statement(i).get_names()); _params_ptr->query_option_values.emplace_back(prepared_options_ptr.for_statement(i).get_values()); } } void trace_state::build_parameters_map() { if (!_params_ptr) { return; } auto& params_map = _records->session_rec.parameters; params_values& vals = *_params_ptr; if (vals.batchlog_endpoints) { params_map.emplace("batch_endpoints", join(sstring(","), *vals.batchlog_endpoints | boost::adaptors::transformed([](gms::inet_address ep) {return seastar::format("/{}", ep);}))); } if (vals.cl) { params_map.emplace("consistency_level", seastar::format("{}", *vals.cl)); } if (vals.serial_cl) { params_map.emplace("serial_consistency_level", seastar::format("{}", *vals.serial_cl)); } if (vals.page_size) { params_map.emplace("page_size", seastar::format("{:d}", *vals.page_size)); } auto& queries = vals.queries; if (!queries.empty()) { if (queries.size() == 1) { params_map.emplace("query", queries[0]); } else { // BATCH for (size_t i = 0; i < queries.size(); ++i) { params_map.emplace(format("query[{:d}]", i), queries[i]); } } } if (vals.user_timestamp) { params_map.emplace("user_timestamp", seastar::format("{:d}", *vals.user_timestamp)); } auto& prepared_statements = vals.prepared_statements; if (!prepared_statements.empty()) { // Parameter's key in the map will be "param[X]" for a single query CQL command and "param[Y][X] for a multiple // queries CQL command, where X is an index of the parameter in a corresponding query and Y is an index of the // corresponding query in the BATCH. if (prepared_statements.size() == 1) { build_parameters_map_for_one_prepared(prepared_statements[0], vals.query_option_names[0], vals.query_option_values[0], "param"); } else { // BATCH for (size_t i = 0; i < prepared_statements.size(); ++i) { build_parameters_map_for_one_prepared(prepared_statements[i], vals.query_option_names[i], vals.query_option_values[i], format("param[{:d}]", i)); } } } } void trace_state::build_parameters_map_for_one_prepared(const prepared_checked_weak_ptr& prepared_ptr, std::optional<std::vector<sstring_view>>& names_opt, std::vector<cql3::raw_value_view>& values, const sstring& param_name_prefix) { auto& params_map = _records->session_rec.parameters; size_t i = 0; // Trace parameters native values representations only if the current prepared statement has not been evicted from the cache by the time we got here. // Such an eviction is a very unlikely event, however if it happens, since we are unable to recover their types, trace raw representations of the values. if (names_opt) { if (names_opt->size() != values.size()) { throw std::logic_error(format("Number of \"names\" ({}) doesn't match the number of positional variables ({})", names_opt->size(), values.size()).c_str()); } auto& names = names_opt.value(); for (; i < values.size(); ++i) { params_map.emplace(format("{}[{:d}]({})", param_name_prefix, i, names[i]), raw_value_to_sstring(values[i], prepared_ptr ? prepared_ptr->bound_names[i]->type : nullptr)); } } else { for (; i < values.size(); ++i) { params_map.emplace(format("{}[{:d}]", param_name_prefix, i), raw_value_to_sstring(values[i], prepared_ptr ? prepared_ptr->bound_names[i]->type : nullptr)); } } } trace_state::~trace_state() { if (!is_primary() && is_in_state(state::background)) { trace_state_logger.error("Secondary session is in a background state! session_id: {}", session_id()); } stop_foreground_and_write(); _local_tracing_ptr->end_session(); trace_state_logger.trace("{}: destructing", session_id()); } void trace_state::stop_foreground_and_write() noexcept { // Do nothing if state hasn't been initiated if (is_in_state(state::inactive)) { return; } if (is_in_state(state::foreground)) { auto e = elapsed(); _records->do_log_slow_query = should_log_slow_query(e); if (is_primary()) { // We don't account the session_record event when checking a limit // of maximum events per session because there may be only one such // event and we don't want to cripple the primary session by // "stealing" one trace() event from it. // // We do want to account them however. If for instance there are a // lot of tracing sessions that only open itself and then do nothing // - they will create a lot of session_record events and we do want // to handle this case properly. _records->consume_from_budget(); _records->session_rec.elapsed = e; // build_parameters_map() may throw. We don't want to record the // session's record in this case since its data may be incomplete. // These events should be really rare however, therefore we don't // want to optimize this flow (e.g. rollback the corresponding // events' records that have already been sent to I/O). if (should_write_records()) { try { build_parameters_map(); } catch (...) { // Bump up an error counter, drop any pending records and // continue ++_local_tracing_ptr->stats.trace_errors; _records->drop_records(); } } } set_state(state::background); } trace_state_logger.trace("{}: Current records count is {}", session_id(), _records->size()); if (should_write_records()) { _local_tracing_ptr->write_session_records(_records, write_on_close()); } else { _records->drop_records(); } } sstring trace_state::raw_value_to_sstring(const cql3::raw_value_view& v, const data_type& t) { static constexpr int max_val_bytes = 64; if (v.is_null()) { return "null"; } else if (v.is_unset_value()) { return "unset value"; } else { return v.with_linearized([&] (bytes_view val) { sstring str_rep; if (t) { str_rep = t->to_string(to_bytes(val)); } else { trace_state_logger.trace("{}: data types are unavailable - tracing a raw value", session_id()); str_rep = to_hex(val); } if (str_rep.size() > max_val_bytes) { return format("{}...", str_rep.substr(0, max_val_bytes)); } else { return str_rep; } }); } } } <commit_msg>tracing: unify prepared statement info into a single struct<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2016-present ScyllaDB * * Modified by 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 <chrono> #include "cql3/statements/prepared_statement.hh" #include "tracing/trace_state.hh" #include "tracing/trace_keyspace_helper.hh" #include "service/storage_proxy.hh" #include "to_string.hh" #include "timestamp.hh" #include "cql3/values.hh" #include "cql3/query_options.hh" #include "utils/UUID_gen.hh" namespace tracing { logging::logger trace_state_logger("trace_state"); struct trace_state::params_values { struct prepared_statement_info { prepared_checked_weak_ptr statement; std::optional<std::vector<sstring_view>> query_option_names; std::vector<cql3::raw_value_view> query_option_values; explicit prepared_statement_info(prepared_checked_weak_ptr statement) : statement(std::move(statement)) {} }; std::optional<inet_address_vector_replica_set> batchlog_endpoints; std::optional<api::timestamp_type> user_timestamp; std::vector<sstring> queries; std::optional<db::consistency_level> cl; std::optional<db::consistency_level> serial_cl; std::optional<int32_t> page_size; std::vector<prepared_statement_info> prepared_statements; }; trace_state::params_values* trace_state::params_ptr::get_ptr_safe() { if (!_vals) { _vals = std::unique_ptr<params_values, params_values_deleter>(new params_values, params_values_deleter()); } return _vals.get(); } void trace_state::params_values_deleter::operator()(params_values* pv) { delete pv; } void trace_state::init_session_records( trace_type type, std::chrono::seconds slow_query_ttl, std::optional<utils::UUID> session_id, span_id parent_id) { _records = make_lw_shared<one_session_records>(); _records->session_id = session_id ? *session_id : utils::UUID_gen::get_time_UUID(); if (full_tracing()) { if (!log_slow_query()) { _records->ttl = ttl_by_type(type); } else { _records->ttl = std::max(ttl_by_type(type), slow_query_ttl); } } else { _records->ttl = slow_query_ttl; } _records->session_rec.command = type; _records->session_rec.slow_query_record_ttl = slow_query_ttl; _records->my_span_id = span_id::make_span_id(); _records->parent_id = parent_id; } void trace_state::set_batchlog_endpoints(const inet_address_vector_replica_set& val) { _params_ptr->batchlog_endpoints.emplace(val); } void trace_state::set_consistency_level(db::consistency_level val) { _params_ptr->cl.emplace(val); } void trace_state::set_optional_serial_consistency_level(const std::optional<db::consistency_level>& val) { if (val) { _params_ptr->serial_cl.emplace(*val); } } void trace_state::set_page_size(int32_t val) { if (val > 0) { _params_ptr->page_size.emplace(val); } } void trace_state::set_request_size(size_t s) noexcept { _records->session_rec.request_size = s; } void trace_state::set_response_size(size_t s) noexcept { _records->session_rec.response_size = s; } void trace_state::add_query(sstring_view val) { _params_ptr->queries.emplace_back(std::move(val)); } void trace_state::add_session_param(sstring_view key, sstring_view val) { _records->session_rec.parameters.emplace(std::move(key), std::move(val)); } void trace_state::set_user_timestamp(api::timestamp_type val) { _params_ptr->user_timestamp.emplace(val); } void trace_state::add_prepared_statement(prepared_checked_weak_ptr& prepared) { _params_ptr->prepared_statements.emplace_back(prepared->checked_weak_from_this()); } void trace_state::add_prepared_query_options(const cql3::query_options& prepared_options_ptr) { if (_params_ptr->prepared_statements.empty()) { throw std::logic_error("Tracing a prepared statement but no prepared statement is stored"); } for (size_t i = 0; i < _params_ptr->prepared_statements.size(); ++i) { const cql3::query_options& opts = prepared_options_ptr.for_statement(i); _params_ptr->prepared_statements[i].query_option_names = opts.get_names(); _params_ptr->prepared_statements[i].query_option_values = opts.get_values(); } } void trace_state::build_parameters_map() { if (!_params_ptr) { return; } auto& params_map = _records->session_rec.parameters; params_values& vals = *_params_ptr; if (vals.batchlog_endpoints) { params_map.emplace("batch_endpoints", join(sstring(","), *vals.batchlog_endpoints | boost::adaptors::transformed([](gms::inet_address ep) {return seastar::format("/{}", ep);}))); } if (vals.cl) { params_map.emplace("consistency_level", seastar::format("{}", *vals.cl)); } if (vals.serial_cl) { params_map.emplace("serial_consistency_level", seastar::format("{}", *vals.serial_cl)); } if (vals.page_size) { params_map.emplace("page_size", seastar::format("{:d}", *vals.page_size)); } auto& queries = vals.queries; if (!queries.empty()) { if (queries.size() == 1) { params_map.emplace("query", queries[0]); } else { // BATCH for (size_t i = 0; i < queries.size(); ++i) { params_map.emplace(format("query[{:d}]", i), queries[i]); } } } if (vals.user_timestamp) { params_map.emplace("user_timestamp", seastar::format("{:d}", *vals.user_timestamp)); } auto& prepared_statements = vals.prepared_statements; if (!prepared_statements.empty()) { // Parameter's key in the map will be "param[X]" for a single query CQL command and "param[Y][X] for a multiple // queries CQL command, where X is an index of the parameter in a corresponding query and Y is an index of the // corresponding query in the BATCH. if (prepared_statements.size() == 1) { auto& stmt_info = prepared_statements[0]; build_parameters_map_for_one_prepared(stmt_info.statement, stmt_info.query_option_names, stmt_info.query_option_values, "param"); } else { // BATCH for (size_t i = 0; i < prepared_statements.size(); ++i) { auto& stmt_info = prepared_statements[i]; build_parameters_map_for_one_prepared(stmt_info.statement, stmt_info.query_option_names, stmt_info.query_option_values, format("param[{:d}]", i)); } } } } void trace_state::build_parameters_map_for_one_prepared(const prepared_checked_weak_ptr& prepared_ptr, std::optional<std::vector<sstring_view>>& names_opt, std::vector<cql3::raw_value_view>& values, const sstring& param_name_prefix) { auto& params_map = _records->session_rec.parameters; size_t i = 0; // Trace parameters native values representations only if the current prepared statement has not been evicted from the cache by the time we got here. // Such an eviction is a very unlikely event, however if it happens, since we are unable to recover their types, trace raw representations of the values. if (names_opt) { if (names_opt->size() != values.size()) { throw std::logic_error(format("Number of \"names\" ({}) doesn't match the number of positional variables ({})", names_opt->size(), values.size()).c_str()); } auto& names = names_opt.value(); for (; i < values.size(); ++i) { params_map.emplace(format("{}[{:d}]({})", param_name_prefix, i, names[i]), raw_value_to_sstring(values[i], prepared_ptr ? prepared_ptr->bound_names[i]->type : nullptr)); } } else { for (; i < values.size(); ++i) { params_map.emplace(format("{}[{:d}]", param_name_prefix, i), raw_value_to_sstring(values[i], prepared_ptr ? prepared_ptr->bound_names[i]->type : nullptr)); } } } trace_state::~trace_state() { if (!is_primary() && is_in_state(state::background)) { trace_state_logger.error("Secondary session is in a background state! session_id: {}", session_id()); } stop_foreground_and_write(); _local_tracing_ptr->end_session(); trace_state_logger.trace("{}: destructing", session_id()); } void trace_state::stop_foreground_and_write() noexcept { // Do nothing if state hasn't been initiated if (is_in_state(state::inactive)) { return; } if (is_in_state(state::foreground)) { auto e = elapsed(); _records->do_log_slow_query = should_log_slow_query(e); if (is_primary()) { // We don't account the session_record event when checking a limit // of maximum events per session because there may be only one such // event and we don't want to cripple the primary session by // "stealing" one trace() event from it. // // We do want to account them however. If for instance there are a // lot of tracing sessions that only open itself and then do nothing // - they will create a lot of session_record events and we do want // to handle this case properly. _records->consume_from_budget(); _records->session_rec.elapsed = e; // build_parameters_map() may throw. We don't want to record the // session's record in this case since its data may be incomplete. // These events should be really rare however, therefore we don't // want to optimize this flow (e.g. rollback the corresponding // events' records that have already been sent to I/O). if (should_write_records()) { try { build_parameters_map(); } catch (...) { // Bump up an error counter, drop any pending records and // continue ++_local_tracing_ptr->stats.trace_errors; _records->drop_records(); } } } set_state(state::background); } trace_state_logger.trace("{}: Current records count is {}", session_id(), _records->size()); if (should_write_records()) { _local_tracing_ptr->write_session_records(_records, write_on_close()); } else { _records->drop_records(); } } sstring trace_state::raw_value_to_sstring(const cql3::raw_value_view& v, const data_type& t) { static constexpr int max_val_bytes = 64; if (v.is_null()) { return "null"; } else if (v.is_unset_value()) { return "unset value"; } else { return v.with_linearized([&] (bytes_view val) { sstring str_rep; if (t) { str_rep = t->to_string(to_bytes(val)); } else { trace_state_logger.trace("{}: data types are unavailable - tracing a raw value", session_id()); str_rep = to_hex(val); } if (str_rep.size() > max_val_bytes) { return format("{}...", str_rep.substr(0, max_val_bytes)); } else { return str_rep; } }); } } } <|endoftext|>
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*- commands/exportopenpgpcertstoservercommand.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2008 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <config-kleopatra.h> #include "exportopenpgpcertstoservercommand.h" #include "command_p.h" #include <utils/gnupg-helper.h> #include <kleo/cryptobackendfactory.h> #include <kleo/cryptoconfig.h> #include <gpgme++/key.h> #include <KLocale> #include <KMessageBox> using namespace Kleo; using namespace Kleo::Commands; using namespace GpgME; static bool haveKeyserverConfigured() { const Kleo::CryptoConfig * const config = Kleo::CryptoBackendFactory::instance()->config(); if ( !config ) return false; const Kleo::CryptoConfigEntry * const entry = config->entry( "gpg", "Keyserver", "keyserver" ); return entry && !entry->stringValue().isEmpty(); } ExportOpenPGPCertsToServerCommand::ExportOpenPGPCertsToServerCommand( KeyListController * c ) : GnuPGProcessCommand( c ) { } ExportOpenPGPCertsToServerCommand::ExportOpenPGPCertsToServerCommand( QAbstractItemView * v, KeyListController * c ) : GnuPGProcessCommand( v, c ) { } ExportOpenPGPCertsToServerCommand::~ExportOpenPGPCertsToServerCommand() {} bool ExportOpenPGPCertsToServerCommand::preStartHook( QWidget * parent ) const { if ( !haveKeyserverConfigured() ) if ( KMessageBox::warningContinueCancel( parent, i18nc("@info", "<para>No OpenPGP directory services have been configured.</para>" "<para>Since none is configured, <application>Kleopatra</application> will use " "<resource>keys.gnupg.net</resource> as the server to export to.</para>" "<para>You can configure OpenPGP directory servers in <application>Kleopatra</application>'s " "configuration dialog.</para>" "<para>Do you want to continue with <resource>keys.gnupg.net</resource> " "as the server to export to?</para>" ), i18n("OpenPGP Certitifcate Export"), KStandardGuiItem::cont(), KStandardGuiItem::cancel(), QLatin1String( "warn-export-openpgp-missing-keyserver" ) ) != KMessageBox::Continue ) return false; return KMessageBox::warningContinueCancel( parent, i18nc("@info", "<para>When OpenPGP certificates have been exported to a public directory server, " "it is nearly impossible to remove them again.</para>" "<para>Before exporting your key to a public directory server, make sure that you " "have created a revokation certificate so you can revoke the certificate if needed later.</para>" "<para>Are you sure you want to continue?</para>"), i18n("OpenPGP Certitifcate Export"), KStandardGuiItem::cont(), KStandardGuiItem::cancel(), QLatin1String( "warn-export-openpgp-nonrevocable" ) ) == KMessageBox::Continue; } QStringList ExportOpenPGPCertsToServerCommand::arguments() const { QStringList result; result << gpgPath(); if ( !haveKeyserverConfigured() ) result << "--keyserver" << "keys.gnupg.net"; result << "--send-keys"; Q_FOREACH( const Key & key, d->keys() ) result << key.primaryFingerprint(); return result; } QString ExportOpenPGPCertsToServerCommand::errorCaption() const { return i18n( "OpenPGP Certificate Export Error" ); } QString ExportOpenPGPCertsToServerCommand::successCaption() const { return i18n( "OpenPGP Certificate Export Finished" ); } QString ExportOpenPGPCertsToServerCommand::crashExitMessage( const QStringList & args ) const { return i18nc("@info", "<para>The GPG process that tried to export OpenPGP certificates " "ended prematurely because of an unexpected error.</para>" "<para>Please check the output of <icode>%1</icode> for details.</para>", args.join( " " ) ) ; } QString ExportOpenPGPCertsToServerCommand::errorExitMessage( const QStringList & args ) const { return i18nc("@info", "<para>An error occurred while trying to export OpenPGP certificates.</para> " "<para>The output from <command>%1</command> was: <message>%2</message></para>", args[0], errorString() ); } QString ExportOpenPGPCertsToServerCommand::successMessage( const QStringList & ) const { return i18n( "OpenPGP certificates exported successfully." ); } #include "moc_exportopenpgpcertstoservercommand.cpp" <commit_msg>typos, wording<commit_after>/* -*- mode: c++; c-basic-offset:4 -*- commands/exportopenpgpcertstoservercommand.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2008 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <config-kleopatra.h> #include "exportopenpgpcertstoservercommand.h" #include "command_p.h" #include <utils/gnupg-helper.h> #include <kleo/cryptobackendfactory.h> #include <kleo/cryptoconfig.h> #include <gpgme++/key.h> #include <KLocale> #include <KMessageBox> using namespace Kleo; using namespace Kleo::Commands; using namespace GpgME; static bool haveKeyserverConfigured() { const Kleo::CryptoConfig * const config = Kleo::CryptoBackendFactory::instance()->config(); if ( !config ) return false; const Kleo::CryptoConfigEntry * const entry = config->entry( "gpg", "Keyserver", "keyserver" ); return entry && !entry->stringValue().isEmpty(); } ExportOpenPGPCertsToServerCommand::ExportOpenPGPCertsToServerCommand( KeyListController * c ) : GnuPGProcessCommand( c ) { } ExportOpenPGPCertsToServerCommand::ExportOpenPGPCertsToServerCommand( QAbstractItemView * v, KeyListController * c ) : GnuPGProcessCommand( v, c ) { } ExportOpenPGPCertsToServerCommand::~ExportOpenPGPCertsToServerCommand() {} bool ExportOpenPGPCertsToServerCommand::preStartHook( QWidget * parent ) const { if ( !haveKeyserverConfigured() ) if ( KMessageBox::warningContinueCancel( parent, i18nc("@info", "<para>No OpenPGP directory services have been configured.</para>" "<para>Since none is configured, <application>Kleopatra</application> will use " "<resource>keys.gnupg.net</resource> as the server to export to.</para>" "<para>You can configure OpenPGP directory servers in <application>Kleopatra</application>'s " "configuration dialog.</para>" "<para>Do you want to continue with <resource>keys.gnupg.net</resource> " "as the server to export to?</para>" ), i18n("OpenPGP Certificate Export"), KStandardGuiItem::cont(), KStandardGuiItem::cancel(), QLatin1String( "warn-export-openpgp-missing-keyserver" ) ) != KMessageBox::Continue ) return false; return KMessageBox::warningContinueCancel( parent, i18nc("@info", "<para>When OpenPGP certificates have been exported to a public directory server, " "it is nearly impossible to remove them again.</para>" "<para>Before exporting your certificate to a public directory server, make sure that you " "have created a revocation certificate so you can revoke the certificate if needed later.</para>" "<para>Are you sure you want to continue?</para>"), i18n("OpenPGP Certificate Export"), KStandardGuiItem::cont(), KStandardGuiItem::cancel(), QLatin1String( "warn-export-openpgp-nonrevocable" ) ) == KMessageBox::Continue; } QStringList ExportOpenPGPCertsToServerCommand::arguments() const { QStringList result; result << gpgPath(); if ( !haveKeyserverConfigured() ) result << "--keyserver" << "keys.gnupg.net"; result << "--send-keys"; Q_FOREACH( const Key & key, d->keys() ) result << key.primaryFingerprint(); return result; } QString ExportOpenPGPCertsToServerCommand::errorCaption() const { return i18n( "OpenPGP Certificate Export Error" ); } QString ExportOpenPGPCertsToServerCommand::successCaption() const { return i18n( "OpenPGP Certificate Export Finished" ); } QString ExportOpenPGPCertsToServerCommand::crashExitMessage( const QStringList & args ) const { return i18nc("@info", "<para>The GPG process that tried to export OpenPGP certificates " "ended prematurely because of an unexpected error.</para>" "<para>Please check the output of <icode>%1</icode> for details.</para>", args.join( " " ) ) ; } QString ExportOpenPGPCertsToServerCommand::errorExitMessage( const QStringList & args ) const { return i18nc("@info", "<para>An error occurred while trying to export OpenPGP certificates.</para> " "<para>The output from <command>%1</command> was: <message>%2</message></para>", args[0], errorString() ); } QString ExportOpenPGPCertsToServerCommand::successMessage( const QStringList & ) const { return i18n( "OpenPGP certificates exported successfully." ); } #include "moc_exportopenpgpcertstoservercommand.cpp" <|endoftext|>
<commit_before>/* Copyright 2020 Google 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 https://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 "thread.h" #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) #include <windows.h> void CreateThread(void *(*start_routine) (void *), void *arg) { CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)start_routine, arg, 0, NULL); } #else #include <pthread.h> void CreateThread(void *(*start_routine) (void *), void *arg) { pthread_t thread_id; pthread_create(&thread_id, NULL, start_routine, arg); } #endif <commit_msg>Fix a handle leak<commit_after>/* Copyright 2020 Google 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 https://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 "thread.h" #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) #include <windows.h> void CreateThread(void *(*start_routine) (void *), void *arg) { HANDLE thread_handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)start_routine, arg, 0, NULL); // close the handle immediately to prevent handle leak if(thread_handle) CloseHandle(thread_handle); } #else #include <pthread.h> void CreateThread(void *(*start_routine) (void *), void *arg) { pthread_t thread_id; pthread_create(&thread_id, NULL, start_routine, arg); } #endif <|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 "content/renderer/render_widget_fullscreen_pepper.h" #include "base/message_loop.h" #include "content/common/view_messages.h" #include "content/renderer/renderer_gl_context.h" #include "content/renderer/gpu_channel_host.h" #include "content/renderer/pepper_platform_context_3d_impl.h" #include "content/renderer/render_thread.h" #include "gpu/command_buffer/client/gles2_implementation.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebCursorInfo.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebSize.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebWidget.h" #include "webkit/plugins/ppapi/plugin_delegate.h" #include "webkit/plugins/ppapi/ppapi_plugin_instance.h" using WebKit::WebCanvas; using WebKit::WebCompositionUnderline; using WebKit::WebCursorInfo; using WebKit::WebInputEvent; using WebKit::WebMouseEvent; using WebKit::WebPoint; using WebKit::WebRect; using WebKit::WebSize; using WebKit::WebString; using WebKit::WebTextDirection; using WebKit::WebTextInputType; using WebKit::WebVector; using WebKit::WebWidget; namespace { // WebWidget that simply wraps the pepper plugin. class PepperWidget : public WebWidget { public: PepperWidget(webkit::ppapi::PluginInstance* plugin, RenderWidgetFullscreenPepper* widget) : plugin_(plugin), widget_(widget), cursor_(WebCursorInfo::TypePointer) { } // WebWidget API virtual void close() { delete this; } virtual WebSize size() { return size_; } virtual void resize(const WebSize& size) { size_ = size; WebRect plugin_rect(0, 0, size_.width, size_.height); plugin_->ViewChanged(plugin_rect, plugin_rect); widget_->Invalidate(); } virtual void animate() { } virtual void layout() { } virtual void paint(WebCanvas* canvas, const WebRect& rect) { WebRect plugin_rect(0, 0, size_.width, size_.height); plugin_->Paint(canvas, plugin_rect, rect); } virtual void composite(bool finish) { RendererGLContext* context = widget_->context(); DCHECK(context); gpu::gles2::GLES2Implementation* gl = context->GetImplementation(); unsigned int texture = plugin_->GetBackingTextureId(); gl->BindTexture(GL_TEXTURE_2D, texture); gl->DrawArrays(GL_TRIANGLES, 0, 3); context->SwapBuffers(); } virtual void themeChanged() { NOTIMPLEMENTED(); } virtual bool handleInputEvent(const WebInputEvent& event) { bool result = plugin_->HandleInputEvent(event, &cursor_); // For normal web pages, WebViewImpl does input event translations and // generates context menu events. Since we don't have a WebView, we need to // do the necessary translation ourselves. if (WebInputEvent::isMouseEventType(event.type)) { const WebMouseEvent& mouse_event = reinterpret_cast<const WebMouseEvent&>(event); bool send_context_menu_event = false; // On Mac/Linux, we handle it on mouse down. // On Windows, we handle it on mouse up. #if defined(OS_WIN) send_context_menu_event = mouse_event.type == WebInputEvent::MouseUp && mouse_event.button == WebMouseEvent::ButtonRight; #elif defined(OS_MACOSX) send_context_menu_event = mouse_event.type == WebInputEvent::MouseDown && (mouse_event.button == WebMouseEvent::ButtonRight || (mouse_event.button == WebMouseEvent::ButtonLeft && mouse_event.modifiers & WebMouseEvent::ControlKey)); #else send_context_menu_event = mouse_event.type == WebInputEvent::MouseDown && mouse_event.button == WebMouseEvent::ButtonRight; #endif if (send_context_menu_event) { WebMouseEvent context_menu_event(mouse_event); context_menu_event.type = WebInputEvent::ContextMenu; plugin_->HandleInputEvent(context_menu_event, &cursor_); } } return result; } virtual void mouseCaptureLost() { NOTIMPLEMENTED(); } virtual void setFocus(bool focus) { NOTIMPLEMENTED(); } // TODO(piman): figure out IME and implement these if necessary. virtual bool setComposition( const WebString& text, const WebVector<WebCompositionUnderline>& underlines, int selectionStart, int selectionEnd) { return false; } virtual bool confirmComposition() { return false; } virtual bool compositionRange(size_t* location, size_t* length) { return false; } virtual bool confirmComposition(const WebString& text) { return false; } virtual WebTextInputType textInputType() { return WebKit::WebTextInputTypeNone; } virtual WebRect caretOrSelectionBounds() { return WebRect(); } virtual bool selectionRange(WebPoint& start, WebPoint& end) const { return false; } virtual bool selectionRange(size_t *location, size_t *length) { return false; } virtual void setTextDirection(WebTextDirection) { } virtual bool isAcceleratedCompositingActive() const { return widget_->context() && (plugin_->GetBackingTextureId() != 0); } private: scoped_refptr<webkit::ppapi::PluginInstance> plugin_; RenderWidgetFullscreenPepper* widget_; WebSize size_; WebCursorInfo cursor_; DISALLOW_COPY_AND_ASSIGN(PepperWidget); }; void DestroyContext(RendererGLContext* context, GLuint program, GLuint buffer) { DCHECK(context); gpu::gles2::GLES2Implementation* gl = context->GetImplementation(); if (program) gl->DeleteProgram(program); if (buffer) gl->DeleteBuffers(1, &buffer); delete context; } } // anonymous namespace // static RenderWidgetFullscreenPepper* RenderWidgetFullscreenPepper::Create( int32 opener_id, RenderThreadBase* render_thread, webkit::ppapi::PluginInstance* plugin, const GURL& active_url) { DCHECK_NE(MSG_ROUTING_NONE, opener_id); scoped_refptr<RenderWidgetFullscreenPepper> widget( new RenderWidgetFullscreenPepper(render_thread, plugin, active_url)); widget->Init(opener_id); return widget.release(); } RenderWidgetFullscreenPepper::RenderWidgetFullscreenPepper( RenderThreadBase* render_thread, webkit::ppapi::PluginInstance* plugin, const GURL& active_url) : RenderWidgetFullscreen(render_thread), active_url_(active_url), plugin_(plugin), context_(NULL), buffer_(0), program_(0) { } RenderWidgetFullscreenPepper::~RenderWidgetFullscreenPepper() { if (context_) DestroyContext(context_, program_, buffer_); } void RenderWidgetFullscreenPepper::Invalidate() { InvalidateRect(gfx::Rect(size_.width(), size_.height())); } void RenderWidgetFullscreenPepper::InvalidateRect(const WebKit::WebRect& rect) { if (CheckCompositing()) { scheduleComposite(); } else { didInvalidateRect(rect); } } void RenderWidgetFullscreenPepper::ScrollRect( int dx, int dy, const WebKit::WebRect& rect) { if (CheckCompositing()) { scheduleComposite(); } else { didScrollRect(dx, dy, rect); } } void RenderWidgetFullscreenPepper::Destroy() { // This function is called by the plugin instance as it's going away, so reset // plugin_ to NULL to avoid calling into a dangling pointer e.g. on Close(). plugin_ = NULL; Send(new ViewHostMsg_Close(routing_id_)); } webkit::ppapi::PluginDelegate::PlatformContext3D* RenderWidgetFullscreenPepper::CreateContext3D() { if (!context_) { CreateContext(); } if (!context_) return NULL; return new PlatformContext3DImpl(context_); } void RenderWidgetFullscreenPepper::DidInitiatePaint() { if (plugin_) plugin_->ViewInitiatedPaint(); } void RenderWidgetFullscreenPepper::DidFlushPaint() { if (plugin_) plugin_->ViewFlushedPaint(); } void RenderWidgetFullscreenPepper::Close() { // If the fullscreen window is closed (e.g. user pressed escape), reset to // normal mode. if (plugin_) plugin_->SetFullscreen(false, false); } webkit::ppapi::PluginInstance* RenderWidgetFullscreenPepper::GetBitmapForOptimizedPluginPaint( const gfx::Rect& paint_bounds, TransportDIB** dib, gfx::Rect* location, gfx::Rect* clip) { if (plugin_ && plugin_->GetBitmapForOptimizedPluginPaint(paint_bounds, dib, location, clip)) return plugin_; return NULL; } void RenderWidgetFullscreenPepper::OnResize(const gfx::Size& size, const gfx::Rect& resizer_rect) { if (context_) { gpu::gles2::GLES2Implementation* gl = context_->GetImplementation(); #if defined(OS_MACOSX) context_->ResizeOnscreen(size); #else gl->ResizeCHROMIUM(size.width(), size.height()); #endif gl->Viewport(0, 0, size.width(), size.height()); } RenderWidget::OnResize(size, resizer_rect); } WebWidget* RenderWidgetFullscreenPepper::CreateWebWidget() { return new PepperWidget(plugin_, this); } void RenderWidgetFullscreenPepper::CreateContext() { DCHECK(!context_); RenderThread* render_thread = RenderThread::current(); DCHECK(render_thread); GpuChannelHost* host = render_thread->EstablishGpuChannelSync( content::CAUSE_FOR_GPU_LAUNCH_RENDERWIDGETFULLSCREENPEPPER_CREATECONTEXT); if (!host) return; const int32 attribs[] = { RendererGLContext::ALPHA_SIZE, 8, RendererGLContext::DEPTH_SIZE, 0, RendererGLContext::STENCIL_SIZE, 0, RendererGLContext::SAMPLES, 0, RendererGLContext::SAMPLE_BUFFERS, 0, RendererGLContext::NONE, }; context_ = RendererGLContext::CreateViewContext( host, compositing_surface(), routing_id(), "GL_OES_packed_depth_stencil GL_OES_depth24", attribs, active_url_); if (!context_) return; if (!InitContext()) { DestroyContext(context_, program_, buffer_); context_ = NULL; return; } context_->SetSwapBuffersCallback( NewCallback(this, &RenderWidgetFullscreenPepper::DidFlushPaint)); context_->SetContextLostCallback( NewCallback(this, &RenderWidgetFullscreenPepper::OnLostContext)); } namespace { const char kVertexShader[] = "attribute vec2 in_tex_coord;\n" "varying vec2 tex_coord;\n" "void main() {\n" " gl_Position = vec4(in_tex_coord.x * 2. - 1.,\n" " in_tex_coord.y * 2. - 1.,\n" " 0.,\n" " 1.);\n" " tex_coord = vec2(in_tex_coord.x, in_tex_coord.y);\n" "}\n"; const char kFragmentShader[] = "precision mediump float;\n" "varying vec2 tex_coord;\n" "uniform sampler2D in_texture;\n" "void main() {\n" " gl_FragColor = texture2D(in_texture, tex_coord);\n" "}\n"; GLuint CreateShaderFromSource(gpu::gles2::GLES2Implementation* gl, GLenum type, const char* source) { GLuint shader = gl->CreateShader(type); gl->ShaderSource(shader, 1, &source, NULL); gl->CompileShader(shader); int status; gl->GetShaderiv(shader, GL_COMPILE_STATUS, &status); if (!status) { int size = 0; gl->GetShaderiv(shader, GL_INFO_LOG_LENGTH, &size); scoped_array<char> log(new char[size]); gl->GetShaderInfoLog(shader, size, NULL, log.get()); DLOG(ERROR) << "Compilation failed: " << log.get(); gl->DeleteShader(shader); shader = 0; } return shader; } const float kTexCoords[] = { 0.f, 0.f, 0.f, 2.f, 2.f, 0.f, }; } // anonymous namespace bool RenderWidgetFullscreenPepper::InitContext() { gpu::gles2::GLES2Implementation* gl = context_->GetImplementation(); program_ = gl->CreateProgram(); GLuint vertex_shader = CreateShaderFromSource(gl, GL_VERTEX_SHADER, kVertexShader); if (!vertex_shader) return false; gl->AttachShader(program_, vertex_shader); gl->DeleteShader(vertex_shader); GLuint fragment_shader = CreateShaderFromSource(gl, GL_FRAGMENT_SHADER, kFragmentShader); if (!fragment_shader) return false; gl->AttachShader(program_, fragment_shader); gl->DeleteShader(fragment_shader); gl->BindAttribLocation(program_, 0, "in_tex_coord"); gl->LinkProgram(program_); int status; gl->GetProgramiv(program_, GL_LINK_STATUS, &status); if (!status) { int size = 0; gl->GetProgramiv(program_, GL_INFO_LOG_LENGTH, &size); scoped_array<char> log(new char[size]); gl->GetProgramInfoLog(program_, size, NULL, log.get()); DLOG(ERROR) << "Link failed: " << log.get(); return false; } gl->UseProgram(program_); int texture_location = gl->GetUniformLocation(program_, "in_texture"); gl->Uniform1i(texture_location, 0); gl->GenBuffers(1, &buffer_); gl->BindBuffer(GL_ARRAY_BUFFER, buffer_); gl->BufferData(GL_ARRAY_BUFFER, sizeof(kTexCoords), kTexCoords, GL_STATIC_DRAW); gl->VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL); gl->EnableVertexAttribArray(0); return true; } bool RenderWidgetFullscreenPepper::CheckCompositing() { bool compositing = webwidget_->isAcceleratedCompositingActive(); if (compositing != is_accelerated_compositing_active_) { didActivateAcceleratedCompositing(compositing); } return compositing; } void RenderWidgetFullscreenPepper::OnLostContext() { if (!context_) return; // Destroy the context later, in case we got called from InitContext for // example. We still need to reset context_ now so that a new context gets // created when the plugin recreates its own. MessageLoop::current()->PostTask( FROM_HERE, NewRunnableFunction(DestroyContext, context_, program_, buffer_)); context_ = NULL; program_ = 0; buffer_ = 0; } <commit_msg>Fix downstream bustage due to WebKit r8495 by implementing methods on RenderWidgetFullscreenPepper.<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 "content/renderer/render_widget_fullscreen_pepper.h" #include "base/message_loop.h" #include "content/common/view_messages.h" #include "content/renderer/renderer_gl_context.h" #include "content/renderer/gpu_channel_host.h" #include "content/renderer/pepper_platform_context_3d_impl.h" #include "content/renderer/render_thread.h" #include "gpu/command_buffer/client/gles2_implementation.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebCursorInfo.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebSize.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebWidget.h" #include "webkit/plugins/ppapi/plugin_delegate.h" #include "webkit/plugins/ppapi/ppapi_plugin_instance.h" using WebKit::WebCanvas; using WebKit::WebCompositionUnderline; using WebKit::WebCursorInfo; using WebKit::WebInputEvent; using WebKit::WebMouseEvent; using WebKit::WebPoint; using WebKit::WebRect; using WebKit::WebSize; using WebKit::WebString; using WebKit::WebTextDirection; using WebKit::WebTextInputType; using WebKit::WebVector; using WebKit::WebWidget; namespace { // WebWidget that simply wraps the pepper plugin. class PepperWidget : public WebWidget { public: PepperWidget(webkit::ppapi::PluginInstance* plugin, RenderWidgetFullscreenPepper* widget) : plugin_(plugin), widget_(widget), cursor_(WebCursorInfo::TypePointer) { } // WebWidget API virtual void close() { delete this; } virtual WebSize size() { return size_; } virtual void resize(const WebSize& size) { size_ = size; WebRect plugin_rect(0, 0, size_.width, size_.height); plugin_->ViewChanged(plugin_rect, plugin_rect); widget_->Invalidate(); } virtual void animate() { } virtual void layout() { } virtual void paint(WebCanvas* canvas, const WebRect& rect) { WebRect plugin_rect(0, 0, size_.width, size_.height); plugin_->Paint(canvas, plugin_rect, rect); } virtual void composite(bool finish) { RendererGLContext* context = widget_->context(); DCHECK(context); gpu::gles2::GLES2Implementation* gl = context->GetImplementation(); unsigned int texture = plugin_->GetBackingTextureId(); gl->BindTexture(GL_TEXTURE_2D, texture); gl->DrawArrays(GL_TRIANGLES, 0, 3); context->SwapBuffers(); } virtual void themeChanged() { NOTIMPLEMENTED(); } virtual bool handleInputEvent(const WebInputEvent& event) { bool result = plugin_->HandleInputEvent(event, &cursor_); // For normal web pages, WebViewImpl does input event translations and // generates context menu events. Since we don't have a WebView, we need to // do the necessary translation ourselves. if (WebInputEvent::isMouseEventType(event.type)) { const WebMouseEvent& mouse_event = reinterpret_cast<const WebMouseEvent&>(event); bool send_context_menu_event = false; // On Mac/Linux, we handle it on mouse down. // On Windows, we handle it on mouse up. #if defined(OS_WIN) send_context_menu_event = mouse_event.type == WebInputEvent::MouseUp && mouse_event.button == WebMouseEvent::ButtonRight; #elif defined(OS_MACOSX) send_context_menu_event = mouse_event.type == WebInputEvent::MouseDown && (mouse_event.button == WebMouseEvent::ButtonRight || (mouse_event.button == WebMouseEvent::ButtonLeft && mouse_event.modifiers & WebMouseEvent::ControlKey)); #else send_context_menu_event = mouse_event.type == WebInputEvent::MouseDown && mouse_event.button == WebMouseEvent::ButtonRight; #endif if (send_context_menu_event) { WebMouseEvent context_menu_event(mouse_event); context_menu_event.type = WebInputEvent::ContextMenu; plugin_->HandleInputEvent(context_menu_event, &cursor_); } } return result; } virtual void mouseCaptureLost() { NOTIMPLEMENTED(); } virtual void setFocus(bool focus) { NOTIMPLEMENTED(); } // TODO(piman): figure out IME and implement these if necessary. virtual bool setComposition( const WebString& text, const WebVector<WebCompositionUnderline>& underlines, int selectionStart, int selectionEnd) { return false; } virtual bool confirmComposition() { return false; } virtual bool compositionRange(size_t* location, size_t* length) { return false; } virtual bool confirmComposition(const WebString& text) { return false; } virtual WebTextInputType textInputType() { return WebKit::WebTextInputTypeNone; } virtual WebRect caretOrSelectionBounds() { return WebRect(); } virtual bool selectionRange(WebPoint& start, WebPoint& end) const { return false; } virtual bool selectionRange(size_t *location, size_t *length) { return false; } virtual bool caretOrSelectionRange(size_t* location, size_t* length) { return false; } virtual void setTextDirection(WebTextDirection) { } virtual bool isAcceleratedCompositingActive() const { return widget_->context() && (plugin_->GetBackingTextureId() != 0); } private: scoped_refptr<webkit::ppapi::PluginInstance> plugin_; RenderWidgetFullscreenPepper* widget_; WebSize size_; WebCursorInfo cursor_; DISALLOW_COPY_AND_ASSIGN(PepperWidget); }; void DestroyContext(RendererGLContext* context, GLuint program, GLuint buffer) { DCHECK(context); gpu::gles2::GLES2Implementation* gl = context->GetImplementation(); if (program) gl->DeleteProgram(program); if (buffer) gl->DeleteBuffers(1, &buffer); delete context; } } // anonymous namespace // static RenderWidgetFullscreenPepper* RenderWidgetFullscreenPepper::Create( int32 opener_id, RenderThreadBase* render_thread, webkit::ppapi::PluginInstance* plugin, const GURL& active_url) { DCHECK_NE(MSG_ROUTING_NONE, opener_id); scoped_refptr<RenderWidgetFullscreenPepper> widget( new RenderWidgetFullscreenPepper(render_thread, plugin, active_url)); widget->Init(opener_id); return widget.release(); } RenderWidgetFullscreenPepper::RenderWidgetFullscreenPepper( RenderThreadBase* render_thread, webkit::ppapi::PluginInstance* plugin, const GURL& active_url) : RenderWidgetFullscreen(render_thread), active_url_(active_url), plugin_(plugin), context_(NULL), buffer_(0), program_(0) { } RenderWidgetFullscreenPepper::~RenderWidgetFullscreenPepper() { if (context_) DestroyContext(context_, program_, buffer_); } void RenderWidgetFullscreenPepper::Invalidate() { InvalidateRect(gfx::Rect(size_.width(), size_.height())); } void RenderWidgetFullscreenPepper::InvalidateRect(const WebKit::WebRect& rect) { if (CheckCompositing()) { scheduleComposite(); } else { didInvalidateRect(rect); } } void RenderWidgetFullscreenPepper::ScrollRect( int dx, int dy, const WebKit::WebRect& rect) { if (CheckCompositing()) { scheduleComposite(); } else { didScrollRect(dx, dy, rect); } } void RenderWidgetFullscreenPepper::Destroy() { // This function is called by the plugin instance as it's going away, so reset // plugin_ to NULL to avoid calling into a dangling pointer e.g. on Close(). plugin_ = NULL; Send(new ViewHostMsg_Close(routing_id_)); } webkit::ppapi::PluginDelegate::PlatformContext3D* RenderWidgetFullscreenPepper::CreateContext3D() { if (!context_) { CreateContext(); } if (!context_) return NULL; return new PlatformContext3DImpl(context_); } void RenderWidgetFullscreenPepper::DidInitiatePaint() { if (plugin_) plugin_->ViewInitiatedPaint(); } void RenderWidgetFullscreenPepper::DidFlushPaint() { if (plugin_) plugin_->ViewFlushedPaint(); } void RenderWidgetFullscreenPepper::Close() { // If the fullscreen window is closed (e.g. user pressed escape), reset to // normal mode. if (plugin_) plugin_->SetFullscreen(false, false); } webkit::ppapi::PluginInstance* RenderWidgetFullscreenPepper::GetBitmapForOptimizedPluginPaint( const gfx::Rect& paint_bounds, TransportDIB** dib, gfx::Rect* location, gfx::Rect* clip) { if (plugin_ && plugin_->GetBitmapForOptimizedPluginPaint(paint_bounds, dib, location, clip)) return plugin_; return NULL; } void RenderWidgetFullscreenPepper::OnResize(const gfx::Size& size, const gfx::Rect& resizer_rect) { if (context_) { gpu::gles2::GLES2Implementation* gl = context_->GetImplementation(); #if defined(OS_MACOSX) context_->ResizeOnscreen(size); #else gl->ResizeCHROMIUM(size.width(), size.height()); #endif gl->Viewport(0, 0, size.width(), size.height()); } RenderWidget::OnResize(size, resizer_rect); } WebWidget* RenderWidgetFullscreenPepper::CreateWebWidget() { return new PepperWidget(plugin_, this); } void RenderWidgetFullscreenPepper::CreateContext() { DCHECK(!context_); RenderThread* render_thread = RenderThread::current(); DCHECK(render_thread); GpuChannelHost* host = render_thread->EstablishGpuChannelSync( content::CAUSE_FOR_GPU_LAUNCH_RENDERWIDGETFULLSCREENPEPPER_CREATECONTEXT); if (!host) return; const int32 attribs[] = { RendererGLContext::ALPHA_SIZE, 8, RendererGLContext::DEPTH_SIZE, 0, RendererGLContext::STENCIL_SIZE, 0, RendererGLContext::SAMPLES, 0, RendererGLContext::SAMPLE_BUFFERS, 0, RendererGLContext::NONE, }; context_ = RendererGLContext::CreateViewContext( host, compositing_surface(), routing_id(), "GL_OES_packed_depth_stencil GL_OES_depth24", attribs, active_url_); if (!context_) return; if (!InitContext()) { DestroyContext(context_, program_, buffer_); context_ = NULL; return; } context_->SetSwapBuffersCallback( NewCallback(this, &RenderWidgetFullscreenPepper::DidFlushPaint)); context_->SetContextLostCallback( NewCallback(this, &RenderWidgetFullscreenPepper::OnLostContext)); } namespace { const char kVertexShader[] = "attribute vec2 in_tex_coord;\n" "varying vec2 tex_coord;\n" "void main() {\n" " gl_Position = vec4(in_tex_coord.x * 2. - 1.,\n" " in_tex_coord.y * 2. - 1.,\n" " 0.,\n" " 1.);\n" " tex_coord = vec2(in_tex_coord.x, in_tex_coord.y);\n" "}\n"; const char kFragmentShader[] = "precision mediump float;\n" "varying vec2 tex_coord;\n" "uniform sampler2D in_texture;\n" "void main() {\n" " gl_FragColor = texture2D(in_texture, tex_coord);\n" "}\n"; GLuint CreateShaderFromSource(gpu::gles2::GLES2Implementation* gl, GLenum type, const char* source) { GLuint shader = gl->CreateShader(type); gl->ShaderSource(shader, 1, &source, NULL); gl->CompileShader(shader); int status; gl->GetShaderiv(shader, GL_COMPILE_STATUS, &status); if (!status) { int size = 0; gl->GetShaderiv(shader, GL_INFO_LOG_LENGTH, &size); scoped_array<char> log(new char[size]); gl->GetShaderInfoLog(shader, size, NULL, log.get()); DLOG(ERROR) << "Compilation failed: " << log.get(); gl->DeleteShader(shader); shader = 0; } return shader; } const float kTexCoords[] = { 0.f, 0.f, 0.f, 2.f, 2.f, 0.f, }; } // anonymous namespace bool RenderWidgetFullscreenPepper::InitContext() { gpu::gles2::GLES2Implementation* gl = context_->GetImplementation(); program_ = gl->CreateProgram(); GLuint vertex_shader = CreateShaderFromSource(gl, GL_VERTEX_SHADER, kVertexShader); if (!vertex_shader) return false; gl->AttachShader(program_, vertex_shader); gl->DeleteShader(vertex_shader); GLuint fragment_shader = CreateShaderFromSource(gl, GL_FRAGMENT_SHADER, kFragmentShader); if (!fragment_shader) return false; gl->AttachShader(program_, fragment_shader); gl->DeleteShader(fragment_shader); gl->BindAttribLocation(program_, 0, "in_tex_coord"); gl->LinkProgram(program_); int status; gl->GetProgramiv(program_, GL_LINK_STATUS, &status); if (!status) { int size = 0; gl->GetProgramiv(program_, GL_INFO_LOG_LENGTH, &size); scoped_array<char> log(new char[size]); gl->GetProgramInfoLog(program_, size, NULL, log.get()); DLOG(ERROR) << "Link failed: " << log.get(); return false; } gl->UseProgram(program_); int texture_location = gl->GetUniformLocation(program_, "in_texture"); gl->Uniform1i(texture_location, 0); gl->GenBuffers(1, &buffer_); gl->BindBuffer(GL_ARRAY_BUFFER, buffer_); gl->BufferData(GL_ARRAY_BUFFER, sizeof(kTexCoords), kTexCoords, GL_STATIC_DRAW); gl->VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL); gl->EnableVertexAttribArray(0); return true; } bool RenderWidgetFullscreenPepper::CheckCompositing() { bool compositing = webwidget_->isAcceleratedCompositingActive(); if (compositing != is_accelerated_compositing_active_) { didActivateAcceleratedCompositing(compositing); } return compositing; } void RenderWidgetFullscreenPepper::OnLostContext() { if (!context_) return; // Destroy the context later, in case we got called from InitContext for // example. We still need to reset context_ now so that a new context gets // created when the plugin recreates its own. MessageLoop::current()->PostTask( FROM_HERE, NewRunnableFunction(DestroyContext, context_, program_, buffer_)); context_ = NULL; program_ = 0; buffer_ = 0; } <|endoftext|>
<commit_before>#ifndef BUILDERS_GENERATORS_ICOSPHEREGENERATOR_HPP_DEFINED #define BUILDERS_GENERATORS_ICOSPHEREGENERATOR_HPP_DEFINED #include "builders/generators/AbstractGenerator.hpp" #include "math/Vector3.hpp" #include <algorithm> #include <cstdint> #include <vector> namespace utymap { namespace builders { /// Builds icosphere. /// See http://blog.andreaskahler.com/2009/06/creating-icosphere-mesh-in-code.html class IcoSphereGenerator final : public AbstractGenerator { /// Helper class for calculations struct TriangleIndices { std::size_t V1, V2, V3; TriangleIndices(std::size_t v1, std::size_t v2, std::size_t v3) : V1(v1), V2(v2), V3(v3) { } }; public: IcoSphereGenerator(const utymap::builders::BuilderContext& builderContext, utymap::builders::MeshContext& meshContext): AbstractGenerator(builderContext, meshContext), center_(), size_(), recursionLevel_(0), isSemiSphere_(false) { } /// Sets center of icosphere. IcoSphereGenerator& setCenter(const utymap::math::Vector3& center) { center_ = center; return *this; } /// Sets radius of icosphere. IcoSphereGenerator& setSize(const utymap::math::Vector3& size) { size_ = size; return *this; } /// Sets recursion level. IcoSphereGenerator& setRecursionLevel(int recursionLevel) { recursionLevel_ = recursionLevel; return *this; } /// If true than only half will be generated. IcoSphereGenerator& isSemiSphere(bool value) { isSemiSphere_ = value; return *this; } void generate() override { // create 12 vertices of a icosahedron double t = (1 + std::sqrt(5)) / 2; vertexList_.push_back(utymap::math::Vector3(-1, t, 0).normalized()); vertexList_.push_back(utymap::math::Vector3(1, t, 0).normalized()); vertexList_.push_back(utymap::math::Vector3(-1, -t, 0).normalized()); vertexList_.push_back(utymap::math::Vector3(1, -t, 0).normalized()); vertexList_.push_back(utymap::math::Vector3(0, -1, t).normalized()); vertexList_.push_back(utymap::math::Vector3(0, 1, t).normalized()); vertexList_.push_back(utymap::math::Vector3(0., -1, -t).normalized()); vertexList_.push_back(utymap::math::Vector3(0, 1, -t).normalized()); vertexList_.push_back(utymap::math::Vector3(t, 0, -1).normalized()); vertexList_.push_back(utymap::math::Vector3(t, 0, 1).normalized()); vertexList_.push_back(utymap::math::Vector3(-t, 0, -1).normalized()); vertexList_.push_back(utymap::math::Vector3(-t, 0, 1).normalized()); // create 20 triangles of the icosahedron std::vector<TriangleIndices> faces; // 5 faces around point 0 faces.push_back(TriangleIndices(0, 11, 5)); faces.push_back(TriangleIndices(0, 5, 1)); faces.push_back(TriangleIndices(0, 1, 7)); faces.push_back(TriangleIndices(0, 7, 10)); faces.push_back(TriangleIndices(0, 10, 11)); // 5 adjacent faces faces.push_back(TriangleIndices(1, 5, 9)); faces.push_back(TriangleIndices(5, 11, 4)); if (!isSemiSphere_) faces.push_back(TriangleIndices(11, 10, 2)); faces.push_back(TriangleIndices(10, 7, 6)); faces.push_back(TriangleIndices(7, 1, 8)); // 5 faces around point 3 if (!isSemiSphere_) { faces.push_back(TriangleIndices(3, 9, 4)); faces.push_back(TriangleIndices(3, 4, 2)); faces.push_back(TriangleIndices(3, 2, 6)); faces.push_back(TriangleIndices(3, 6, 8)); faces.push_back(TriangleIndices(3, 8, 9)); } // 5 adjacent faces faces.push_back(TriangleIndices(4, 9, 5)); if (!isSemiSphere_) { faces.push_back(TriangleIndices(2, 4, 11)); faces.push_back(TriangleIndices(6, 2, 10)); } faces.push_back(TriangleIndices(8, 6, 7)); faces.push_back(TriangleIndices(9, 8, 1)); // refine triangles for (int i = 0; i < recursionLevel_; i++) { std::vector<TriangleIndices> faces2; for (const auto& tri : faces) { // replace triangle by 4 triangles auto a = getMiddlePoint(tri.V1, tri.V2); auto b = getMiddlePoint(tri.V2, tri.V3); auto c = getMiddlePoint(tri.V3, tri.V1); faces2.push_back(TriangleIndices(tri.V1, a, c)); faces2.push_back(TriangleIndices(tri.V2, b, a)); faces2.push_back(TriangleIndices(tri.V3, c, b)); faces2.push_back(TriangleIndices(a, b, c)); } faces = faces2; } generateMesh(faces); // clear state to allow reuse middlePointIndexCache_.clear(); vertexList_.clear(); } private: /// Returns index of point in the middle of p1 and p2. std::size_t getMiddlePoint(std::size_t p1, std::size_t p2) { // first check if we have it already bool firstIsSmaller = p1 < p2; std::uint64_t smallerIndex = firstIsSmaller ? p1 : p2; std::uint64_t greaterIndex = firstIsSmaller ? p2 : p1; std::uint64_t key = (smallerIndex << 32) + greaterIndex; auto ret = middlePointIndexCache_.find(key); if (ret != middlePointIndexCache_.end()) return ret->second; // not in cache, calculate it utymap::math::Vector3 point1 = vertexList_[p1]; utymap::math::Vector3 point2 = vertexList_[p2]; utymap::math::Vector3 middle ( (point1.x + point2.x) / 2, (point1.y + point2.y) / 2, (point1.z + point2.z) / 2 ); // add vertex makes sure point is on unit sphere std::size_t size = vertexList_.size(); vertexList_.push_back(middle.normalized()); // store it, return index middlePointIndexCache_.insert(std::make_pair(key, size)); return size; } void generateMesh(const std::vector<TriangleIndices>& faces) { for (auto i = 0; i < faces.size(); ++i) { auto face = faces[i]; addTriangle( scale(vertexList_[face.V1]) + center_, scale(vertexList_[face.V2]) + center_, scale(vertexList_[face.V3]) + center_); } } utymap::math::Vector3 scale(const utymap::math::Vector3& v) const { return translate(utymap::math::Vector3(v.x * size_.x, v.y * size_.y, v.z * size_.z)); } utymap::math::Vector3 center_; utymap::math::Vector3 size_; int recursionLevel_; bool isSemiSphere_; std::unordered_map<std::uint64_t, std::size_t> middlePointIndexCache_; std::vector<utymap::math::Vector3> vertexList_; }; }} #endif // BUILDERS_GENERATORS_ICOSPHEREGENERATOR_HPP_DEFINED <commit_msg>core: fix scale issue in icosphere generator<commit_after>#ifndef BUILDERS_GENERATORS_ICOSPHEREGENERATOR_HPP_DEFINED #define BUILDERS_GENERATORS_ICOSPHEREGENERATOR_HPP_DEFINED #include "builders/generators/AbstractGenerator.hpp" #include "math/Vector3.hpp" #include <algorithm> #include <cstdint> #include <vector> namespace utymap { namespace builders { /// Builds icosphere. /// See http://blog.andreaskahler.com/2009/06/creating-icosphere-mesh-in-code.html class IcoSphereGenerator final : public AbstractGenerator { /// Helper class for calculations struct TriangleIndices { std::size_t V1, V2, V3; TriangleIndices(std::size_t v1, std::size_t v2, std::size_t v3) : V1(v1), V2(v2), V3(v3) { } }; public: IcoSphereGenerator(const utymap::builders::BuilderContext& builderContext, utymap::builders::MeshContext& meshContext): AbstractGenerator(builderContext, meshContext), center_(), size_(), recursionLevel_(0), isSemiSphere_(false) { } /// Sets center of icosphere. IcoSphereGenerator& setCenter(const utymap::math::Vector3& center) { center_ = center; return *this; } /// Sets radius of icosphere. IcoSphereGenerator& setSize(const utymap::math::Vector3& size) { size_ = size; return *this; } /// Sets recursion level. IcoSphereGenerator& setRecursionLevel(int recursionLevel) { recursionLevel_ = recursionLevel; return *this; } /// If true than only half will be generated. IcoSphereGenerator& isSemiSphere(bool value) { isSemiSphere_ = value; return *this; } void generate() override { // create 12 vertices of a icosahedron double t = (1 + std::sqrt(5)) / 2; vertexList_.push_back(utymap::math::Vector3(-1, t, 0).normalized()); vertexList_.push_back(utymap::math::Vector3(1, t, 0).normalized()); vertexList_.push_back(utymap::math::Vector3(-1, -t, 0).normalized()); vertexList_.push_back(utymap::math::Vector3(1, -t, 0).normalized()); vertexList_.push_back(utymap::math::Vector3(0, -1, t).normalized()); vertexList_.push_back(utymap::math::Vector3(0, 1, t).normalized()); vertexList_.push_back(utymap::math::Vector3(0., -1, -t).normalized()); vertexList_.push_back(utymap::math::Vector3(0, 1, -t).normalized()); vertexList_.push_back(utymap::math::Vector3(t, 0, -1).normalized()); vertexList_.push_back(utymap::math::Vector3(t, 0, 1).normalized()); vertexList_.push_back(utymap::math::Vector3(-t, 0, -1).normalized()); vertexList_.push_back(utymap::math::Vector3(-t, 0, 1).normalized()); // create 20 triangles of the icosahedron std::vector<TriangleIndices> faces; // 5 faces around point 0 faces.push_back(TriangleIndices(0, 11, 5)); faces.push_back(TriangleIndices(0, 5, 1)); faces.push_back(TriangleIndices(0, 1, 7)); faces.push_back(TriangleIndices(0, 7, 10)); faces.push_back(TriangleIndices(0, 10, 11)); // 5 adjacent faces faces.push_back(TriangleIndices(1, 5, 9)); faces.push_back(TriangleIndices(5, 11, 4)); if (!isSemiSphere_) faces.push_back(TriangleIndices(11, 10, 2)); faces.push_back(TriangleIndices(10, 7, 6)); faces.push_back(TriangleIndices(7, 1, 8)); // 5 faces around point 3 if (!isSemiSphere_) { faces.push_back(TriangleIndices(3, 9, 4)); faces.push_back(TriangleIndices(3, 4, 2)); faces.push_back(TriangleIndices(3, 2, 6)); faces.push_back(TriangleIndices(3, 6, 8)); faces.push_back(TriangleIndices(3, 8, 9)); } // 5 adjacent faces faces.push_back(TriangleIndices(4, 9, 5)); if (!isSemiSphere_) { faces.push_back(TriangleIndices(2, 4, 11)); faces.push_back(TriangleIndices(6, 2, 10)); } faces.push_back(TriangleIndices(8, 6, 7)); faces.push_back(TriangleIndices(9, 8, 1)); // refine triangles for (int i = 0; i < recursionLevel_; i++) { std::vector<TriangleIndices> faces2; for (const auto& tri : faces) { // replace triangle by 4 triangles auto a = getMiddlePoint(tri.V1, tri.V2); auto b = getMiddlePoint(tri.V2, tri.V3); auto c = getMiddlePoint(tri.V3, tri.V1); faces2.push_back(TriangleIndices(tri.V1, a, c)); faces2.push_back(TriangleIndices(tri.V2, b, a)); faces2.push_back(TriangleIndices(tri.V3, c, b)); faces2.push_back(TriangleIndices(a, b, c)); } faces = faces2; } generateMesh(faces); // clear state to allow reuse middlePointIndexCache_.clear(); vertexList_.clear(); } private: /// Returns index of point in the middle of p1 and p2. std::size_t getMiddlePoint(std::size_t p1, std::size_t p2) { // first check if we have it already bool firstIsSmaller = p1 < p2; std::uint64_t smallerIndex = firstIsSmaller ? p1 : p2; std::uint64_t greaterIndex = firstIsSmaller ? p2 : p1; std::uint64_t key = (smallerIndex << 32) + greaterIndex; auto ret = middlePointIndexCache_.find(key); if (ret != middlePointIndexCache_.end()) return ret->second; // not in cache, calculate it utymap::math::Vector3 point1 = vertexList_[p1]; utymap::math::Vector3 point2 = vertexList_[p2]; utymap::math::Vector3 middle ( (point1.x + point2.x) / 2, (point1.y + point2.y) / 2, (point1.z + point2.z) / 2 ); // add vertex makes sure point is on unit sphere std::size_t size = vertexList_.size(); vertexList_.push_back(middle.normalized()); // store it, return index middlePointIndexCache_.insert(std::make_pair(key, size)); return size; } void generateMesh(const std::vector<TriangleIndices>& faces) { for (auto i = 0; i < faces.size(); ++i) { auto face = faces[i]; addTriangle( translate(scale(vertexList_[face.V1]) + center_), translate(scale(vertexList_[face.V2]) + center_), translate(scale(vertexList_[face.V3]) + center_)); } } utymap::math::Vector3 scale(const utymap::math::Vector3& v) const { return utymap::math::Vector3(v.x * size_.x, v.y * size_.y, v.z * size_.z); } utymap::math::Vector3 center_; utymap::math::Vector3 size_; int recursionLevel_; bool isSemiSphere_; std::unordered_map<std::uint64_t, std::size_t> middlePointIndexCache_; std::vector<utymap::math::Vector3> vertexList_; }; }} #endif // BUILDERS_GENERATORS_ICOSPHEREGENERATOR_HPP_DEFINED <|endoftext|>
<commit_before>#include<iostream> #include<string> // g++ --std=c++11 -Wall -pedantic hello.cpp using namespace std; int main() { string msg = "Hello, world!"; cout << msg << endl; return 0; } <commit_msg>Added bool example<commit_after>#include<iostream> #include<string> // g++ --std=c++11 -Wall -pedantic hello.cpp using namespace std; int main() { string msg = "Hello, world!"; bool sayIt = true; if (sayIt) { cout << msg << endl; } return 0; } <|endoftext|>
<commit_before>#ifdef QUICKTEST_GUI #include <FL/Fl.H> #include <FL/Fl_Double_Window.H> #include <FL/Fl_Button.H> #include <FL/Fl_Multiline_Output.H> #include <FL/Fl_Box.H> #include "FL/fl_draw.H" #endif #include <vector> #include <string> #include <fstream> #include "LimeSDRTest.h" #include <iostream> #include <getopt.h> #ifdef NDEBUG #ifdef _MSC_VER #pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") #endif #endif #ifdef QUICKTEST_GUI static Fl_Button** buttons; static Fl_Window* popup = nullptr; static Fl_Multiline_Output* out; static Fl_Output* detect; static std::string logfile; static int started = false; Fl_Button* start; const Fl_Color CL_DARK = fl_rgb_color(0x18, 0x8A, 0x2E); class Lms_Double_window : public Fl_Double_Window { private: int error_msg; public: Lms_Double_window(int W, int H, const char* L = 0) : Fl_Double_Window(W, H, L) { error_msg = 0; }; void SetErrorMsg(int msg) { error_msg = msg; } void draw() { Fl_Double_Window::draw(); if (error_msg != 0) { fl_rectf(w() / 4, h() / 4, w() / 2, h() / 4,FL_WHITE); fl_rect(w() / 4, h() / 4, w() / 2, h() / 4, FL_BLACK); fl_color(FL_RED); fl_font(FL_HELVETICA, 20); if (error_msg == -1) { fl_draw("No Board Detected", 320, h()/4+50); fl_font(FL_HELVETICA, 20); } else if (error_msg == -2) { fl_font(FL_HELVETICA, 20); fl_draw("Multiple Boards Detected", 295, h() / 4 + 50); } } } }; Lms_Double_window* win; class LmsPopupResult : public Fl_Window { public: LmsPopupResult(int X, int Y, int W, int H, bool passed, const char* L=0) :Fl_Window(W, H, L) { position(X, Y); color(FL_WHITE); Fl_Button* b = new Fl_Button(W / 2 - 40, H - 50, 80, 30, "OK"); b->callback(Button_CB, this); b->shortcut(FL_Enter); Fl_Multiline_Output* out = new Fl_Multiline_Output(64, 15, W - 128, 50); out->box(FL_NO_BOX); out->textsize(24); out->textcolor(passed ? CL_DARK : FL_RED); out->value(passed ? "Board Tests PASSED" : "Board Tests FAILED"); end(); set_modal(); show(); } ~LmsPopupResult() {}; private: static void Button_CB(Fl_Widget* obj, void* v) { ((Fl_Window*)v)->hide(); } }; class LmsPopupError : public Fl_Window { Fl_Output* out; public: LmsPopupError(int W, int H, const char* L = 0) :Fl_Window(W, H, L) { color(FL_WHITE); out = new Fl_Output(64, 15, W - 128, 40); out->box(FL_NO_BOX); out->textsize(32); out->textcolor(FL_RED); end(); set_modal(); }; void Update(int X, int Y, const char* msg) { position(X, Y); out->value(msg); } ~LmsPopupError() {}; }; static LmsPopupError* error_popup = nullptr; void ShowMessage(void* v) { if (popup != nullptr) { popup->hide(); delete popup; popup = nullptr; } bool passed = *((bool*)v); popup = new LmsPopupResult(win->x() + win->w() / 4, win->y() + win->h() / 4, win->w() / 2, 120, passed, ""); while (popup && popup->shown()) Fl::wait(); delete (bool*)v; delete popup; popup = nullptr; } void Timer_CB(void *data) { static int counter = 30; Fl::repeat_timeout(1.0f / 25.0f, Timer_CB, nullptr); if (counter++ == 30) { counter = 0; Fl::lock(); std::string str; win->SetErrorMsg(0); int ret; str = ""; if ((ret = LimeSDRTest::CheckDevice(str)) == 0) { detect->textcolor(CL_DARK); if (!started) start->activate(); win->SetErrorMsg(0); } else { detect->textcolor(FL_RED); if (!started) start->deactivate(); if (popup != nullptr) popup->hide(); win->SetErrorMsg(ret); } if (str != "") detect->value(str.c_str()); win->redraw(); win->damage(FL_DAMAGE_ALL, 150, 460, 320, 30); Fl::unlock(); } } static void Window_CB(Fl_Widget*, void*) { if (Fl::event() == FL_SHORTCUT && Fl::event_key() == FL_Escape) return; // ignore Escape exit(0); } static void AddLine(const char * str) { std::string val; val = out->value(); val += str; val += "\n"; out->value(val.c_str()); out->position(val.length()); if (logfile != "") { std::ofstream file(logfile, std::ios_base::out | std::ios_base::app); if (file.is_open()) { file << str << std::endl; file.close(); } } } static void DrawButtons(int X, int Y) { buttons = new Fl_Button*[testNames.size()]; Fl_Group* g = new Fl_Group(X-10,Y-8,240,testNames.size()*55+10,"Board Tests"); //g->align(FL_ALIGN_TOP_LEFT); g->box(FL_ENGRAVED_FRAME); for (unsigned i = 0; i < testNames.size(); i++) { auto button = new Fl_Button(X, Y+i*55, 220, 40,testNames[i].c_str()); button->box(FL_ROUND_UP_BOX); button->deactivate(); buttons[i] = button; } g->end(); } static int CB_Function(int id, int event, const char* msg) { Fl::lock(); if (event == LMS_TEST_INFO) { if (id != -1) { buttons[id]->activate(); buttons[id]->color(FL_YELLOW); } } else if (event == LMS_TEST_FAIL) { if (id != -1) { buttons[id]->activate(); buttons[id]->color(FL_RED); } else { bool* passed = new bool; *passed = false; started = false; Fl::awake(ShowMessage, passed); } } else if (event == LMS_TEST_SUCCESS) { if (id != -1) { buttons[id]->activate(); buttons[id]->color(FL_GREEN); } else { bool* passed = new bool; *passed = true; started = false; Fl::awake(ShowMessage, passed); } } else if (event == LMS_TEST_LOGFILE) { logfile = "LimeSDR-Mini_"; logfile += msg; logfile +=".log"; std::ofstream file(logfile, std::ios_base::out | std::ios_base::app); if (file.is_open()) { file << out->value(); file.close(); } std::string str = " Serial Number: "; str += msg; AddLine(str.c_str()); } if (msg && event != LMS_TEST_LOGFILE) AddLine(msg); if (id == -1) start->activate(); win->redraw(); Fl::unlock(); return 0; } static void Start_CB(Fl_Widget*, void*) { out->value(""); logfile = ""; for (unsigned i = 0; i < testNames.size(); i++) { buttons[i]->color(FL_BACKGROUND_COLOR); buttons[i]->deactivate(); } started = true; if (LimeSDRTest::RunTests(CB_Function) == 0) start->deactivate(); } #endif static int CB_FunctionCLI(int id, int event, const char* msg) { if (event == LMS_TEST_LOGFILE) { std::string str = " Serial Number: "; str += msg; std::cout << str << std::endl; } else std::cout << msg << std::endl; return 0; } int main(int argc, char** argv) { #ifdef QUICKTEST_GUI #ifdef __unix int gui = 0; #else int gui = 1; #endif static struct option long_options[] = { {"gui", no_argument, &gui, 1}, {"no-gui", no_argument, &gui, 0}, {0, 0, 0, 0} }; int option; int option_index = 0; while ((option = getopt_long(argc, argv, "", long_options, &option_index)) != -1) { if (option != 0) { std::cout << " --gui\t\tenables GUI\n --no-gui\tdisables GUI\n" << std::endl; return -1; } } if (gui) { Fl::scheme("gleam"); win = new Lms_Double_window(860, 135+testNames.size()*55, "LimeSDR TestApp"); out = new Fl_Multiline_Output(260, 22, win->w()-270, win->h()-50, "Message Log"); out->align(FL_ALIGN_TOP_LEFT); out->textsize(11); start = new Fl_Button(20, win->h()-82, 220, 40, "Start Test"); start->callback(Start_CB); start->shortcut(FL_Enter); DrawButtons(20, 30); detect = new Fl_Output(10, win->h()-28, 480, 30); detect->box(FL_NO_BOX); detect->textsize(16); win->show(); win->end(); error_popup = new LmsPopupError(win->w()/2, win->h()/4,""); win->callback(Window_CB); Fl::add_timeout(0.1f, Timer_CB, nullptr); Fl::lock(); Fl::run(); delete win; return 0; } #endif return LimeSDRTest::RunTests(CB_FunctionCLI, false); //returns bit field of failed tests } <commit_msg>Dont hide console when QUICKTEST_GUI is not defined (resolves #270)<commit_after>#ifdef QUICKTEST_GUI #include <FL/Fl.H> #include <FL/Fl_Double_Window.H> #include <FL/Fl_Button.H> #include <FL/Fl_Multiline_Output.H> #include <FL/Fl_Box.H> #include "FL/fl_draw.H" #endif #include <vector> #include <string> #include <fstream> #include "LimeSDRTest.h" #include <iostream> #include <getopt.h> #ifdef QUICKTEST_GUI #ifdef NDEBUG #ifdef _MSC_VER #pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") #endif #endif static Fl_Button** buttons; static Fl_Window* popup = nullptr; static Fl_Multiline_Output* out; static Fl_Output* detect; static std::string logfile; static int started = false; Fl_Button* start; const Fl_Color CL_DARK = fl_rgb_color(0x18, 0x8A, 0x2E); class Lms_Double_window : public Fl_Double_Window { private: int error_msg; public: Lms_Double_window(int W, int H, const char* L = 0) : Fl_Double_Window(W, H, L) { error_msg = 0; }; void SetErrorMsg(int msg) { error_msg = msg; } void draw() { Fl_Double_Window::draw(); if (error_msg != 0) { fl_rectf(w() / 4, h() / 4, w() / 2, h() / 4,FL_WHITE); fl_rect(w() / 4, h() / 4, w() / 2, h() / 4, FL_BLACK); fl_color(FL_RED); fl_font(FL_HELVETICA, 20); if (error_msg == -1) { fl_draw("No Board Detected", 320, h()/4+50); fl_font(FL_HELVETICA, 20); } else if (error_msg == -2) { fl_font(FL_HELVETICA, 20); fl_draw("Multiple Boards Detected", 295, h() / 4 + 50); } } } }; Lms_Double_window* win; class LmsPopupResult : public Fl_Window { public: LmsPopupResult(int X, int Y, int W, int H, bool passed, const char* L=0) :Fl_Window(W, H, L) { position(X, Y); color(FL_WHITE); Fl_Button* b = new Fl_Button(W / 2 - 40, H - 50, 80, 30, "OK"); b->callback(Button_CB, this); b->shortcut(FL_Enter); Fl_Multiline_Output* out = new Fl_Multiline_Output(64, 15, W - 128, 50); out->box(FL_NO_BOX); out->textsize(24); out->textcolor(passed ? CL_DARK : FL_RED); out->value(passed ? "Board Tests PASSED" : "Board Tests FAILED"); end(); set_modal(); show(); } ~LmsPopupResult() {}; private: static void Button_CB(Fl_Widget* obj, void* v) { ((Fl_Window*)v)->hide(); } }; class LmsPopupError : public Fl_Window { Fl_Output* out; public: LmsPopupError(int W, int H, const char* L = 0) :Fl_Window(W, H, L) { color(FL_WHITE); out = new Fl_Output(64, 15, W - 128, 40); out->box(FL_NO_BOX); out->textsize(32); out->textcolor(FL_RED); end(); set_modal(); }; void Update(int X, int Y, const char* msg) { position(X, Y); out->value(msg); } ~LmsPopupError() {}; }; static LmsPopupError* error_popup = nullptr; void ShowMessage(void* v) { if (popup != nullptr) { popup->hide(); delete popup; popup = nullptr; } bool passed = *((bool*)v); popup = new LmsPopupResult(win->x() + win->w() / 4, win->y() + win->h() / 4, win->w() / 2, 120, passed, ""); while (popup && popup->shown()) Fl::wait(); delete (bool*)v; delete popup; popup = nullptr; } void Timer_CB(void *data) { static int counter = 30; Fl::repeat_timeout(1.0f / 25.0f, Timer_CB, nullptr); if (counter++ == 30) { counter = 0; Fl::lock(); std::string str; win->SetErrorMsg(0); int ret; str = ""; if ((ret = LimeSDRTest::CheckDevice(str)) == 0) { detect->textcolor(CL_DARK); if (!started) start->activate(); win->SetErrorMsg(0); } else { detect->textcolor(FL_RED); if (!started) start->deactivate(); if (popup != nullptr) popup->hide(); win->SetErrorMsg(ret); } if (str != "") detect->value(str.c_str()); win->redraw(); win->damage(FL_DAMAGE_ALL, 150, 460, 320, 30); Fl::unlock(); } } static void Window_CB(Fl_Widget*, void*) { if (Fl::event() == FL_SHORTCUT && Fl::event_key() == FL_Escape) return; // ignore Escape exit(0); } static void AddLine(const char * str) { std::string val; val = out->value(); val += str; val += "\n"; out->value(val.c_str()); out->position(val.length()); if (logfile != "") { std::ofstream file(logfile, std::ios_base::out | std::ios_base::app); if (file.is_open()) { file << str << std::endl; file.close(); } } } static void DrawButtons(int X, int Y) { buttons = new Fl_Button*[testNames.size()]; Fl_Group* g = new Fl_Group(X-10,Y-8,240,testNames.size()*55+10,"Board Tests"); //g->align(FL_ALIGN_TOP_LEFT); g->box(FL_ENGRAVED_FRAME); for (unsigned i = 0; i < testNames.size(); i++) { auto button = new Fl_Button(X, Y+i*55, 220, 40,testNames[i].c_str()); button->box(FL_ROUND_UP_BOX); button->deactivate(); buttons[i] = button; } g->end(); } static int CB_Function(int id, int event, const char* msg) { Fl::lock(); if (event == LMS_TEST_INFO) { if (id != -1) { buttons[id]->activate(); buttons[id]->color(FL_YELLOW); } } else if (event == LMS_TEST_FAIL) { if (id != -1) { buttons[id]->activate(); buttons[id]->color(FL_RED); } else { bool* passed = new bool; *passed = false; started = false; Fl::awake(ShowMessage, passed); } } else if (event == LMS_TEST_SUCCESS) { if (id != -1) { buttons[id]->activate(); buttons[id]->color(FL_GREEN); } else { bool* passed = new bool; *passed = true; started = false; Fl::awake(ShowMessage, passed); } } else if (event == LMS_TEST_LOGFILE) { logfile = "LimeSDR-Mini_"; logfile += msg; logfile +=".log"; std::ofstream file(logfile, std::ios_base::out | std::ios_base::app); if (file.is_open()) { file << out->value(); file.close(); } std::string str = " Serial Number: "; str += msg; AddLine(str.c_str()); } if (msg && event != LMS_TEST_LOGFILE) AddLine(msg); if (id == -1) start->activate(); win->redraw(); Fl::unlock(); return 0; } static void Start_CB(Fl_Widget*, void*) { out->value(""); logfile = ""; for (unsigned i = 0; i < testNames.size(); i++) { buttons[i]->color(FL_BACKGROUND_COLOR); buttons[i]->deactivate(); } started = true; if (LimeSDRTest::RunTests(CB_Function) == 0) start->deactivate(); } #endif static int CB_FunctionCLI(int id, int event, const char* msg) { if (event == LMS_TEST_LOGFILE) { std::string str = " Serial Number: "; str += msg; std::cout << str << std::endl; } else std::cout << msg << std::endl; return 0; } int main(int argc, char** argv) { #ifdef QUICKTEST_GUI #ifdef __unix int gui = 0; #else int gui = 1; #endif static struct option long_options[] = { {"gui", no_argument, &gui, 1}, {"no-gui", no_argument, &gui, 0}, {0, 0, 0, 0} }; int option; int option_index = 0; while ((option = getopt_long(argc, argv, "", long_options, &option_index)) != -1) { if (option != 0) { std::cout << " --gui\t\tenables GUI\n --no-gui\tdisables GUI\n" << std::endl; return -1; } } if (gui) { Fl::scheme("gleam"); win = new Lms_Double_window(860, 135+testNames.size()*55, "LimeSDR TestApp"); out = new Fl_Multiline_Output(260, 22, win->w()-270, win->h()-50, "Message Log"); out->align(FL_ALIGN_TOP_LEFT); out->textsize(11); start = new Fl_Button(20, win->h()-82, 220, 40, "Start Test"); start->callback(Start_CB); start->shortcut(FL_Enter); DrawButtons(20, 30); detect = new Fl_Output(10, win->h()-28, 480, 30); detect->box(FL_NO_BOX); detect->textsize(16); win->show(); win->end(); error_popup = new LmsPopupError(win->w()/2, win->h()/4,""); win->callback(Window_CB); Fl::add_timeout(0.1f, Timer_CB, nullptr); Fl::lock(); Fl::run(); delete win; return 0; } #endif return LimeSDRTest::RunTests(CB_FunctionCLI, false); //returns bit field of failed tests } <|endoftext|>
<commit_before>/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "core-precomp.h" // Precompiled headers #include <mrpt/core/cpu.h> #include <mrpt/core/format.h> #include <array> #if defined(_MSC_VER) #include <intrin.h> // __cpuidex #endif class CPU_analyzer { public: static CPU_analyzer& Instance() { static CPU_analyzer o; return o; } std::array< bool, static_cast<std::size_t>(mrpt::cpu::feature::FEATURE_COUNT)> feat_detected; bool& feat(mrpt::cpu::feature f) noexcept { return feat_detected[static_cast<std::size_t>(f)]; } const bool& feat(mrpt::cpu::feature f) const noexcept { return feat_detected[static_cast<std::size_t>(f)]; } private: // Ctor: runs all the checks and fills in the vector of features: CPU_analyzer() noexcept { // Start with all falses: feat_detected.fill(false); detect_impl(); } #if defined(_MSC_VER) // MSVC version void detect_impl() noexcept { // Based on: https://stackoverflow.com/a/7495023/1631514 #define cpuid(info, x) __cpuidex(info, x, 0) int info[4]; cpuid(info, 0); int nIds = info[0]; cpuid(info, 0x80000000); unsigned nExIds = info[0]; // Detect Features using namespace mrpt::cpu; if (nIds >= 0x00000001) { cpuid(info, 0x00000001); feat(feature::MMX) = !!(info[3] & (1 << 23)); feat(feature::POPCNT) = !!(info[2] & (1 << 23)); feat(feature::SSE) = !!(info[3] & (1 << 25)); feat(feature::SSE2) = !!(info[3] & (1 << 26)); feat(feature::SSE3) = !!(info[2] & (1 << 0)); feat(feature::SSSE3) = !!(info[2] & (1 << 9)); feat(feature::SSE4_1) = !!(info[2] & (1 << 19)); feat(feature::SSE4_2) = !!(info[2] & (1 << 20)); feat(feature::AVX) = !!(info[2] & (1 << 28)); } if (nIds >= 0x00000007) { cpuid(info, 0x00000007); feat(feature::AVX2) = !!(info[1] & (1 << 5)); } // Doubt: is this required? // auto xcrFeatureMask = _xgetbv(_XCR_XFEATURE_ENABLED_MASK); } #else // GCC/CLANG version void detect_impl() noexcept { // __builtin_cpu_supports() checks for both: CPU and OS support using namespace mrpt::cpu; feat(feature::MMX) = !!__builtin_cpu_supports("mmx"); feat(feature::POPCNT) = !!__builtin_cpu_supports("popcnt"); feat(feature::SSE) = !!__builtin_cpu_supports("sse"); feat(feature::SSE2) = !!__builtin_cpu_supports("sse2"); feat(feature::SSE3) = !!__builtin_cpu_supports("sse3"); feat(feature::SSSE3) = !!__builtin_cpu_supports("ssse3"); feat(feature::SSE4_1) = !!__builtin_cpu_supports("sse4.1"); feat(feature::SSE4_2) = !!__builtin_cpu_supports("sse4.2"); feat(feature::AVX) = __builtin_cpu_supports("avx"); feat(feature::AVX2) = __builtin_cpu_supports("avx2"); } #endif }; bool mrpt::cpu::supports(mrpt::cpu::feature f) { const auto& o = CPU_analyzer::Instance(); return o.feat(f); } std::string mrpt::cpu::features_as_string() { std::string s; const auto& o = CPU_analyzer::Instance(); using namespace mrpt::cpu; s += mrpt::format("MMX:%i ", o.feat(feature::MMX) ? 1 : 0); s += mrpt::format("POPCNT:%i ", o.feat(feature::POPCNT) ? 1 : 0); s += mrpt::format("SSE:%i ", o.feat(feature::SSE) ? 1 : 0); s += mrpt::format("SSE2:%i ", o.feat(feature::SSE2) ? 1 : 0); s += mrpt::format("SSE3:%i ", o.feat(feature::SSE3) ? 1 : 0); s += mrpt::format("SSSE3:%i ", o.feat(feature::SSSE3) ? 1 : 0); s += mrpt::format("SSE4_1:%i ", o.feat(feature::SSE4_1) ? 1 : 0); s += mrpt::format("SSE4_2:%i ", o.feat(feature::SSE4_2) ? 1 : 0); s += mrpt::format("AVX:%i ", o.feat(feature::AVX) ? 1 : 0); s += mrpt::format("AVX2:%i ", o.feat(feature::AVX2) ? 1 : 0); return s; } <commit_msg>fix CPU flags for non intel archs<commit_after>/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "core-precomp.h" // Precompiled headers #include <mrpt/core/cpu.h> #include <mrpt/core/format.h> #include <array> #if defined(_MSC_VER) #include <intrin.h> // __cpuidex #endif class CPU_analyzer { public: static CPU_analyzer& Instance() { static CPU_analyzer o; return o; } std::array< bool, static_cast<std::size_t>(mrpt::cpu::feature::FEATURE_COUNT)> feat_detected; bool& feat(mrpt::cpu::feature f) noexcept { return feat_detected[static_cast<std::size_t>(f)]; } const bool& feat(mrpt::cpu::feature f) const noexcept { return feat_detected[static_cast<std::size_t>(f)]; } private: // Ctor: runs all the checks and fills in the vector of features: CPU_analyzer() noexcept { // Start with all falses: feat_detected.fill(false); detect_impl(); } #if defined(_MSC_VER) // MSVC version void detect_impl() noexcept { // Based on: https://stackoverflow.com/a/7495023/1631514 #define cpuid(info, x) __cpuidex(info, x, 0) int info[4]; cpuid(info, 0); int nIds = info[0]; cpuid(info, 0x80000000); unsigned nExIds = info[0]; // Detect Features using namespace mrpt::cpu; if (nIds >= 0x00000001) { cpuid(info, 0x00000001); feat(feature::MMX) = !!(info[3] & (1 << 23)); feat(feature::POPCNT) = !!(info[2] & (1 << 23)); feat(feature::SSE) = !!(info[3] & (1 << 25)); feat(feature::SSE2) = !!(info[3] & (1 << 26)); feat(feature::SSE3) = !!(info[2] & (1 << 0)); feat(feature::SSSE3) = !!(info[2] & (1 << 9)); feat(feature::SSE4_1) = !!(info[2] & (1 << 19)); feat(feature::SSE4_2) = !!(info[2] & (1 << 20)); feat(feature::AVX) = !!(info[2] & (1 << 28)); } if (nIds >= 0x00000007) { cpuid(info, 0x00000007); feat(feature::AVX2) = !!(info[1] & (1 << 5)); } // Doubt: is this required? // auto xcrFeatureMask = _xgetbv(_XCR_XFEATURE_ENABLED_MASK); } #else // GCC/CLANG version void detect_impl() noexcept { // __builtin_cpu_supports() checks for both: CPU and OS support using namespace mrpt::cpu; // These ones only for intel 64bit arch: // Some might be usable in 32bit builds, but they might require // additional checks (in MSVC) and it's not worth: why building for // 32bit nowadays? #if defined(__x86_64__) feat(feature::MMX) = !!__builtin_cpu_supports("mmx"); feat(feature::POPCNT) = !!__builtin_cpu_supports("popcnt"); feat(feature::SSE) = !!__builtin_cpu_supports("sse"); feat(feature::SSE2) = !!__builtin_cpu_supports("sse2"); feat(feature::SSE3) = !!__builtin_cpu_supports("sse3"); feat(feature::SSSE3) = !!__builtin_cpu_supports("ssse3"); feat(feature::SSE4_1) = !!__builtin_cpu_supports("sse4.1"); feat(feature::SSE4_2) = !!__builtin_cpu_supports("sse4.2"); feat(feature::AVX) = __builtin_cpu_supports("avx"); feat(feature::AVX2) = __builtin_cpu_supports("avx2"); #endif } #endif }; bool mrpt::cpu::supports(mrpt::cpu::feature f) { const auto& o = CPU_analyzer::Instance(); return o.feat(f); } std::string mrpt::cpu::features_as_string() { std::string s; const auto& o = CPU_analyzer::Instance(); using namespace mrpt::cpu; s += mrpt::format("MMX:%i ", o.feat(feature::MMX) ? 1 : 0); s += mrpt::format("POPCNT:%i ", o.feat(feature::POPCNT) ? 1 : 0); s += mrpt::format("SSE:%i ", o.feat(feature::SSE) ? 1 : 0); s += mrpt::format("SSE2:%i ", o.feat(feature::SSE2) ? 1 : 0); s += mrpt::format("SSE3:%i ", o.feat(feature::SSE3) ? 1 : 0); s += mrpt::format("SSSE3:%i ", o.feat(feature::SSSE3) ? 1 : 0); s += mrpt::format("SSE4_1:%i ", o.feat(feature::SSE4_1) ? 1 : 0); s += mrpt::format("SSE4_2:%i ", o.feat(feature::SSE4_2) ? 1 : 0); s += mrpt::format("AVX:%i ", o.feat(feature::AVX) ? 1 : 0); s += mrpt::format("AVX2:%i ", o.feat(feature::AVX2) ? 1 : 0); return s; } <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2014 Clifford Wolf <clifford@clifford.at> * Copyright (C) 2014 Johann Glaser <Johann.Glaser@gmx.at> * * Permission to use, copy, modify, and/or 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 "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct WriteFileFrontend : public Frontend { WriteFileFrontend() : Frontend("=write_file", "write a text to a file") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" write_file [options] output_file [input_file]\n"); log("\n"); log("Write the text from the input file to the output file.\n"); log("\n"); log(" -a\n"); log(" Append to output file (instead of overwriting)\n"); log("\n"); log("\n"); log("Inside a script the input file can also can a here-document:\n"); log("\n"); log(" write_file hello.txt <<EOT\n"); log(" Hello World!\n"); log(" EOT\n"); log("\n"); } void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design*) YS_OVERRIDE { bool append_mode = false; std::string output_filename; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-a") { append_mode = true; continue; } break; } if (argidx < args.size() && args[argidx].rfind("-", 0) != 0) output_filename = args[argidx++]; else log_cmd_error("Missing putput filename.\n"); extra_args(f, filename, args, argidx); FILE *of = fopen(output_filename.c_str(), append_mode ? "a" : "w"); yosys_output_files.insert(output_filename); char buffer[64 * 1024]; int bytes; while (0 < (bytes = readsome(*f, buffer, sizeof(buffer)))) fwrite(buffer, bytes, 1, of); fclose(of); } } WriteFileFrontend; PRIVATE_NAMESPACE_END <commit_msg>Fix typo, fixes #1095<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2014 Clifford Wolf <clifford@clifford.at> * Copyright (C) 2014 Johann Glaser <Johann.Glaser@gmx.at> * * Permission to use, copy, modify, and/or 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 "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct WriteFileFrontend : public Frontend { WriteFileFrontend() : Frontend("=write_file", "write a text to a file") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" write_file [options] output_file [input_file]\n"); log("\n"); log("Write the text from the input file to the output file.\n"); log("\n"); log(" -a\n"); log(" Append to output file (instead of overwriting)\n"); log("\n"); log("\n"); log("Inside a script the input file can also can a here-document:\n"); log("\n"); log(" write_file hello.txt <<EOT\n"); log(" Hello World!\n"); log(" EOT\n"); log("\n"); } void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design*) YS_OVERRIDE { bool append_mode = false; std::string output_filename; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-a") { append_mode = true; continue; } break; } if (argidx < args.size() && args[argidx].rfind("-", 0) != 0) output_filename = args[argidx++]; else log_cmd_error("Missing output filename.\n"); extra_args(f, filename, args, argidx); FILE *of = fopen(output_filename.c_str(), append_mode ? "a" : "w"); yosys_output_files.insert(output_filename); char buffer[64 * 1024]; int bytes; while (0 < (bytes = readsome(*f, buffer, sizeof(buffer)))) fwrite(buffer, bytes, 1, of); fclose(of); } } WriteFileFrontend; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/***************************************************************************** * playlist_model.hpp : Model for a playlist tree **************************************************************************** * Copyright (C) 2006-2011 the VideoLAN team * $Id$ * * Authors: Clément Stenac <zorglub@videolan.org> * Jakob Leben <jleben@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef _PLAYLIST_MODEL_H_ #define _PLAYLIST_MODEL_H_ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_input.h> #include <vlc_playlist.h> #include "vlc_model.hpp" #include "playlist_item.hpp" #include <QObject> #include <QEvent> #include <QSignalMapper> #include <QMimeData> #include <QAbstractItemModel> #include <QVariant> #include <QModelIndex> #include <QAction> class PLItem; class PLSelector; class PlMimeData; class PLModel : public VLCModel { Q_OBJECT public: PLModel( playlist_t *, intf_thread_t *, playlist_item_t *, QObject *parent = 0 ); virtual ~PLModel(); /* Qt main PLModel */ static PLModel* getPLModel( intf_thread_t *p_intf ) { if(!p_intf->p_sys->pl_model ) { playlist_Lock( THEPL ); playlist_item_t *p_root = THEPL->p_playing; playlist_Unlock( THEPL ); p_intf->p_sys->pl_model = new PLModel( THEPL, p_intf, p_root, NULL ); } return p_intf->p_sys->pl_model; } /*** QAbstractItemModel subclassing ***/ /* Data structure */ virtual QVariant data( const QModelIndex &index, const int role ) const; virtual int rowCount( const QModelIndex &parent = QModelIndex() ) const; virtual Qt::ItemFlags flags( const QModelIndex &index ) const; virtual QModelIndex index( const int r, const int c, const QModelIndex &parent ) const; virtual QModelIndex parent( const QModelIndex &index ) const; /* Drag and Drop */ virtual Qt::DropActions supportedDropActions() const; virtual QMimeData* mimeData( const QModelIndexList &indexes ) const; virtual bool dropMimeData( const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &target ); virtual QStringList mimeTypes() const; /* Sort */ virtual void sort( const int column, Qt::SortOrder order = Qt::AscendingOrder ); /*** VLCModelSubInterface subclassing ***/ virtual void rebuild( playlist_item_t * p = NULL ); virtual void doDelete( QModelIndexList selected ); virtual void createNode( QModelIndex index, QString name ); virtual void renameNode( QModelIndex index, QString name ); virtual void removeAll(); /* Lookups */ virtual QModelIndex rootIndex() const; virtual void filter( const QString& search_text, const QModelIndex & root, bool b_recursive ); virtual QModelIndex currentIndex() const; virtual QModelIndex indexByPLID( const int i_plid, const int c ) const; virtual QModelIndex indexByInputItemID( const int i_inputitem_id, const int c ) const; virtual bool isTree() const; virtual bool canEdit() const; virtual bool action( QAction *action, const QModelIndexList &indexes ); virtual bool isSupportedAction( actions action, const QModelIndex & ) const; /* VLCModelSubInterface indirect slots */ virtual void activateItem( const QModelIndex &index ); protected: /* VLCModel subclassing */ bool isParent( const QModelIndex &index, const QModelIndex &current) const; bool isLeaf( const QModelIndex &index ) const; PLItem *getItem( const QModelIndex & index ) const; private: /* General */ PLItem *rootItem; playlist_t *p_playlist; /* Custom model private methods */ /* Lookups */ QModelIndex index( PLItem *, const int c ) const; /* Shallow actions (do not affect core playlist) */ void updateTreeItem( PLItem * ); void removeItem ( PLItem * ); void recurseDelete( QList<AbstractPLItem*> children, QModelIndexList *fullList ); void takeItem( PLItem * ); //will not delete item void insertChildren( PLItem *node, QList<PLItem*>& items, int i_pos ); /* ...of which the following will not update the views */ void updateChildren( PLItem * ); void updateChildren( playlist_item_t *, PLItem * ); /* Deep actions (affect core playlist) */ void dropAppendCopy( const PlMimeData * data, PLItem *target, int pos ); void dropMove( const PlMimeData * data, PLItem *target, int new_pos ); /* */ void sort( QModelIndex caller, QModelIndex rootIndex, const int column, Qt::SortOrder order ); /* Lookups */ PLItem *findByPLId( PLItem *, int i_plitemid ) const; PLItem *findByInputId( PLItem *, int i_input_itemid ) const; PLItem *findInner(PLItem *, int i_id, bool b_isinputid ) const; enum pl_nodetype { ROOTTYPE_CURRENT_PLAYING, ROOTTYPE_MEDIA_LIBRARY, ROOTTYPE_OTHER }; pl_nodetype getPLRootType() const; /* */ QString latestSearch; private slots: void processInputItemUpdate( input_item_t *); void processInputItemUpdate( input_thread_t* p_input ); void processItemRemoval( int i_pl_itemid ); void processItemAppend( int i_pl_itemid, int i_pl_itemidparent ); void activateItem( playlist_item_t *p_item ); }; class PlMimeData : public QMimeData { Q_OBJECT public: PlMimeData() {} virtual ~PlMimeData(); void appendItem( input_item_t *p_item ); QList<input_item_t*> inputItems() const; QStringList formats () const; private: QList<input_item_t*> _inputItems; QMimeData *_mimeData; }; #endif <commit_msg>Qt: fix missing slot (playlist entry of popupmenu)<commit_after>/***************************************************************************** * playlist_model.hpp : Model for a playlist tree **************************************************************************** * Copyright (C) 2006-2011 the VideoLAN team * $Id$ * * Authors: Clément Stenac <zorglub@videolan.org> * Jakob Leben <jleben@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef _PLAYLIST_MODEL_H_ #define _PLAYLIST_MODEL_H_ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_input.h> #include <vlc_playlist.h> #include "vlc_model.hpp" #include "playlist_item.hpp" #include <QObject> #include <QEvent> #include <QSignalMapper> #include <QMimeData> #include <QAbstractItemModel> #include <QVariant> #include <QModelIndex> #include <QAction> class PLItem; class PLSelector; class PlMimeData; class PLModel : public VLCModel { Q_OBJECT public: PLModel( playlist_t *, intf_thread_t *, playlist_item_t *, QObject *parent = 0 ); virtual ~PLModel(); /* Qt main PLModel */ static PLModel* getPLModel( intf_thread_t *p_intf ) { if(!p_intf->p_sys->pl_model ) { playlist_Lock( THEPL ); playlist_item_t *p_root = THEPL->p_playing; playlist_Unlock( THEPL ); p_intf->p_sys->pl_model = new PLModel( THEPL, p_intf, p_root, NULL ); } return p_intf->p_sys->pl_model; } /*** QAbstractItemModel subclassing ***/ /* Data structure */ virtual QVariant data( const QModelIndex &index, const int role ) const; virtual int rowCount( const QModelIndex &parent = QModelIndex() ) const; virtual Qt::ItemFlags flags( const QModelIndex &index ) const; virtual QModelIndex index( const int r, const int c, const QModelIndex &parent ) const; virtual QModelIndex parent( const QModelIndex &index ) const; /* Drag and Drop */ virtual Qt::DropActions supportedDropActions() const; virtual QMimeData* mimeData( const QModelIndexList &indexes ) const; virtual bool dropMimeData( const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &target ); virtual QStringList mimeTypes() const; /* Sort */ virtual void sort( const int column, Qt::SortOrder order = Qt::AscendingOrder ); /*** VLCModelSubInterface subclassing ***/ virtual void rebuild( playlist_item_t * p = NULL ); virtual void doDelete( QModelIndexList selected ); virtual void createNode( QModelIndex index, QString name ); virtual void renameNode( QModelIndex index, QString name ); virtual void removeAll(); /* Lookups */ virtual QModelIndex rootIndex() const; virtual void filter( const QString& search_text, const QModelIndex & root, bool b_recursive ); virtual QModelIndex currentIndex() const; virtual QModelIndex indexByPLID( const int i_plid, const int c ) const; virtual QModelIndex indexByInputItemID( const int i_inputitem_id, const int c ) const; virtual bool isTree() const; virtual bool canEdit() const; virtual bool action( QAction *action, const QModelIndexList &indexes ); virtual bool isSupportedAction( actions action, const QModelIndex & ) const; protected: /* VLCModel subclassing */ bool isParent( const QModelIndex &index, const QModelIndex &current) const; bool isLeaf( const QModelIndex &index ) const; PLItem *getItem( const QModelIndex & index ) const; private: /* General */ PLItem *rootItem; playlist_t *p_playlist; /* Custom model private methods */ /* Lookups */ QModelIndex index( PLItem *, const int c ) const; /* Shallow actions (do not affect core playlist) */ void updateTreeItem( PLItem * ); void removeItem ( PLItem * ); void recurseDelete( QList<AbstractPLItem*> children, QModelIndexList *fullList ); void takeItem( PLItem * ); //will not delete item void insertChildren( PLItem *node, QList<PLItem*>& items, int i_pos ); /* ...of which the following will not update the views */ void updateChildren( PLItem * ); void updateChildren( playlist_item_t *, PLItem * ); /* Deep actions (affect core playlist) */ void dropAppendCopy( const PlMimeData * data, PLItem *target, int pos ); void dropMove( const PlMimeData * data, PLItem *target, int new_pos ); /* */ void sort( QModelIndex caller, QModelIndex rootIndex, const int column, Qt::SortOrder order ); /* Lookups */ PLItem *findByPLId( PLItem *, int i_plitemid ) const; PLItem *findByInputId( PLItem *, int i_input_itemid ) const; PLItem *findInner(PLItem *, int i_id, bool b_isinputid ) const; enum pl_nodetype { ROOTTYPE_CURRENT_PLAYING, ROOTTYPE_MEDIA_LIBRARY, ROOTTYPE_OTHER }; pl_nodetype getPLRootType() const; /* */ QString latestSearch; private slots: void processInputItemUpdate( input_item_t *); void processInputItemUpdate( input_thread_t* p_input ); void processItemRemoval( int i_pl_itemid ); void processItemAppend( int i_pl_itemid, int i_pl_itemidparent ); void activateItem( playlist_item_t *p_item ); void activateItem( const QModelIndex &index ); }; class PlMimeData : public QMimeData { Q_OBJECT public: PlMimeData() {} virtual ~PlMimeData(); void appendItem( input_item_t *p_item ); QList<input_item_t*> inputItems() const; QStringList formats () const; private: QList<input_item_t*> _inputItems; QMimeData *_mimeData; }; #endif <|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 "net/http/http_auth_handler_digest.h" #include "base/md5.h" #include "base/string_util.h" #include "net/base/net_util.h" #include "net/http/http_auth.h" #include "net/http/http_request_info.h" #include "net/http/http_util.h" // TODO(eroman): support qop=auth-int namespace net { // Digest authentication is specified in RFC 2617. // The expanded derivations are listed in the tables below. //==========+==========+==========================================+ // qop |algorithm | response | //==========+==========+==========================================+ // ? | ?, md5, | MD5(MD5(A1):nonce:MD5(A2)) | // | md5-sess | | //--------- +----------+------------------------------------------+ // auth, | ?, md5, | MD5(MD5(A1):nonce:nc:cnonce:qop:MD5(A2)) | // auth-int | md5-sess | | //==========+==========+==========================================+ // qop |algorithm | A1 | //==========+==========+==========================================+ // | ?, md5 | user:realm:password | //----------+----------+------------------------------------------+ // | md5-sess | MD5(user:realm:password):nonce:cnonce | //==========+==========+==========================================+ // qop |algorithm | A2 | //==========+==========+==========================================+ // ?, auth | | req-method:req-uri | //----------+----------+------------------------------------------+ // auth-int | | req-method:req-uri:MD5(req-entity-body) | //=====================+==========================================+ // static std::string HttpAuthHandlerDigest::GenerateNonce() { // This is how mozilla generates their cnonce -- a 16 digit hex string. static const char domain[] = "0123456789abcdef"; std::string cnonce; cnonce.reserve(16); // TODO(eroman): use rand_util::RandIntSecure() for (int i = 0; i < 16; ++i) cnonce.push_back(domain[rand() % 16]); return cnonce; } // static std::string HttpAuthHandlerDigest::QopToString(int qop) { switch (qop) { case QOP_AUTH: return "auth"; case QOP_AUTH_INT: return "auth-int"; default: return ""; } } // static std::string HttpAuthHandlerDigest::AlgorithmToString(int algorithm) { switch (algorithm) { case ALGORITHM_MD5: return "MD5"; case ALGORITHM_MD5_SESS: return "MD5-sess"; default: return ""; } } std::string HttpAuthHandlerDigest::GenerateCredentials( const std::wstring& username, const std::wstring& password, const HttpRequestInfo* request, const ProxyInfo* proxy) { // Generate a random client nonce. std::string cnonce = GenerateNonce(); // The nonce-count should be incremented after re-use per the spec. // This may not be possible when there are multiple connections to the // server though: // https://bugzilla.mozilla.org/show_bug.cgi?id=114451 // TODO(eroman): leave as 1 for now, and possibly permanently. int nonce_count = 1; // Extract the request method and path -- the meaning of 'path' is overloaded // in certain cases, to be a hostname. std::string method; std::string path; GetRequestMethodAndPath(request, proxy, &method, &path); return AssembleCredentials(method, path, // TODO(eroman): is this the right encoding? WideToUTF8(username), WideToUTF8(password), cnonce, nonce_count); } void HttpAuthHandlerDigest::GetRequestMethodAndPath( const HttpRequestInfo* request, const ProxyInfo* proxy, std::string* method, std::string* path) const { DCHECK(request); DCHECK(proxy); const GURL& url = request->url; if (target_ == HttpAuth::AUTH_PROXY && url.SchemeIs("https")) { *method = "CONNECT"; *path = url.host() + ":" + GetImplicitPort(url); } else { *method = request->method; *path = HttpUtil::PathForRequest(url); } } std::string HttpAuthHandlerDigest::AssembleResponseDigest( const std::string& method, const std::string& path, const std::string& username, const std::string& password, const std::string& cnonce, const std::string& nc) const { // ha1 = MD5(A1) std::string ha1 = MD5String(username + ":" + realm_ + ":" + password); if (algorithm_ == HttpAuthHandlerDigest::ALGORITHM_MD5_SESS) ha1 = MD5String(ha1 + ":" + nonce_ + ":" + cnonce); // ha2 = MD5(A2) // TODO(eroman): need to add MD5(req-entity-body) for qop=auth-int. std::string ha2 = MD5String(method + ":" + path); std::string nc_part; if (qop_ != HttpAuthHandlerDigest::QOP_UNSPECIFIED) { nc_part = nc + ":" + cnonce + ":" + QopToString(qop_) + ":"; } return MD5String(ha1 + ":" + nonce_ + ":" + nc_part + ha2); } std::string HttpAuthHandlerDigest::AssembleCredentials( const std::string& method, const std::string& path, const std::string& username, const std::string& password, const std::string& cnonce, int nonce_count) const { // the nonce-count is an 8 digit hex string. std::string nc = StringPrintf("%08x", nonce_count); std::string authorization = std::string("Digest username=") + HttpUtil::Quote(username); authorization += ", realm=" + HttpUtil::Quote(realm_); authorization += ", nonce=" + HttpUtil::Quote(nonce_); authorization += ", uri=" + HttpUtil::Quote(path); if (algorithm_ != ALGORITHM_UNSPECIFIED) { authorization += ", algorithm=" + AlgorithmToString(algorithm_); } std::string response = AssembleResponseDigest(method, path, username, password, cnonce, nc); // No need to call HttpUtil::Quote() as the response digest cannot contain // any characters needing to be escaped. authorization += ", response=\"" + response + "\""; if (!opaque_.empty()) { authorization += ", opaque=" + HttpUtil::Quote(opaque_); } if (qop_ != QOP_UNSPECIFIED) { // TODO(eroman): Supposedly IIS server requires quotes surrounding qop. authorization += ", qop=" + QopToString(qop_); authorization += ", nc=" + nc; authorization += ", cnonce=" + HttpUtil::Quote(cnonce); } return authorization; } // The digest challenge header looks like: // WWW-Authenticate: Digest // realm="<realm-value>" // nonce="<nonce-value>" // [domain="<list-of-URIs>"] // [opaque="<opaque-token-value>"] // [stale="<true-or-false>"] // [algorithm="<digest-algorithm>"] // [qop="<list-of-qop-values>"] // [<extension-directive>] bool HttpAuthHandlerDigest::ParseChallenge( std::string::const_iterator challenge_begin, std::string::const_iterator challenge_end) { scheme_ = "digest"; score_ = 2; // Initialize to defaults. stale_ = false; algorithm_ = ALGORITHM_UNSPECIFIED; qop_ = QOP_UNSPECIFIED; realm_ = nonce_ = domain_ = opaque_ = std::string(); HttpAuth::ChallengeTokenizer props(challenge_begin, challenge_end); if (!props.valid() || !LowerCaseEqualsASCII(props.scheme(), "digest")) return false; // FAIL -- Couldn't match auth-scheme. // Loop through all the properties. while (props.GetNext()) { if (props.value().empty()) { DLOG(INFO) << "Invalid digest property"; return false; } if (!ParseChallengeProperty(props.name(), props.unquoted_value())) return false; // FAIL -- couldn't parse a property. } // Check if tokenizer failed. if (!props.valid()) return false; // FAIL // Check that a minimum set of properties were provided. if (realm_.empty() || nonce_.empty()) return false; // FAIL return true; } bool HttpAuthHandlerDigest::ParseChallengeProperty(const std::string& name, const std::string& value) { if (LowerCaseEqualsASCII(name, "realm")) { realm_ = value; } else if (LowerCaseEqualsASCII(name, "nonce")) { nonce_ = value; } else if (LowerCaseEqualsASCII(name, "domain")) { domain_ = value; } else if (LowerCaseEqualsASCII(name, "opaque")) { opaque_ = value; } else if (LowerCaseEqualsASCII(name, "stale")) { // Parse the stale boolean. stale_ = LowerCaseEqualsASCII(value, "true"); } else if (LowerCaseEqualsASCII(name, "algorithm")) { // Parse the algorithm. if (LowerCaseEqualsASCII(value, "md5")) { algorithm_ = ALGORITHM_MD5; } else if (LowerCaseEqualsASCII(value, "md5-sess")) { algorithm_ = ALGORITHM_MD5_SESS; } else { DLOG(INFO) << "Unknown value of algorithm"; return false; // FAIL -- unsupported value of algorithm. } } else if (LowerCaseEqualsASCII(name, "qop")) { // Parse the comma separated list of qops. HttpUtil::ValuesIterator qop_values(value.begin(), value.end(), ','); while (qop_values.GetNext()) { if (LowerCaseEqualsASCII(qop_values.value(), "auth")) { qop_ |= QOP_AUTH; } else if (LowerCaseEqualsASCII(qop_values.value(), "auth-int")) { qop_ |= QOP_AUTH_INT; } } } else { DLOG(INFO) << "Skipping unrecognized digest property"; // TODO(eroman): perhaps we should fail instead of silently skipping? } return true; } } // namespace net <commit_msg>Use base::RandInt() in place of rand(), now that rand_util has been moved from chrome/ to base/.<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 "net/http/http_auth_handler_digest.h" #include "base/md5.h" #include "base/rand_util.h" #include "base/string_util.h" #include "net/base/net_util.h" #include "net/http/http_auth.h" #include "net/http/http_request_info.h" #include "net/http/http_util.h" // TODO(eroman): support qop=auth-int namespace net { // Digest authentication is specified in RFC 2617. // The expanded derivations are listed in the tables below. //==========+==========+==========================================+ // qop |algorithm | response | //==========+==========+==========================================+ // ? | ?, md5, | MD5(MD5(A1):nonce:MD5(A2)) | // | md5-sess | | //--------- +----------+------------------------------------------+ // auth, | ?, md5, | MD5(MD5(A1):nonce:nc:cnonce:qop:MD5(A2)) | // auth-int | md5-sess | | //==========+==========+==========================================+ // qop |algorithm | A1 | //==========+==========+==========================================+ // | ?, md5 | user:realm:password | //----------+----------+------------------------------------------+ // | md5-sess | MD5(user:realm:password):nonce:cnonce | //==========+==========+==========================================+ // qop |algorithm | A2 | //==========+==========+==========================================+ // ?, auth | | req-method:req-uri | //----------+----------+------------------------------------------+ // auth-int | | req-method:req-uri:MD5(req-entity-body) | //=====================+==========================================+ // static std::string HttpAuthHandlerDigest::GenerateNonce() { // This is how mozilla generates their cnonce -- a 16 digit hex string. static const char domain[] = "0123456789abcdef"; std::string cnonce; cnonce.reserve(16); for (int i = 0; i < 16; ++i) cnonce.push_back(domain[base::RandInt(0, 15)]); return cnonce; } // static std::string HttpAuthHandlerDigest::QopToString(int qop) { switch (qop) { case QOP_AUTH: return "auth"; case QOP_AUTH_INT: return "auth-int"; default: return ""; } } // static std::string HttpAuthHandlerDigest::AlgorithmToString(int algorithm) { switch (algorithm) { case ALGORITHM_MD5: return "MD5"; case ALGORITHM_MD5_SESS: return "MD5-sess"; default: return ""; } } std::string HttpAuthHandlerDigest::GenerateCredentials( const std::wstring& username, const std::wstring& password, const HttpRequestInfo* request, const ProxyInfo* proxy) { // Generate a random client nonce. std::string cnonce = GenerateNonce(); // The nonce-count should be incremented after re-use per the spec. // This may not be possible when there are multiple connections to the // server though: // https://bugzilla.mozilla.org/show_bug.cgi?id=114451 // TODO(eroman): leave as 1 for now, and possibly permanently. int nonce_count = 1; // Extract the request method and path -- the meaning of 'path' is overloaded // in certain cases, to be a hostname. std::string method; std::string path; GetRequestMethodAndPath(request, proxy, &method, &path); return AssembleCredentials(method, path, // TODO(eroman): is this the right encoding? WideToUTF8(username), WideToUTF8(password), cnonce, nonce_count); } void HttpAuthHandlerDigest::GetRequestMethodAndPath( const HttpRequestInfo* request, const ProxyInfo* proxy, std::string* method, std::string* path) const { DCHECK(request); DCHECK(proxy); const GURL& url = request->url; if (target_ == HttpAuth::AUTH_PROXY && url.SchemeIs("https")) { *method = "CONNECT"; *path = url.host() + ":" + GetImplicitPort(url); } else { *method = request->method; *path = HttpUtil::PathForRequest(url); } } std::string HttpAuthHandlerDigest::AssembleResponseDigest( const std::string& method, const std::string& path, const std::string& username, const std::string& password, const std::string& cnonce, const std::string& nc) const { // ha1 = MD5(A1) std::string ha1 = MD5String(username + ":" + realm_ + ":" + password); if (algorithm_ == HttpAuthHandlerDigest::ALGORITHM_MD5_SESS) ha1 = MD5String(ha1 + ":" + nonce_ + ":" + cnonce); // ha2 = MD5(A2) // TODO(eroman): need to add MD5(req-entity-body) for qop=auth-int. std::string ha2 = MD5String(method + ":" + path); std::string nc_part; if (qop_ != HttpAuthHandlerDigest::QOP_UNSPECIFIED) { nc_part = nc + ":" + cnonce + ":" + QopToString(qop_) + ":"; } return MD5String(ha1 + ":" + nonce_ + ":" + nc_part + ha2); } std::string HttpAuthHandlerDigest::AssembleCredentials( const std::string& method, const std::string& path, const std::string& username, const std::string& password, const std::string& cnonce, int nonce_count) const { // the nonce-count is an 8 digit hex string. std::string nc = StringPrintf("%08x", nonce_count); std::string authorization = std::string("Digest username=") + HttpUtil::Quote(username); authorization += ", realm=" + HttpUtil::Quote(realm_); authorization += ", nonce=" + HttpUtil::Quote(nonce_); authorization += ", uri=" + HttpUtil::Quote(path); if (algorithm_ != ALGORITHM_UNSPECIFIED) { authorization += ", algorithm=" + AlgorithmToString(algorithm_); } std::string response = AssembleResponseDigest(method, path, username, password, cnonce, nc); // No need to call HttpUtil::Quote() as the response digest cannot contain // any characters needing to be escaped. authorization += ", response=\"" + response + "\""; if (!opaque_.empty()) { authorization += ", opaque=" + HttpUtil::Quote(opaque_); } if (qop_ != QOP_UNSPECIFIED) { // TODO(eroman): Supposedly IIS server requires quotes surrounding qop. authorization += ", qop=" + QopToString(qop_); authorization += ", nc=" + nc; authorization += ", cnonce=" + HttpUtil::Quote(cnonce); } return authorization; } // The digest challenge header looks like: // WWW-Authenticate: Digest // realm="<realm-value>" // nonce="<nonce-value>" // [domain="<list-of-URIs>"] // [opaque="<opaque-token-value>"] // [stale="<true-or-false>"] // [algorithm="<digest-algorithm>"] // [qop="<list-of-qop-values>"] // [<extension-directive>] bool HttpAuthHandlerDigest::ParseChallenge( std::string::const_iterator challenge_begin, std::string::const_iterator challenge_end) { scheme_ = "digest"; score_ = 2; // Initialize to defaults. stale_ = false; algorithm_ = ALGORITHM_UNSPECIFIED; qop_ = QOP_UNSPECIFIED; realm_ = nonce_ = domain_ = opaque_ = std::string(); HttpAuth::ChallengeTokenizer props(challenge_begin, challenge_end); if (!props.valid() || !LowerCaseEqualsASCII(props.scheme(), "digest")) return false; // FAIL -- Couldn't match auth-scheme. // Loop through all the properties. while (props.GetNext()) { if (props.value().empty()) { DLOG(INFO) << "Invalid digest property"; return false; } if (!ParseChallengeProperty(props.name(), props.unquoted_value())) return false; // FAIL -- couldn't parse a property. } // Check if tokenizer failed. if (!props.valid()) return false; // FAIL // Check that a minimum set of properties were provided. if (realm_.empty() || nonce_.empty()) return false; // FAIL return true; } bool HttpAuthHandlerDigest::ParseChallengeProperty(const std::string& name, const std::string& value) { if (LowerCaseEqualsASCII(name, "realm")) { realm_ = value; } else if (LowerCaseEqualsASCII(name, "nonce")) { nonce_ = value; } else if (LowerCaseEqualsASCII(name, "domain")) { domain_ = value; } else if (LowerCaseEqualsASCII(name, "opaque")) { opaque_ = value; } else if (LowerCaseEqualsASCII(name, "stale")) { // Parse the stale boolean. stale_ = LowerCaseEqualsASCII(value, "true"); } else if (LowerCaseEqualsASCII(name, "algorithm")) { // Parse the algorithm. if (LowerCaseEqualsASCII(value, "md5")) { algorithm_ = ALGORITHM_MD5; } else if (LowerCaseEqualsASCII(value, "md5-sess")) { algorithm_ = ALGORITHM_MD5_SESS; } else { DLOG(INFO) << "Unknown value of algorithm"; return false; // FAIL -- unsupported value of algorithm. } } else if (LowerCaseEqualsASCII(name, "qop")) { // Parse the comma separated list of qops. HttpUtil::ValuesIterator qop_values(value.begin(), value.end(), ','); while (qop_values.GetNext()) { if (LowerCaseEqualsASCII(qop_values.value(), "auth")) { qop_ |= QOP_AUTH; } else if (LowerCaseEqualsASCII(qop_values.value(), "auth-int")) { qop_ |= QOP_AUTH_INT; } } } else { DLOG(INFO) << "Skipping unrecognized digest property"; // TODO(eroman): perhaps we should fail instead of silently skipping? } return true; } } // namespace net <|endoftext|>
<commit_before>#include "ExifParser.h" #include <math.h> #include <QtEndian> #include <QDateTime> ExifParser::ExifParser() { } ExifParser::~ExifParser() { } double ExifParser::readTime(QByteArray& buf) { char tiffHeader[] = {static_cast<char>(0x49),static_cast<char>(0x49),static_cast<char>(0x2A),static_cast<char>(0x00)}; char createDateHeader[] = {static_cast<char>(0x04),static_cast<char>(0x90),static_cast<char>(0x02),static_cast<char>(0x00)}; // find header position uint32_t tiffHeaderIndex = buf.indexOf(tiffHeader); // find creation date header index uint32_t createDateHeaderIndex = buf.indexOf(createDateHeader); // extract size of date-time string, -1 accounting for null-termination uint32_t* sizeString = reinterpret_cast<uint32_t*>(buf.mid(createDateHeaderIndex + 4, 4).data()); uint32_t createDateStringSize = qFromLittleEndian(*sizeString) - 1; // extract location of date-time string uint32_t* dataIndex = reinterpret_cast<uint32_t*>(buf.mid(createDateHeaderIndex + 8, 4).data()); uint32_t createDateStringDataIndex = qFromLittleEndian(*dataIndex) + tiffHeaderIndex; // read out data of create date-time field QString createDate = buf.mid(createDateStringDataIndex, createDateStringSize); QStringList createDateList = createDate.split(' '); if (createDateList.count() < 2) { qWarning() << "Could not decode creation time and date: " << createDateList; return -1.0; } QStringList dateList = createDateList[0].split(':'); if (dateList.count() < 3) { qWarning() << "Could not decode creation date: " << dateList; return -1.0; } QStringList timeList = createDateList[1].split(':'); if (timeList.count() < 3) { qWarning() << "Could not decode creation time: " << timeList; return -1.0; } QDate date(dateList[0].toInt(), dateList[1].toInt(), dateList[2].toInt()); QTime time(timeList[0].toInt(), timeList[1].toInt(), timeList[2].toInt()); QDateTime tagTime(date, time); return tagTime.toMSecsSinceEpoch()/1000.0; } bool ExifParser::write(QByteArray &buf, QGeoCoordinate coordinate) { QByteArray app1Header; app1Header.append(0xff); app1Header.append(0xe1); uint32_t app1HeaderInd = buf.indexOf(app1Header); uint16_t *conversionPointer = reinterpret_cast<uint16_t *>(buf.mid(app1HeaderInd + 2, 2).data()); uint16_t app1Size = *conversionPointer; uint16_t app1SizeEndian = qFromBigEndian(app1Size) + 0xa5; // change wrong endian char tiffHeader[4] = {0x49, 0x49, 0x2A, 0x00}; uint32_t tiffHeaderInd = buf.indexOf(tiffHeader); conversionPointer = reinterpret_cast<uint16_t *>(buf.mid(tiffHeaderInd + 8, 2).data()); uint16_t numberOfTiffFields = *conversionPointer; uint32_t nextIfdOffsetInd = tiffHeaderInd + 10 + 12 * (numberOfTiffFields); conversionPointer = reinterpret_cast<uint16_t *>(buf.mid(nextIfdOffsetInd, 2).data()); uint16_t nextIfdOffset = *conversionPointer; // Definition of usefull unions and structs union char2uint32_u { char c[4]; uint32_t i; }; union char2uint16_u { char c[2]; uint16_t i; }; // This struct describes a standart field used in exif files struct field_s { uint16_t tagID; // Describes which information is added here, e.g. GPS Lat uint16_t type; // Describes the data type, e.g. string, uint8_t,... uint32_t size; // Describes the size uint32_t content; // Either contains the information, or the offset to the exif header where the information is stored (if 32 bits is not enough) }; // This struct contains all the fields that we want to add to the image struct fields_s { field_s gpsVersion; field_s gpsLatRef; field_s gpsLat; field_s gpsLonRef; field_s gpsLon; field_s gpsAltRef; field_s gpsAlt; field_s gpsMapDatum; uint32_t finishedDataField; }; // These are the additional information that can not be put into a single uin32_t struct extended_s { uint32_t gpsLat[6]; uint32_t gpsLon[6]; uint32_t gpsAlt[2]; char mapDatum[7];// = {0x57,0x47,0x53,0x2D,0x38,0x34,0x00}; }; // This struct contains all the information we want to add to the image struct readable_s { fields_s fields; extended_s extendedData; }; // This union is used because for writing the information we have to use a char array, but we still want the information to be available in a more descriptive way union { char c[0xa3]; readable_s readable; } gpsData; char2uint32_u gpsIFDInd; gpsIFDInd.i = nextIfdOffset; // this will stay constant char gpsInfo[12] = {static_cast<char>(0x25), static_cast<char>(0x88), static_cast<char>(0x04), static_cast<char>(0x00), static_cast<char>(0x01), static_cast<char>(0x00), static_cast<char>(0x00), static_cast<char>(0x00), static_cast<char>(gpsIFDInd.c[0]), static_cast<char>(gpsIFDInd.c[1]), static_cast<char>(gpsIFDInd.c[2]), static_cast<char>(gpsIFDInd.c[3])}; // filling values to gpsData uint32_t gpsDataExtInd = gpsIFDInd.i + 2 + sizeof(fields_s); // Filling up the fields with the corresponding values gpsData.readable.fields.gpsVersion.tagID = 0; gpsData.readable.fields.gpsVersion.type = 1; gpsData.readable.fields.gpsVersion.size = 4; gpsData.readable.fields.gpsVersion.content = 2; gpsData.readable.fields.gpsLatRef.tagID = 1; gpsData.readable.fields.gpsLatRef.type = 2; gpsData.readable.fields.gpsLatRef.size = 2; gpsData.readable.fields.gpsLatRef.content = coordinate.latitude() > 0 ? 'N' : 'S'; gpsData.readable.fields.gpsLat.tagID = 2; gpsData.readable.fields.gpsLat.type = 5; gpsData.readable.fields.gpsLat.size = 3; gpsData.readable.fields.gpsLat.content = gpsDataExtInd; gpsData.readable.fields.gpsLonRef.tagID = 3; gpsData.readable.fields.gpsLonRef.type = 2; gpsData.readable.fields.gpsLonRef.size = 2; gpsData.readable.fields.gpsLonRef.content = coordinate.longitude() > 0 ? 'E' : 'W'; gpsData.readable.fields.gpsLon.tagID = 4; gpsData.readable.fields.gpsLon.type = 5; gpsData.readable.fields.gpsLon.size = 3; gpsData.readable.fields.gpsLon.content = gpsDataExtInd + 6 * 4; gpsData.readable.fields.gpsAltRef.tagID = 5; gpsData.readable.fields.gpsAltRef.type = 2; gpsData.readable.fields.gpsAltRef.size = 2; gpsData.readable.fields.gpsAltRef.content = 0x00; gpsData.readable.fields.gpsAlt.tagID = 6; gpsData.readable.fields.gpsAlt.type = 5; gpsData.readable.fields.gpsAlt.size = 1; gpsData.readable.fields.gpsAlt.content = gpsDataExtInd + 6 * 4 * 2; gpsData.readable.fields.gpsMapDatum.tagID = 18; gpsData.readable.fields.gpsMapDatum.type = 2; gpsData.readable.fields.gpsMapDatum.size = 7; gpsData.readable.fields.gpsMapDatum.content = gpsDataExtInd + 6 * 4 * 2 + 2 * 4; gpsData.readable.fields.finishedDataField = 0; // Filling up the additional information that does not fit into the fields gpsData.readable.extendedData.gpsLat[0] = abs(static_cast<int>(coordinate.latitude())); gpsData.readable.extendedData.gpsLat[1] = 1; gpsData.readable.extendedData.gpsLat[2] = static_cast<int>((fabs(coordinate.latitude()) - floor(fabs(coordinate.latitude()))) * 60000.0); gpsData.readable.extendedData.gpsLat[3] = 1000; gpsData.readable.extendedData.gpsLat[4] = 0; gpsData.readable.extendedData.gpsLat[5] = 1; gpsData.readable.extendedData.gpsLon[0] = abs(static_cast<int>(coordinate.longitude())); gpsData.readable.extendedData.gpsLon[1] = 1; gpsData.readable.extendedData.gpsLon[2] = static_cast<int>((fabs(coordinate.longitude()) - floor(fabs(coordinate.longitude()))) * 60000.0); gpsData.readable.extendedData.gpsLon[3] = 1000; gpsData.readable.extendedData.gpsLon[4] = 0; gpsData.readable.extendedData.gpsLon[5] = 1; gpsData.readable.extendedData.gpsAlt[0] = coordinate.altitude() * 100; gpsData.readable.extendedData.gpsAlt[1] = 100; gpsData.readable.extendedData.mapDatum[0] = 'W'; gpsData.readable.extendedData.mapDatum[1] = 'G'; gpsData.readable.extendedData.mapDatum[2] = 'S'; gpsData.readable.extendedData.mapDatum[3] = '-'; gpsData.readable.extendedData.mapDatum[4] = '8'; gpsData.readable.extendedData.mapDatum[5] = '4'; gpsData.readable.extendedData.mapDatum[6] = 0x00; // remove 12 spaces from image description, as otherwise we need to loop through every field and correct the new address values buf.remove(nextIfdOffsetInd + 4, 12); // TODO correct size in image description // insert Gps Info to image file buf.insert(nextIfdOffsetInd, gpsInfo, 12); char numberOfFields[2] = {0x08, 0x00}; // insert number of gps specific fields that we want to add buf.insert(gpsIFDInd.i + tiffHeaderInd, numberOfFields, 2); // insert the gps data buf.insert(gpsIFDInd.i + 2 + tiffHeaderInd, gpsData.c, 0xa3); // update the new file size and exif offsets char2uint16_u converter; converter.i = qToBigEndian(app1SizeEndian); buf.replace(app1HeaderInd + 2, 2, converter.c, 2); converter.i = nextIfdOffset + 12 + 0xa5; buf.replace(nextIfdOffsetInd + 12, 2, converter.c, 2); converter.i = (numberOfTiffFields) + 1; buf.replace(tiffHeaderInd + 8, 2, converter.c, 2); return true; } <commit_msg>casting to unsigned chars<commit_after>#include "ExifParser.h" #include <math.h> #include <QtEndian> #include <QDateTime> ExifParser::ExifParser() { } ExifParser::~ExifParser() { } double ExifParser::readTime(QByteArray& buf) { QByteArray tiffHeader("\x49\x49\x2A", 3); QByteArray createDateHeader("\x04\x90\x02", 3); // find header position uint32_t tiffHeaderIndex = buf.indexOf(tiffHeader); // find creation date header index uint32_t createDateHeaderIndex = buf.indexOf(createDateHeader); // extract size of date-time string, -1 accounting for null-termination uint32_t* sizeString = reinterpret_cast<uint32_t*>(buf.mid(createDateHeaderIndex + 4, 4).data()); uint32_t createDateStringSize = qFromLittleEndian(*sizeString) - 1; // extract location of date-time string uint32_t* dataIndex = reinterpret_cast<uint32_t*>(buf.mid(createDateHeaderIndex + 8, 4).data()); uint32_t createDateStringDataIndex = qFromLittleEndian(*dataIndex) + tiffHeaderIndex; // read out data of create date-time field QString createDate = buf.mid(createDateStringDataIndex, createDateStringSize); QStringList createDateList = createDate.split(' '); if (createDateList.count() < 2) { qWarning() << "Could not decode creation time and date: " << createDateList; return -1.0; } QStringList dateList = createDateList[0].split(':'); if (dateList.count() < 3) { qWarning() << "Could not decode creation date: " << dateList; return -1.0; } QStringList timeList = createDateList[1].split(':'); if (timeList.count() < 3) { qWarning() << "Could not decode creation time: " << timeList; return -1.0; } QDate date(dateList[0].toInt(), dateList[1].toInt(), dateList[2].toInt()); QTime time(timeList[0].toInt(), timeList[1].toInt(), timeList[2].toInt()); QDateTime tagTime(date, time); return tagTime.toMSecsSinceEpoch()/1000.0; } bool ExifParser::write(QByteArray &buf, QGeoCoordinate coordinate) { QByteArray app1Header("\xff\xe1", 2); uint32_t app1HeaderInd = buf.indexOf(app1Header); uint16_t *conversionPointer = reinterpret_cast<uint16_t *>(buf.mid(app1HeaderInd + 2, 2).data()); uint16_t app1Size = *conversionPointer; uint16_t app1SizeEndian = qFromBigEndian(app1Size) + 0xa5; // change wrong endian QByteArray tiffHeader("\x49\x49\x2A", 3); uint32_t tiffHeaderInd = buf.indexOf(tiffHeader); conversionPointer = reinterpret_cast<uint16_t *>(buf.mid(tiffHeaderInd + 8, 2).data()); uint16_t numberOfTiffFields = *conversionPointer; uint32_t nextIfdOffsetInd = tiffHeaderInd + 10 + 12 * (numberOfTiffFields); conversionPointer = reinterpret_cast<uint16_t *>(buf.mid(nextIfdOffsetInd, 2).data()); uint16_t nextIfdOffset = *conversionPointer; // Definition of usefull unions and structs union char2uint32_u { char c[4]; uint32_t i; }; union char2uint16_u { char c[2]; uint16_t i; }; // This struct describes a standart field used in exif files struct field_s { uint16_t tagID; // Describes which information is added here, e.g. GPS Lat uint16_t type; // Describes the data type, e.g. string, uint8_t,... uint32_t size; // Describes the size uint32_t content; // Either contains the information, or the offset to the exif header where the information is stored (if 32 bits is not enough) }; // This struct contains all the fields that we want to add to the image struct fields_s { field_s gpsVersion; field_s gpsLatRef; field_s gpsLat; field_s gpsLonRef; field_s gpsLon; field_s gpsAltRef; field_s gpsAlt; field_s gpsMapDatum; uint32_t finishedDataField; }; // These are the additional information that can not be put into a single uin32_t struct extended_s { uint32_t gpsLat[6]; uint32_t gpsLon[6]; uint32_t gpsAlt[2]; char mapDatum[7];// = {0x57,0x47,0x53,0x2D,0x38,0x34,0x00}; }; // This struct contains all the information we want to add to the image struct readable_s { fields_s fields; extended_s extendedData; }; // This union is used because for writing the information we have to use a char array, but we still want the information to be available in a more descriptive way union { char c[0xa3]; readable_s readable; } gpsData; char2uint32_u gpsIFDInd; gpsIFDInd.i = nextIfdOffset; // this will stay constant QByteArray gpsInfo("\x25\x88\x04\x00\x01\x00\x00\x00", 8); gpsInfo.append(gpsIFDInd.c[0]); gpsInfo.append(gpsIFDInd.c[1]); gpsInfo.append(gpsIFDInd.c[2]); gpsInfo.append(gpsIFDInd.c[3]); // filling values to gpsData uint32_t gpsDataExtInd = gpsIFDInd.i + 2 + sizeof(fields_s); // Filling up the fields with the corresponding values gpsData.readable.fields.gpsVersion.tagID = 0; gpsData.readable.fields.gpsVersion.type = 1; gpsData.readable.fields.gpsVersion.size = 4; gpsData.readable.fields.gpsVersion.content = 2; gpsData.readable.fields.gpsLatRef.tagID = 1; gpsData.readable.fields.gpsLatRef.type = 2; gpsData.readable.fields.gpsLatRef.size = 2; gpsData.readable.fields.gpsLatRef.content = coordinate.latitude() > 0 ? 'N' : 'S'; gpsData.readable.fields.gpsLat.tagID = 2; gpsData.readable.fields.gpsLat.type = 5; gpsData.readable.fields.gpsLat.size = 3; gpsData.readable.fields.gpsLat.content = gpsDataExtInd; gpsData.readable.fields.gpsLonRef.tagID = 3; gpsData.readable.fields.gpsLonRef.type = 2; gpsData.readable.fields.gpsLonRef.size = 2; gpsData.readable.fields.gpsLonRef.content = coordinate.longitude() > 0 ? 'E' : 'W'; gpsData.readable.fields.gpsLon.tagID = 4; gpsData.readable.fields.gpsLon.type = 5; gpsData.readable.fields.gpsLon.size = 3; gpsData.readable.fields.gpsLon.content = gpsDataExtInd + 6 * 4; gpsData.readable.fields.gpsAltRef.tagID = 5; gpsData.readable.fields.gpsAltRef.type = 2; gpsData.readable.fields.gpsAltRef.size = 2; gpsData.readable.fields.gpsAltRef.content = 0x00; gpsData.readable.fields.gpsAlt.tagID = 6; gpsData.readable.fields.gpsAlt.type = 5; gpsData.readable.fields.gpsAlt.size = 1; gpsData.readable.fields.gpsAlt.content = gpsDataExtInd + 6 * 4 * 2; gpsData.readable.fields.gpsMapDatum.tagID = 18; gpsData.readable.fields.gpsMapDatum.type = 2; gpsData.readable.fields.gpsMapDatum.size = 7; gpsData.readable.fields.gpsMapDatum.content = gpsDataExtInd + 6 * 4 * 2 + 2 * 4; gpsData.readable.fields.finishedDataField = 0; // Filling up the additional information that does not fit into the fields gpsData.readable.extendedData.gpsLat[0] = abs(static_cast<int>(coordinate.latitude())); gpsData.readable.extendedData.gpsLat[1] = 1; gpsData.readable.extendedData.gpsLat[2] = static_cast<int>((fabs(coordinate.latitude()) - floor(fabs(coordinate.latitude()))) * 60000.0); gpsData.readable.extendedData.gpsLat[3] = 1000; gpsData.readable.extendedData.gpsLat[4] = 0; gpsData.readable.extendedData.gpsLat[5] = 1; gpsData.readable.extendedData.gpsLon[0] = abs(static_cast<int>(coordinate.longitude())); gpsData.readable.extendedData.gpsLon[1] = 1; gpsData.readable.extendedData.gpsLon[2] = static_cast<int>((fabs(coordinate.longitude()) - floor(fabs(coordinate.longitude()))) * 60000.0); gpsData.readable.extendedData.gpsLon[3] = 1000; gpsData.readable.extendedData.gpsLon[4] = 0; gpsData.readable.extendedData.gpsLon[5] = 1; gpsData.readable.extendedData.gpsAlt[0] = coordinate.altitude() * 100; gpsData.readable.extendedData.gpsAlt[1] = 100; gpsData.readable.extendedData.mapDatum[0] = 'W'; gpsData.readable.extendedData.mapDatum[1] = 'G'; gpsData.readable.extendedData.mapDatum[2] = 'S'; gpsData.readable.extendedData.mapDatum[3] = '-'; gpsData.readable.extendedData.mapDatum[4] = '8'; gpsData.readable.extendedData.mapDatum[5] = '4'; gpsData.readable.extendedData.mapDatum[6] = 0x00; // remove 12 spaces from image description, as otherwise we need to loop through every field and correct the new address values buf.remove(nextIfdOffsetInd + 4, 12); // TODO correct size in image description // insert Gps Info to image file buf.insert(nextIfdOffsetInd, gpsInfo, 12); char numberOfFields[2] = {0x08, 0x00}; // insert number of gps specific fields that we want to add buf.insert(gpsIFDInd.i + tiffHeaderInd, numberOfFields, 2); // insert the gps data buf.insert(gpsIFDInd.i + 2 + tiffHeaderInd, gpsData.c, 0xa3); // update the new file size and exif offsets char2uint16_u converter; converter.i = qToBigEndian(app1SizeEndian); buf.replace(app1HeaderInd + 2, 2, converter.c, 2); converter.i = nextIfdOffset + 12 + 0xa5; buf.replace(nextIfdOffsetInd + 12, 2, converter.c, 2); converter.i = (numberOfTiffFields) + 1; buf.replace(tiffHeaderInd + 8, 2, converter.c, 2); return true; } <|endoftext|>
<commit_before>// RobotBuilder Version: 1.5 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // C++ from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. #include "AutonOneTote.h" #include "LiftXTicks.h" #include "../Subsystems/Lift.h" #include "DriveXFeet.h" #include "ParallelArmsOut.h" #include "ParallelArmsIn.h" #include "DelayCommand.h" AutonOneTote::AutonOneTote() { // Add Commands here: // e.g. AddSequential(new Command1()); // AddSequential(new Command2()); // these will run in order. // To run multiple commands at the same time, // use AddParallel() // e.g. AddParallel(new Command1()); // AddSequential(new Command2()); // Command1 and Command2 will run in parallel. // A command group will require all of the subsystems that each member // would require. // e.g. if Command1 requires chassis, and Command2 requires arm, // a CommandGroup containing them would require both the chassis and the // arm. // grabbing one tote and moving it to auto zone and move away AddSequential (new ParallelArmsIn()); AddSequential (new DelayCommand(1)); AddSequential(new LiftXTicks(Lift:: TOTE_TWO_ENGAGE_TICKS,Lift::SPEED_UP)); AddSequential (new DriveXFeet(-10, .3)); AddSequential(new LiftXTicks(Lift:: TOTE_ONE_ENGAGE_TICKS,Lift::SPEED_DOWN)); AddSequential (new ParallelArmsOut()); // may want to add this to all command groups so it is ovbious we are not touching totes; AddSequential (new DriveXFeet(-.5, .3)); // to clear away from bin AddSequential (new LiftXTicks(Lift::GO_OVER_BIN_TICKS, Lift::SPEED_UP)); } <commit_msg>change to lift in Auton<commit_after>// RobotBuilder Version: 1.5 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // C++ from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. #include "AutonOneTote.h" #include "LiftXTicks.h" #include "../Subsystems/Lift.h" #include "DriveXFeet.h" #include "ParallelArmsOut.h" #include "ParallelArmsIn.h" #include "DelayCommand.h" AutonOneTote::AutonOneTote() { // Add Commands here: // e.g. AddSequential(new Command1()); // AddSequential(new Command2()); // these will run in order. // To run multiple commands at the same time, // use AddParallel() // e.g. AddParallel(new Command1()); // AddSequential(new Command2()); // Command1 and Command2 will run in parallel. // A command group will require all of the subsystems that each member // would require. // e.g. if Command1 requires chassis, and Command2 requires arm, // a CommandGroup containing them would require both the chassis and the // arm. // grabbing one tote and moving it to auto zone and move away AddSequential (new ParallelArmsIn()); AddSequential (new DelayCommand(1)); AddSequential(new LiftXTicks(Lift:: TOTE_TWO_ENGAGE_TICKS,Lift::SPEED_UP)); AddSequential (new DriveXFeet(-10, .3)); AddSequential(new LiftXTicks(Lift:: TOTE_ONE_ENGAGE_TICKS,Lift::SPEED_DOWN)); AddSequential (new ParallelArmsOut()); // may want to add this to all command groups so it is ovbious we are not touching totes; AddSequential (new DriveXFeet(-.5, .3)); // to clear away from bin AddSequential (new LiftXTicks(Lift::TOTE_TWO_ENGAGE_TICKS, Lift::SPEED_UP)); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LifeTime.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 00:42:04 $ * * 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 _LIFETIME_HXX #define _LIFETIME_HXX #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _OSL_CONDITN_HXX_ #include <osl/conditn.hxx> #endif #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HDL_ #include <com/sun/star/uno/Exception.hdl> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _COM_SUN_STAR_UTIL_XCLOSELISTENER_HPP_ #include <com/sun/star/util/XCloseListener.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XCLOSEABLE_HPP_ #include <com/sun/star/util/XCloseable.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _CPPUHELPER_WEAKREF_HXX_ #include <cppuhelper/weakref.hxx> #endif namespace apphelper { class LifeTimeGuard; class LifeTimeManager { friend class LifeTimeGuard; public: LifeTimeManager( ::com::sun::star::lang::XComponent* pComponent, sal_Bool bLongLastingCallsCancelable = sal_False ); virtual ~LifeTimeManager(); sal_Bool impl_isDisposed(); sal_Bool dispose() throw(::com::sun::star::uno::RuntimeException); public: ::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; protected: virtual sal_Bool impl_canStartApiCall(); virtual void impl_apiCallCountReachedNull(){} void impl_registerApiCall(sal_Bool bLongLastingCall); void impl_unregisterApiCall(sal_Bool bLongLastingCall); void impl_init(); protected: mutable ::osl::Mutex m_aAccessMutex; ::com::sun::star::lang::XComponent* m_pComponent; ::osl::Condition m_aNoAccessCountCondition; sal_Int32 volatile m_nAccessCount; sal_Bool volatile m_bDisposed; sal_Bool volatile m_bInDispose; // sal_Bool m_bLongLastingCallsCancelable; ::osl::Condition m_aNoLongLastingCallCountCondition; sal_Int32 volatile m_nLongLastingCallCount; }; class CloseableLifeTimeManager : public LifeTimeManager { protected: ::com::sun::star::util::XCloseable* m_pCloseable; ::osl::Condition m_aEndTryClosingCondition; sal_Bool volatile m_bClosed; sal_Bool volatile m_bInTryClose; //the ownership between model and controller is not clear at first //each controller might consider him as owner of the model first //at start the model is not considered as owner of itself sal_Bool volatile m_bOwnership; //with a XCloseable::close call and during XCloseListener::queryClosing //the ownership can be regulated more explicit, //if so the ownership is considered to be well known sal_Bool volatile m_bOwnershipIsWellKnown; public: CloseableLifeTimeManager( ::com::sun::star::util::XCloseable* pCloseable , ::com::sun::star::lang::XComponent* pComponent , sal_Bool bLongLastingCallsCancelable = sal_False ); virtual ~CloseableLifeTimeManager(); sal_Bool impl_isDisposedOrClosed(); sal_Bool g_close_startTryClose(sal_Bool bDeliverOwnership) throw ( ::com::sun::star::uno::Exception ); sal_Bool g_close_isNeedToCancelLongLastingCalls( sal_Bool bDeliverOwnership, ::com::sun::star::uno::Exception& ex ) throw ( ::com::sun::star::uno::Exception ); void g_close_endTryClose(sal_Bool bDeliverOwnership, sal_Bool bMyVeto, ::com::sun::star::uno::Exception& ex) throw ( ::com::sun::star::uno::Exception ); void g_close_endTryClose_doClose(); sal_Bool g_addCloseListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloseListener > & xListener ) throw(::com::sun::star::uno::RuntimeException); protected: virtual sal_Bool impl_canStartApiCall(); virtual void impl_apiCallCountReachedNull(); void impl_setOwnership( sal_Bool bDeliverOwnership, sal_Bool bMyVeto ); sal_Bool impl_shouldCloseAtNextChance(); void impl_doClose(); void impl_init() { m_bClosed = sal_False; m_bInTryClose = sal_False; m_bOwnership = sal_False; m_bOwnershipIsWellKnown = sal_False; m_aEndTryClosingCondition.set(); } }; //----------------------------------------------------------------- /* Use this Guard in your apicalls to protect access on resources which will be released in dispose. It's guarantied, that the release of resources only starts if your guarded call has finished. ! It's only partly guaranteed that this resources will not change during the call. See the example for details. This class is to be used as described in the example. If this guard is used in all api calls of an XCloseable object it's guarantied, that the closeable will close itself after finishing the last call if it should do so. ::ApiCall { //hold no mutex!!! LifeTimeGuard aLifeTimeGuard(m_aLifeTimeManager); //mutex is acquired; call is not registered if(!aGuard.startApiCall()) return ; //behave as passive as possible, if disposed or closed //mutex is acquired, call is registered { //you might access some private members here //but than you need to protect access to these members always like this //never call to the outside here } aLifeTimeGuard.clear(); //!!! //Mutex is released, the running call is still registered //this call will finish before the 'release-section' in dispose is allowed to start { //you might access some private members here guarded with your own mutex //but release your mutex at the end of this block } //you can call to the outside (without holding the mutex) without becoming disposed //End of method -> ~LifeTimeGuard //-> call is unregistered //-> this object might be disposed now } your XComponent::dispose method has to be implemented in the following way: ::dispose() { //hold no mutex!!! if( !m_aLifeTimeManager.dispose() ) return; //--release all resources and references //... } */ //----------------------------------------------------------------- class LifeTimeGuard : public ::osl::ResettableMutexGuard { public: LifeTimeGuard( LifeTimeManager& rManager ) : ::osl::ResettableGuard< ::osl::Mutex >( rManager.m_aAccessMutex ) , m_rManager(rManager) , m_bCallRegistered(sal_False) , m_bLongLastingCallRegistered(sal_False) { } sal_Bool startApiCall(sal_Bool bLongLastingCall=sal_False); virtual ~LifeTimeGuard(); private: LifeTimeManager& m_rManager; sal_Bool m_bCallRegistered; sal_Bool m_bLongLastingCallRegistered; private: // these make no sense LifeTimeGuard( ::osl::Mutex& rMutex ); LifeTimeGuard( const LifeTimeGuard& ); LifeTimeGuard& operator= ( const LifeTimeGuard& ); }; template<class T> class NegativeGuard { protected: T * m_pT; public: NegativeGuard(T * pT) : m_pT(pT) { m_pT->release(); } NegativeGuard(T & t) : m_pT(&t) { m_pT->release(); } ~NegativeGuard() { m_pT->acquire(); } }; }//end namespace apphelper #endif <commit_msg>INTEGRATION: CWS chart2mst3 (1.2.4); FILE MERGED 2005/10/07 11:41:53 bm 1.2.4.3: RESYNC: (1.2-1.3); FILE MERGED 2005/08/25 16:24:10 bm 1.2.4.2: #124570# CloseVetoException was passed as Exception to function before throw, which discarded the type. This violated the throw specification later that only allows the CloseVetoException 2004/04/26 11:42:14 iha 1.2.4.1: corrected comment<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LifeTime.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2007-05-22 18:18:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _LIFETIME_HXX #define _LIFETIME_HXX #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _OSL_CONDITN_HXX_ #include <osl/conditn.hxx> #endif #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HDL_ #include <com/sun/star/uno/Exception.hdl> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _COM_SUN_STAR_UTIL_XCLOSELISTENER_HPP_ #include <com/sun/star/util/XCloseListener.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XCLOSEABLE_HPP_ #include <com/sun/star/util/XCloseable.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _CPPUHELPER_WEAKREF_HXX_ #include <cppuhelper/weakref.hxx> #endif namespace apphelper { class LifeTimeGuard; class LifeTimeManager { friend class LifeTimeGuard; public: LifeTimeManager( ::com::sun::star::lang::XComponent* pComponent, sal_Bool bLongLastingCallsCancelable = sal_False ); virtual ~LifeTimeManager(); sal_Bool impl_isDisposed(); sal_Bool dispose() throw(::com::sun::star::uno::RuntimeException); public: ::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; protected: virtual sal_Bool impl_canStartApiCall(); virtual void impl_apiCallCountReachedNull(){} void impl_registerApiCall(sal_Bool bLongLastingCall); void impl_unregisterApiCall(sal_Bool bLongLastingCall); void impl_init(); protected: mutable ::osl::Mutex m_aAccessMutex; ::com::sun::star::lang::XComponent* m_pComponent; ::osl::Condition m_aNoAccessCountCondition; sal_Int32 volatile m_nAccessCount; sal_Bool volatile m_bDisposed; sal_Bool volatile m_bInDispose; // sal_Bool m_bLongLastingCallsCancelable; ::osl::Condition m_aNoLongLastingCallCountCondition; sal_Int32 volatile m_nLongLastingCallCount; }; class CloseableLifeTimeManager : public LifeTimeManager { protected: ::com::sun::star::util::XCloseable* m_pCloseable; ::osl::Condition m_aEndTryClosingCondition; sal_Bool volatile m_bClosed; sal_Bool volatile m_bInTryClose; //the ownership between model and controller is not clear at first //each controller might consider him as owner of the model first //at start the model is not considered as owner of itself sal_Bool volatile m_bOwnership; //with a XCloseable::close call and during XCloseListener::queryClosing //the ownership can be regulated more explicit, //if so the ownership is considered to be well known sal_Bool volatile m_bOwnershipIsWellKnown; public: CloseableLifeTimeManager( ::com::sun::star::util::XCloseable* pCloseable , ::com::sun::star::lang::XComponent* pComponent , sal_Bool bLongLastingCallsCancelable = sal_False ); virtual ~CloseableLifeTimeManager(); sal_Bool impl_isDisposedOrClosed(); sal_Bool g_close_startTryClose(sal_Bool bDeliverOwnership) throw ( ::com::sun::star::uno::Exception ); sal_Bool g_close_isNeedToCancelLongLastingCalls( sal_Bool bDeliverOwnership, ::com::sun::star::util::CloseVetoException& ex ) throw ( ::com::sun::star::util::CloseVetoException ); void g_close_endTryClose(sal_Bool bDeliverOwnership, sal_Bool bMyVeto ); void g_close_endTryClose_doClose(); sal_Bool g_addCloseListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloseListener > & xListener ) throw(::com::sun::star::uno::RuntimeException); protected: virtual sal_Bool impl_canStartApiCall(); virtual void impl_apiCallCountReachedNull(); void impl_setOwnership( sal_Bool bDeliverOwnership, sal_Bool bMyVeto ); sal_Bool impl_shouldCloseAtNextChance(); void impl_doClose(); void impl_init() { m_bClosed = sal_False; m_bInTryClose = sal_False; m_bOwnership = sal_False; m_bOwnershipIsWellKnown = sal_False; m_aEndTryClosingCondition.set(); } }; //----------------------------------------------------------------- /* Use this Guard in your apicalls to protect access on resources which will be released in dispose. It's guarantied, that the release of resources only starts if your guarded call has finished. ! It's only partly guaranteed that this resources will not change during the call. See the example for details. This class is to be used as described in the example. If this guard is used in all api calls of an XCloseable object it's guarantied, that the closeable will close itself after finishing the last call if it should do so. ::ApiCall { //hold no mutex!!! LifeTimeGuard aLifeTimeGuard(m_aLifeTimeManager); //mutex is acquired; call is not registered if(!aLifeTimeGuard.startApiCall()) return ; //behave as passive as possible, if disposed or closed //mutex is acquired, call is registered { //you might access some private members here //but than you need to protect access to these members always like this //never call to the outside here } aLifeTimeGuard.clear(); //!!! //Mutex is released, the running call is still registered //this call will finish before the 'release-section' in dispose is allowed to start { //you might access some private members here guarded with your own mutex //but release your mutex at the end of this block } //you can call to the outside (without holding the mutex) without becoming disposed //End of method -> ~LifeTimeGuard //-> call is unregistered //-> this object might be disposed now } your XComponent::dispose method has to be implemented in the following way: ::dispose() { //hold no mutex!!! if( !m_aLifeTimeManager.dispose() ) return; //--release all resources and references //... } */ //----------------------------------------------------------------- class LifeTimeGuard : public ::osl::ResettableMutexGuard { public: LifeTimeGuard( LifeTimeManager& rManager ) : ::osl::ResettableGuard< ::osl::Mutex >( rManager.m_aAccessMutex ) , m_rManager(rManager) , m_bCallRegistered(sal_False) , m_bLongLastingCallRegistered(sal_False) { } sal_Bool startApiCall(sal_Bool bLongLastingCall=sal_False); virtual ~LifeTimeGuard(); private: LifeTimeManager& m_rManager; sal_Bool m_bCallRegistered; sal_Bool m_bLongLastingCallRegistered; private: // these make no sense LifeTimeGuard( ::osl::Mutex& rMutex ); LifeTimeGuard( const LifeTimeGuard& ); LifeTimeGuard& operator= ( const LifeTimeGuard& ); }; template<class T> class NegativeGuard { protected: T * m_pT; public: NegativeGuard(T * pT) : m_pT(pT) { m_pT->release(); } NegativeGuard(T & t) : m_pT(&t) { m_pT->release(); } ~NegativeGuard() { m_pT->acquire(); } }; }//end namespace apphelper #endif <|endoftext|>
<commit_before>#include "sweep.h" #include "protocol.h" #include "serial.h" #include <chrono> #include <thread> int32_t sweep_get_version(void) { return SWEEP_VERSION; } bool sweep_is_abi_compatible(void) { return sweep_get_version() >> 16u == SWEEP_VERSION_MAJOR; } typedef struct sweep_error { const char* what; // always literal, do not deallocate } sweep_error; typedef struct sweep_device { sweep::serial::device_s serial; // serial port communication bool is_scanning; } sweep_device; #define SWEEP_MAX_SAMPLES 4096 typedef struct sweep_scan { int32_t angle[SWEEP_MAX_SAMPLES]; // in millidegrees int32_t distance[SWEEP_MAX_SAMPLES]; // in cm int32_t signal_strength[SWEEP_MAX_SAMPLES]; // range 0:255 int32_t count; } sweep_scan; // Constructor hidden from users static sweep_error_s sweep_error_construct(const char* what) { SWEEP_ASSERT(what); auto out = new sweep_error{what}; return out; } const char* sweep_error_message(sweep_error_s error) { SWEEP_ASSERT(error); return error->what; } void sweep_error_destruct(sweep_error_s error) { SWEEP_ASSERT(error); delete error; } sweep_device_s sweep_device_construct_simple(sweep_error_s* error) { SWEEP_ASSERT(error); return sweep_device_construct("/dev/ttyUSB0", 115200, error); } sweep_device_s sweep_device_construct(const char* port, int32_t bitrate, sweep_error_s* error) { SWEEP_ASSERT(port); SWEEP_ASSERT(bitrate > 0); SWEEP_ASSERT(error); sweep::serial::error_s serialerror = nullptr; sweep::serial::device_s serial = sweep::serial::device_construct(port, bitrate, &serialerror); if (serialerror) { *error = sweep_error_construct(sweep::serial::error_message(serialerror)); sweep::serial::error_destruct(serialerror); return nullptr; } auto out = new sweep_device{serial, /*is_scanning=*/true}; sweep_error_s stoperror = nullptr; sweep_device_stop_scanning(out, &stoperror); if (stoperror) { *error = stoperror; sweep_device_destruct(out); return nullptr; } return out; } void sweep_device_destruct(sweep_device_s device) { SWEEP_ASSERT(device); sweep_error_s ignore = nullptr; sweep_device_stop_scanning(device, &ignore); (void)ignore; // nothing we can do here sweep::serial::device_destruct(device->serial); delete device; } void sweep_device_start_scanning(sweep_device_s device, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(error); SWEEP_ASSERT(!device->is_scanning); if (device->is_scanning) return; sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command(device->serial, sweep::protocol::DATA_ACQUISITION_START, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send start scanning command"); sweep::protocol::error_destruct(protocolerror); return; } sweep::protocol::response_header_s response; sweep::protocol::read_response_header(device->serial, sweep::protocol::DATA_ACQUISITION_START, &response, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive start scanning command response"); sweep::protocol::error_destruct(protocolerror); return; } device->is_scanning = true; } void sweep_device_stop_scanning(sweep_device_s device, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(error); if (!device->is_scanning) return; sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command(device->serial, sweep::protocol::DATA_ACQUISITION_STOP, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send stop scanning command"); sweep::protocol::error_destruct(protocolerror); return; } // Wait until device stopped sending std::this_thread::sleep_for(std::chrono::milliseconds(20)); sweep::serial::error_s serialerror = nullptr; sweep::serial::device_flush(device->serial, &serialerror); if (serialerror) { *error = sweep_error_construct("unable to flush serial device for stopping scanning command"); sweep::serial::error_destruct(serialerror); return; } sweep::protocol::write_command(device->serial, sweep::protocol::DATA_ACQUISITION_STOP, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send stop scanning command"); sweep::protocol::error_destruct(protocolerror); return; } sweep::protocol::response_header_s response; sweep::protocol::read_response_header(device->serial, sweep::protocol::DATA_ACQUISITION_STOP, &response, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive stop scanning command response"); sweep::protocol::error_destruct(protocolerror); return; } device->is_scanning = false; } sweep_scan_s sweep_device_get_scan(sweep_device_s device, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(error); SWEEP_ASSERT(device->is_scanning); sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::response_scan_packet_s responses[SWEEP_MAX_SAMPLES]; int32_t received = 0; while (received < SWEEP_MAX_SAMPLES) { sweep::protocol::read_response_scan(device->serial, &responses[received], &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive sweep scan response"); sweep::protocol::error_destruct(protocolerror); return nullptr; } const bool is_sync = responses[received].sync_error & sweep::protocol::response_scan_packet_sync::sync; const bool has_error = (responses[received].sync_error >> 1) != 0; // shift out sync bit, others are errors if (!has_error) { received++; } if (is_sync) { break; } } auto out = new sweep_scan; out->count = received; for (int32_t it = 0; it < received; ++it) { // Convert angle from compact serial format to float (in degrees). // In addition convert from degrees to milli-degrees. out->angle[it] = sweep::protocol::u16_to_f32(responses[it].angle) * 1000.f; out->distance[it] = responses[it].distance; out->signal_strength[it] = responses[it].signal_strength; } return out; } int32_t sweep_scan_get_number_of_samples(sweep_scan_s scan) { SWEEP_ASSERT(scan); SWEEP_ASSERT(scan->count >= 0); return scan->count; } int32_t sweep_scan_get_angle(sweep_scan_s scan, int32_t sample) { SWEEP_ASSERT(scan); SWEEP_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds"); return scan->angle[sample]; } int32_t sweep_scan_get_distance(sweep_scan_s scan, int32_t sample) { SWEEP_ASSERT(scan); SWEEP_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds"); return scan->distance[sample]; } int32_t sweep_scan_get_signal_strength(sweep_scan_s scan, int32_t sample) { SWEEP_ASSERT(scan); SWEEP_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds"); return scan->signal_strength[sample]; } void sweep_scan_destruct(sweep_scan_s scan) { SWEEP_ASSERT(scan); delete scan; } int32_t sweep_device_get_motor_speed(sweep_device_s device, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(error); SWEEP_ASSERT(!device->is_scanning); sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command(device->serial, sweep::protocol::MOTOR_INFORMATION, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send motor speed command"); sweep::protocol::error_destruct(protocolerror); return 0; } sweep::protocol::response_info_motor_s response; sweep::protocol::read_response_info_motor(device->serial, sweep::protocol::MOTOR_INFORMATION, &response, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive motor speed command response"); sweep::protocol::error_destruct(protocolerror); return 0; } int32_t speed = sweep::protocol::ascii_bytes_to_integral(response.motor_speed); SWEEP_ASSERT(speed >= 0); return speed; } void sweep_device_set_motor_speed(sweep_device_s device, int32_t hz, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(hz >= 0 && hz <= 10); SWEEP_ASSERT(error); SWEEP_ASSERT(!device->is_scanning); uint8_t args[2] = {0}; sweep::protocol::integral_to_ascii_bytes(hz, args); sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command_with_arguments(device->serial, sweep::protocol::MOTOR_SPEED_ADJUST, args, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send motor speed command"); sweep::protocol::error_destruct(protocolerror); return; } sweep::protocol::response_param_s response; sweep::protocol::read_response_param(device->serial, sweep::protocol::MOTOR_SPEED_ADJUST, &response, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive motor speed command response"); sweep::protocol::error_destruct(protocolerror); return; } } int32_t sweep_device_get_sample_rate(sweep_device_s device, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(error); SWEEP_ASSERT(!device->is_scanning); sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command(device->serial, sweep::protocol::SAMPLE_RATE_INFORMATION, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send sample rate command"); sweep::protocol::error_destruct(protocolerror); return 0; } sweep::protocol::response_info_sample_rate_s response; sweep::protocol::read_response_info_sample_rate(device->serial, sweep::protocol::SAMPLE_RATE_INFORMATION, &response, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive sample rate command response"); sweep::protocol::error_destruct(protocolerror); return 0; } // 01: 500-600Hz, 02: 750-800Hz, 03: 1000-1050Hz int32_t code = sweep::protocol::ascii_bytes_to_integral(response.sample_rate); int32_t rate = 0; switch (code) { case 1: rate = 500; break; case 2: rate = 750; break; case 3: rate = 1000; break; default: SWEEP_ASSERT(false && "sample rate code unknown"); } return rate; } void sweep_device_set_sample_rate(sweep_device_s device, int32_t hz, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(hz == 500 || hz == 750 || hz == 1000); SWEEP_ASSERT(error); SWEEP_ASSERT(!device->is_scanning); // 01: 500-600Hz, 02: 750-800Hz, 03: 1000-1050Hz int32_t code = 1; switch (hz) { case 500: code = 1; break; case 750: code = 2; break; case 1000: code = 3; break; default: SWEEP_ASSERT(false && "sample rate unknown"); } uint8_t args[2] = {0}; sweep::protocol::integral_to_ascii_bytes(code, args); sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command_with_arguments(device->serial, sweep::protocol::SAMPLE_RATE_ADJUST, args, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send sample rate command"); sweep::protocol::error_destruct(protocolerror); return; } sweep::protocol::response_param_s response; sweep::protocol::read_response_param(device->serial, sweep::protocol::SAMPLE_RATE_ADJUST, &response, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive sample rate command response"); sweep::protocol::error_destruct(protocolerror); return; } } void sweep_device_reset(sweep_device_s device, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(error); SWEEP_ASSERT(!device->is_scanning); sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command(device->serial, sweep::protocol::RESET_DEVICE, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send device reset command"); sweep::protocol::error_destruct(protocolerror); return; } } <commit_msg>Formats impl. with clang-format<commit_after>#include "sweep.h" #include "protocol.h" #include "serial.h" #include <chrono> #include <thread> int32_t sweep_get_version(void) { return SWEEP_VERSION; } bool sweep_is_abi_compatible(void) { return sweep_get_version() >> 16u == SWEEP_VERSION_MAJOR; } typedef struct sweep_error { const char* what; // always literal, do not deallocate } sweep_error; typedef struct sweep_device { sweep::serial::device_s serial; // serial port communication bool is_scanning; } sweep_device; #define SWEEP_MAX_SAMPLES 4096 typedef struct sweep_scan { int32_t angle[SWEEP_MAX_SAMPLES]; // in millidegrees int32_t distance[SWEEP_MAX_SAMPLES]; // in cm int32_t signal_strength[SWEEP_MAX_SAMPLES]; // range 0:255 int32_t count; } sweep_scan; // Constructor hidden from users static sweep_error_s sweep_error_construct(const char* what) { SWEEP_ASSERT(what); auto out = new sweep_error{what}; return out; } const char* sweep_error_message(sweep_error_s error) { SWEEP_ASSERT(error); return error->what; } void sweep_error_destruct(sweep_error_s error) { SWEEP_ASSERT(error); delete error; } sweep_device_s sweep_device_construct_simple(sweep_error_s* error) { SWEEP_ASSERT(error); return sweep_device_construct("/dev/ttyUSB0", 115200, error); } sweep_device_s sweep_device_construct(const char* port, int32_t bitrate, sweep_error_s* error) { SWEEP_ASSERT(port); SWEEP_ASSERT(bitrate > 0); SWEEP_ASSERT(error); sweep::serial::error_s serialerror = nullptr; sweep::serial::device_s serial = sweep::serial::device_construct(port, bitrate, &serialerror); if (serialerror) { *error = sweep_error_construct(sweep::serial::error_message(serialerror)); sweep::serial::error_destruct(serialerror); return nullptr; } auto out = new sweep_device{serial, /*is_scanning=*/true}; sweep_error_s stoperror = nullptr; sweep_device_stop_scanning(out, &stoperror); if (stoperror) { *error = stoperror; sweep_device_destruct(out); return nullptr; } return out; } void sweep_device_destruct(sweep_device_s device) { SWEEP_ASSERT(device); sweep_error_s ignore = nullptr; sweep_device_stop_scanning(device, &ignore); (void)ignore; // nothing we can do here sweep::serial::device_destruct(device->serial); delete device; } void sweep_device_start_scanning(sweep_device_s device, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(error); SWEEP_ASSERT(!device->is_scanning); if (device->is_scanning) return; sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command(device->serial, sweep::protocol::DATA_ACQUISITION_START, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send start scanning command"); sweep::protocol::error_destruct(protocolerror); return; } sweep::protocol::response_header_s response; sweep::protocol::read_response_header(device->serial, sweep::protocol::DATA_ACQUISITION_START, &response, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive start scanning command response"); sweep::protocol::error_destruct(protocolerror); return; } device->is_scanning = true; } void sweep_device_stop_scanning(sweep_device_s device, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(error); if (!device->is_scanning) return; sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command(device->serial, sweep::protocol::DATA_ACQUISITION_STOP, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send stop scanning command"); sweep::protocol::error_destruct(protocolerror); return; } // Wait until device stopped sending std::this_thread::sleep_for(std::chrono::milliseconds(20)); sweep::serial::error_s serialerror = nullptr; sweep::serial::device_flush(device->serial, &serialerror); if (serialerror) { *error = sweep_error_construct("unable to flush serial device for stopping scanning command"); sweep::serial::error_destruct(serialerror); return; } sweep::protocol::write_command(device->serial, sweep::protocol::DATA_ACQUISITION_STOP, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send stop scanning command"); sweep::protocol::error_destruct(protocolerror); return; } sweep::protocol::response_header_s response; sweep::protocol::read_response_header(device->serial, sweep::protocol::DATA_ACQUISITION_STOP, &response, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive stop scanning command response"); sweep::protocol::error_destruct(protocolerror); return; } device->is_scanning = false; } sweep_scan_s sweep_device_get_scan(sweep_device_s device, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(error); SWEEP_ASSERT(device->is_scanning); sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::response_scan_packet_s responses[SWEEP_MAX_SAMPLES]; int32_t received = 0; while (received < SWEEP_MAX_SAMPLES) { sweep::protocol::read_response_scan(device->serial, &responses[received], &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive sweep scan response"); sweep::protocol::error_destruct(protocolerror); return nullptr; } const bool is_sync = responses[received].sync_error & sweep::protocol::response_scan_packet_sync::sync; const bool has_error = (responses[received].sync_error >> 1) != 0; // shift out sync bit, others are errors if (!has_error) { received++; } if (is_sync) { break; } } auto out = new sweep_scan; out->count = received; for (int32_t it = 0; it < received; ++it) { // Convert angle from compact serial format to float (in degrees). // In addition convert from degrees to milli-degrees. out->angle[it] = sweep::protocol::u16_to_f32(responses[it].angle) * 1000.f; out->distance[it] = responses[it].distance; out->signal_strength[it] = responses[it].signal_strength; } return out; } int32_t sweep_scan_get_number_of_samples(sweep_scan_s scan) { SWEEP_ASSERT(scan); SWEEP_ASSERT(scan->count >= 0); return scan->count; } int32_t sweep_scan_get_angle(sweep_scan_s scan, int32_t sample) { SWEEP_ASSERT(scan); SWEEP_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds"); return scan->angle[sample]; } int32_t sweep_scan_get_distance(sweep_scan_s scan, int32_t sample) { SWEEP_ASSERT(scan); SWEEP_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds"); return scan->distance[sample]; } int32_t sweep_scan_get_signal_strength(sweep_scan_s scan, int32_t sample) { SWEEP_ASSERT(scan); SWEEP_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds"); return scan->signal_strength[sample]; } void sweep_scan_destruct(sweep_scan_s scan) { SWEEP_ASSERT(scan); delete scan; } int32_t sweep_device_get_motor_speed(sweep_device_s device, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(error); SWEEP_ASSERT(!device->is_scanning); sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command(device->serial, sweep::protocol::MOTOR_INFORMATION, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send motor speed command"); sweep::protocol::error_destruct(protocolerror); return 0; } sweep::protocol::response_info_motor_s response; sweep::protocol::read_response_info_motor(device->serial, sweep::protocol::MOTOR_INFORMATION, &response, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive motor speed command response"); sweep::protocol::error_destruct(protocolerror); return 0; } int32_t speed = sweep::protocol::ascii_bytes_to_integral(response.motor_speed); SWEEP_ASSERT(speed >= 0); return speed; } void sweep_device_set_motor_speed(sweep_device_s device, int32_t hz, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(hz >= 0 && hz <= 10); SWEEP_ASSERT(error); SWEEP_ASSERT(!device->is_scanning); uint8_t args[2] = {0}; sweep::protocol::integral_to_ascii_bytes(hz, args); sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command_with_arguments(device->serial, sweep::protocol::MOTOR_SPEED_ADJUST, args, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send motor speed command"); sweep::protocol::error_destruct(protocolerror); return; } sweep::protocol::response_param_s response; sweep::protocol::read_response_param(device->serial, sweep::protocol::MOTOR_SPEED_ADJUST, &response, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive motor speed command response"); sweep::protocol::error_destruct(protocolerror); return; } } int32_t sweep_device_get_sample_rate(sweep_device_s device, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(error); SWEEP_ASSERT(!device->is_scanning); sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command(device->serial, sweep::protocol::SAMPLE_RATE_INFORMATION, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send sample rate command"); sweep::protocol::error_destruct(protocolerror); return 0; } sweep::protocol::response_info_sample_rate_s response; sweep::protocol::read_response_info_sample_rate(device->serial, sweep::protocol::SAMPLE_RATE_INFORMATION, &response, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive sample rate command response"); sweep::protocol::error_destruct(protocolerror); return 0; } // 01: 500-600Hz, 02: 750-800Hz, 03: 1000-1050Hz int32_t code = sweep::protocol::ascii_bytes_to_integral(response.sample_rate); int32_t rate = 0; switch (code) { case 1: rate = 500; break; case 2: rate = 750; break; case 3: rate = 1000; break; default: SWEEP_ASSERT(false && "sample rate code unknown"); } return rate; } void sweep_device_set_sample_rate(sweep_device_s device, int32_t hz, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(hz == 500 || hz == 750 || hz == 1000); SWEEP_ASSERT(error); SWEEP_ASSERT(!device->is_scanning); // 01: 500-600Hz, 02: 750-800Hz, 03: 1000-1050Hz int32_t code = 1; switch (hz) { case 500: code = 1; break; case 750: code = 2; break; case 1000: code = 3; break; default: SWEEP_ASSERT(false && "sample rate unknown"); } uint8_t args[2] = {0}; sweep::protocol::integral_to_ascii_bytes(code, args); sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command_with_arguments(device->serial, sweep::protocol::SAMPLE_RATE_ADJUST, args, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send sample rate command"); sweep::protocol::error_destruct(protocolerror); return; } sweep::protocol::response_param_s response; sweep::protocol::read_response_param(device->serial, sweep::protocol::SAMPLE_RATE_ADJUST, &response, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to receive sample rate command response"); sweep::protocol::error_destruct(protocolerror); return; } } void sweep_device_reset(sweep_device_s device, sweep_error_s* error) { SWEEP_ASSERT(device); SWEEP_ASSERT(error); SWEEP_ASSERT(!device->is_scanning); sweep::protocol::error_s protocolerror = nullptr; sweep::protocol::write_command(device->serial, sweep::protocol::RESET_DEVICE, &protocolerror); if (protocolerror) { *error = sweep_error_construct("unable to send device reset command"); sweep::protocol::error_destruct(protocolerror); return; } } <|endoftext|>
<commit_before><commit_msg>Framework: delete the redundant code, adjust frame ratio for UI<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sddll.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2004-12-13 12:32:38 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _EEITEM_HXX //autogen #include <svx/eeitem.hxx> #endif #include <svx/editeng.hxx> #ifndef _SVDOBJ_HXX //autogen #include <svx/svdobj.hxx> #endif #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX #include <svtools/moduleoptions.hxx> #endif #ifndef _FM_FMOBJFAC_HXX #include <svx/fmobjfac.hxx> #endif #ifndef _SVX_SIIMPORT_HXX #include <svx/siimport.hxx> #endif #ifndef _SVDFIELD_HXX #include <svx/svdfield.hxx> #endif #ifndef _OBJFAC3D_HXX #include <svx/objfac3d.hxx> #endif #pragma hdrstop #include "sddll.hxx" #ifndef SD_DRAW_DOC_SHELL_HXX #include "DrawDocShell.hxx" #endif #ifndef SD_GRAPHIC_DOC_SHELL_HXX #include "GraphicDocShell.hxx" #endif #include "sdresid.hxx" #include "sdobjfac.hxx" #include "cfgids.hxx" #include "strmname.h" #include "SdShapeTypes.hxx" #include <svx/SvxShapeTypes.hxx> #include <sfx2/docfilt.hxx> #include <sfx2/docfile.hxx> #include <sfx2/fcontnr.hxx> #include <tools/urlobj.hxx> #include <svx/impgrf.hxx> #include <svtools/FilterConfigItem.hxx> #ifndef _COM_SUN_STAR_UTIL_XARCHIVER_HPP_ #include <com/sun/star/util/XArchiver.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star; /************************************************************************* |* |* Init |* \************************************************************************/ void SdDLL::Init() { if ( SD_MOD() ) return; SfxObjectFactory* pDrawFact = NULL; SfxObjectFactory* pImpressFact = NULL; if (SvtModuleOptions().IsImpress()) pImpressFact = &::sd::DrawDocShell::Factory(); if (SvtModuleOptions().IsDraw()) pDrawFact = &::sd::GraphicDocShell::Factory(); // the SdModule must be created SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW); (*ppShlPtr) = new SdModule( pImpressFact, pDrawFact); if (SvtModuleOptions().IsImpress()) { // Register the Impress shape types in order to make the shapes accessible. ::accessibility::RegisterImpressShapeTypes (); ::sd::DrawDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.presentation.PresentationDocument" ) ) ); ::sd::DrawDocShell::Factory().RegisterMenuBar( SdResId( RID_DRAW_DEFAULTMENU ) ); ::sd::DrawDocShell::Factory().RegisterAccel( SdResId( RID_DRAW_DEFAULTACCEL ) ); } if (SvtModuleOptions().IsDraw()) { ::sd::GraphicDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.DrawingDocument" ) ) ); ::sd::GraphicDocShell::Factory().RegisterMenuBar( SdResId( RID_GRAPHIC_DEFAULTMENU ) ); ::sd::GraphicDocShell::Factory().RegisterAccel( SdResId( RID_GRAPHIC_DEFAULTACCEL ) ); } // register your view-factories here RegisterFactorys(); // register your shell-interfaces here RegisterInterfaces(); // register your controllers here RegisterControllers(); // SvDraw-Felder registrieren SdrRegisterFieldClasses(); // 3D-Objekt-Factory eintragen E3dObjFactory(); // ::com::sun::star::form::component::Form-Objekt-Factory eintragen FmFormObjFactory(); // factory for dummy import of old si-controls in 3.1 documents //BFS02 SiImportFactory(); // Objekt-Factory eintragen SdrObjFactory::InsertMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData)); } /************************************************************************* |* |* Exit |* \************************************************************************/ void SdDLL::Exit() { // called directly befor unloading the DLL // do whatever you want, Sd-DLL is accessible // Objekt-Factory austragen SdrObjFactory::RemoveMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData)); // the SdModule must be destroyed SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW); delete (*ppShlPtr); (*ppShlPtr) = NULL; } /* ULONG SdDLL::DetectFilter(SfxMedium& rMedium, const SfxFilter** ppFilter, SfxFilterFlags nMust, SfxFilterFlags nDont) { ULONG nReturn = ERRCODE_ABORT; // Erkennung fehlgeschlagen, Filter ungueltig BOOL bStorage = FALSE; if( *ppFilter && (*ppFilter)->GetFilterFlags() & SFX_FILTER_PACKED ) { uno::Reference< lang::XMultiServiceFactory > xSMgr( ::comphelper::getProcessServiceFactory() ); uno::Reference< util::XArchiver > xPacker( xSMgr->createInstance( OUString::createFromAscii( "com.sun.star.util.Archiver" ) ), uno::UNO_QUERY ); if( xPacker.is() ) { // extract extra data OUString aPath( rMedium.GetOrigURL() ); OUString aExtraData( xPacker->getExtraData( aPath ) ); const OUString aSig1= OUString::createFromAscii( "private:" ); String aTmp; aTmp += sal_Unicode( '?' ); aTmp += String::CreateFromAscii("simpress"); const OUString aSig2( aTmp ); INT32 nIndex1 = aExtraData.indexOf( aSig1 ); INT32 nIndex2 = aExtraData.indexOf( aSig2 ); if( nIndex1 == 0 && nIndex2 != -1 ) return ERRCODE_NONE; } } else if (rMedium.GetError() == SVSTREAM_OK) { if ( rMedium.IsStorage() ) { bStorage = TRUE; SotStorageRef xStorage = rMedium.GetStorage(); if ( !xStorage.Is() ) return ULONG_MAX; if( SvtModuleOptions().IsImpress() ) { // Erkennung ueber contained streams (PowerPoint 97-Filter) String aStreamName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "PowerPoint Document" ) ); if ( xStorage->IsContained( aStreamName ) && xStorage->IsStream( aStreamName ) ) { String aFileName(rMedium.GetName()); aFileName.ToUpperAscii(); if( aFileName.SearchAscii( ".POT" ) == STRING_NOTFOUND ) *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97); else *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97Template ); return ERRCODE_NONE; } } const SfxFilter* pFilter = *ppFilter; if ( *ppFilter ) { if ( (*ppFilter)->GetFormat() == xStorage->GetFormat() ) pFilter = *ppFilter; } if( !pFilter && SvtModuleOptions().IsImpress() ) { SfxFilterMatcher aMatcher( String::CreateFromAscii("simpress") ); pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() ); if ( pFilter ) *ppFilter = pFilter; } if( !pFilter && SvtModuleOptions().IsDraw() ) { SfxFilterMatcher aMatcher( String::CreateFromAscii("sdraw") ); pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() ); if ( pFilter ) *ppFilter = pFilter; } if ( pFilter && ( pFilter->GetFilterFlags() & nMust ) == nMust && ( pFilter->GetFilterFlags() & nDont ) == 0 ) { *ppFilter = pFilter; nReturn = ERRCODE_NONE; } else { *ppFilter = NULL; nReturn = ERRCODE_NONE; } } String aFileName( rMedium.GetName() ); aFileName.ToUpperAscii(); if ( nReturn == ERRCODE_ABORT ) { if( bStorage ) // aber keine Clipboard-Id #55337# { *ppFilter = NULL; } else { // Vektorgraphik? SvStream* pStm = rMedium.GetInStream(); if( !pStm ) nReturn = ERRCODE_IO_GENERAL; else { pStm->Seek( STREAM_SEEK_TO_BEGIN ); const String aFileName( rMedium.GetURLObject().GetMainURL( INetURLObject::NO_DECODE ) ); GraphicDescriptor aDesc( *pStm, &aFileName ); GraphicFilter* pGrfFilter = GetGrfFilter(); if( !aDesc.Detect( FALSE ) ) { if( SvtModuleOptions().IsImpress() ) { *ppFilter = NULL; nReturn = ERRCODE_ABORT; INetURLObject aURL( aFileName ); if( aURL.getExtension().equalsIgnoreAsciiCaseAscii( "cgm" ) ) { sal_uInt8 n8; pStm->Seek( STREAM_SEEK_TO_BEGIN ); *pStm >> n8; if ( ( n8 & 0xf0 ) == 0 ) // we are supporting binary cgm format only, so { // this is a small test to exclude cgm text const String aName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "CGM - Computer Graphics Metafile" ) ); SfxFilterMatcher aMatch( String::CreateFromAscii("simpress") ); *ppFilter = aMatch.GetFilter4FilterName( aName ); nReturn = ERRCODE_NONE; } } } } else { if( SvtModuleOptions().IsDraw() ) { String aShortName( aDesc.GetImportFormatShortName( aDesc.GetFileFormat() ) ); const String aName( pGrfFilter->GetImportFormatTypeName( pGrfFilter->GetImportFormatNumberForShortName( aShortName ) ) ); if ( *ppFilter && aShortName.EqualsIgnoreCaseAscii( "PCD" ) ) // there is a multiple pcd selection possible { sal_Int32 nBase = 2; // default Base0 String aFilterTypeName( (*ppFilter)->GetRealTypeName() ); if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base4" ) == COMPARE_EQUAL ) nBase = 1; else if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base16" ) == COMPARE_EQUAL ) nBase = 0; String aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Graphic/Import/PCD" ) ); FilterConfigItem aFilterConfigItem( aFilterConfigPath ); aFilterConfigItem.WriteInt32( String( RTL_CONSTASCII_USTRINGPARAM( "Resolution" ) ), nBase ); } SfxFilterMatcher aMatch( String::CreateFromAscii("draw") ); *ppFilter = aMatch.GetFilter4FilterName( aName ); nReturn = ERRCODE_NONE; } else { nReturn = ERRCODE_ABORT; *ppFilter = NULL; } } } } } } else { nReturn = rMedium.GetError(); } return nReturn; } */ <commit_msg>INTEGRATION: CWS impress44 (1.10.140); FILE MERGED 2005/04/06 08:39:16 cl 1.10.140.1: #i46427# do not call SfxModule() with an empty factory as first factory<commit_after>/************************************************************************* * * $RCSfile: sddll.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: obo $ $Date: 2005-04-12 16:55:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _EEITEM_HXX //autogen #include <svx/eeitem.hxx> #endif #include <svx/editeng.hxx> #ifndef _SVDOBJ_HXX //autogen #include <svx/svdobj.hxx> #endif #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX #include <svtools/moduleoptions.hxx> #endif #ifndef _FM_FMOBJFAC_HXX #include <svx/fmobjfac.hxx> #endif #ifndef _SVX_SIIMPORT_HXX #include <svx/siimport.hxx> #endif #ifndef _SVDFIELD_HXX #include <svx/svdfield.hxx> #endif #ifndef _OBJFAC3D_HXX #include <svx/objfac3d.hxx> #endif #pragma hdrstop #include "sddll.hxx" #ifndef SD_DRAW_DOC_SHELL_HXX #include "DrawDocShell.hxx" #endif #ifndef SD_GRAPHIC_DOC_SHELL_HXX #include "GraphicDocShell.hxx" #endif #include "sdresid.hxx" #include "sdobjfac.hxx" #include "cfgids.hxx" #include "strmname.h" #include "SdShapeTypes.hxx" #include <svx/SvxShapeTypes.hxx> #include <sfx2/docfilt.hxx> #include <sfx2/docfile.hxx> #include <sfx2/fcontnr.hxx> #include <tools/urlobj.hxx> #include <svx/impgrf.hxx> #include <svtools/FilterConfigItem.hxx> #ifndef _COM_SUN_STAR_UTIL_XARCHIVER_HPP_ #include <com/sun/star/util/XArchiver.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star; /************************************************************************* |* |* Init |* \************************************************************************/ void SdDLL::Init() { if ( SD_MOD() ) return; SfxObjectFactory* pDrawFact = NULL; SfxObjectFactory* pImpressFact = NULL; if (SvtModuleOptions().IsImpress()) pImpressFact = &::sd::DrawDocShell::Factory(); if (SvtModuleOptions().IsDraw()) pDrawFact = &::sd::GraphicDocShell::Factory(); // the SdModule must be created SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW); // #i46427# // The SfxModule::SfxModule stops when the first given factory // is 0, so we must not give a 0 as first factory if( pImpressFact ) { (*ppShlPtr) = new SdModule( pImpressFact, pDrawFact ); } else { (*ppShlPtr) = new SdModule( pDrawFact, pImpressFact ); } if (SvtModuleOptions().IsImpress()) { // Register the Impress shape types in order to make the shapes accessible. ::accessibility::RegisterImpressShapeTypes (); ::sd::DrawDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.presentation.PresentationDocument" ) ) ); ::sd::DrawDocShell::Factory().RegisterMenuBar( SdResId( RID_DRAW_DEFAULTMENU ) ); ::sd::DrawDocShell::Factory().RegisterAccel( SdResId( RID_DRAW_DEFAULTACCEL ) ); } if (SvtModuleOptions().IsDraw()) { ::sd::GraphicDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.DrawingDocument" ) ) ); ::sd::GraphicDocShell::Factory().RegisterMenuBar( SdResId( RID_GRAPHIC_DEFAULTMENU ) ); ::sd::GraphicDocShell::Factory().RegisterAccel( SdResId( RID_GRAPHIC_DEFAULTACCEL ) ); } // register your view-factories here RegisterFactorys(); // register your shell-interfaces here RegisterInterfaces(); // register your controllers here RegisterControllers(); // SvDraw-Felder registrieren SdrRegisterFieldClasses(); // 3D-Objekt-Factory eintragen E3dObjFactory(); // ::com::sun::star::form::component::Form-Objekt-Factory eintragen FmFormObjFactory(); // factory for dummy import of old si-controls in 3.1 documents //BFS02 SiImportFactory(); // Objekt-Factory eintragen SdrObjFactory::InsertMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData)); } /************************************************************************* |* |* Exit |* \************************************************************************/ void SdDLL::Exit() { // called directly befor unloading the DLL // do whatever you want, Sd-DLL is accessible // Objekt-Factory austragen SdrObjFactory::RemoveMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData)); // the SdModule must be destroyed SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW); delete (*ppShlPtr); (*ppShlPtr) = NULL; } /* ULONG SdDLL::DetectFilter(SfxMedium& rMedium, const SfxFilter** ppFilter, SfxFilterFlags nMust, SfxFilterFlags nDont) { ULONG nReturn = ERRCODE_ABORT; // Erkennung fehlgeschlagen, Filter ungueltig BOOL bStorage = FALSE; if( *ppFilter && (*ppFilter)->GetFilterFlags() & SFX_FILTER_PACKED ) { uno::Reference< lang::XMultiServiceFactory > xSMgr( ::comphelper::getProcessServiceFactory() ); uno::Reference< util::XArchiver > xPacker( xSMgr->createInstance( OUString::createFromAscii( "com.sun.star.util.Archiver" ) ), uno::UNO_QUERY ); if( xPacker.is() ) { // extract extra data OUString aPath( rMedium.GetOrigURL() ); OUString aExtraData( xPacker->getExtraData( aPath ) ); const OUString aSig1= OUString::createFromAscii( "private:" ); String aTmp; aTmp += sal_Unicode( '?' ); aTmp += String::CreateFromAscii("simpress"); const OUString aSig2( aTmp ); INT32 nIndex1 = aExtraData.indexOf( aSig1 ); INT32 nIndex2 = aExtraData.indexOf( aSig2 ); if( nIndex1 == 0 && nIndex2 != -1 ) return ERRCODE_NONE; } } else if (rMedium.GetError() == SVSTREAM_OK) { if ( rMedium.IsStorage() ) { bStorage = TRUE; SotStorageRef xStorage = rMedium.GetStorage(); if ( !xStorage.Is() ) return ULONG_MAX; if( SvtModuleOptions().IsImpress() ) { // Erkennung ueber contained streams (PowerPoint 97-Filter) String aStreamName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "PowerPoint Document" ) ); if ( xStorage->IsContained( aStreamName ) && xStorage->IsStream( aStreamName ) ) { String aFileName(rMedium.GetName()); aFileName.ToUpperAscii(); if( aFileName.SearchAscii( ".POT" ) == STRING_NOTFOUND ) *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97); else *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97Template ); return ERRCODE_NONE; } } const SfxFilter* pFilter = *ppFilter; if ( *ppFilter ) { if ( (*ppFilter)->GetFormat() == xStorage->GetFormat() ) pFilter = *ppFilter; } if( !pFilter && SvtModuleOptions().IsImpress() ) { SfxFilterMatcher aMatcher( String::CreateFromAscii("simpress") ); pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() ); if ( pFilter ) *ppFilter = pFilter; } if( !pFilter && SvtModuleOptions().IsDraw() ) { SfxFilterMatcher aMatcher( String::CreateFromAscii("sdraw") ); pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() ); if ( pFilter ) *ppFilter = pFilter; } if ( pFilter && ( pFilter->GetFilterFlags() & nMust ) == nMust && ( pFilter->GetFilterFlags() & nDont ) == 0 ) { *ppFilter = pFilter; nReturn = ERRCODE_NONE; } else { *ppFilter = NULL; nReturn = ERRCODE_NONE; } } String aFileName( rMedium.GetName() ); aFileName.ToUpperAscii(); if ( nReturn == ERRCODE_ABORT ) { if( bStorage ) // aber keine Clipboard-Id #55337# { *ppFilter = NULL; } else { // Vektorgraphik? SvStream* pStm = rMedium.GetInStream(); if( !pStm ) nReturn = ERRCODE_IO_GENERAL; else { pStm->Seek( STREAM_SEEK_TO_BEGIN ); const String aFileName( rMedium.GetURLObject().GetMainURL( INetURLObject::NO_DECODE ) ); GraphicDescriptor aDesc( *pStm, &aFileName ); GraphicFilter* pGrfFilter = GetGrfFilter(); if( !aDesc.Detect( FALSE ) ) { if( SvtModuleOptions().IsImpress() ) { *ppFilter = NULL; nReturn = ERRCODE_ABORT; INetURLObject aURL( aFileName ); if( aURL.getExtension().equalsIgnoreAsciiCaseAscii( "cgm" ) ) { sal_uInt8 n8; pStm->Seek( STREAM_SEEK_TO_BEGIN ); *pStm >> n8; if ( ( n8 & 0xf0 ) == 0 ) // we are supporting binary cgm format only, so { // this is a small test to exclude cgm text const String aName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "CGM - Computer Graphics Metafile" ) ); SfxFilterMatcher aMatch( String::CreateFromAscii("simpress") ); *ppFilter = aMatch.GetFilter4FilterName( aName ); nReturn = ERRCODE_NONE; } } } } else { if( SvtModuleOptions().IsDraw() ) { String aShortName( aDesc.GetImportFormatShortName( aDesc.GetFileFormat() ) ); const String aName( pGrfFilter->GetImportFormatTypeName( pGrfFilter->GetImportFormatNumberForShortName( aShortName ) ) ); if ( *ppFilter && aShortName.EqualsIgnoreCaseAscii( "PCD" ) ) // there is a multiple pcd selection possible { sal_Int32 nBase = 2; // default Base0 String aFilterTypeName( (*ppFilter)->GetRealTypeName() ); if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base4" ) == COMPARE_EQUAL ) nBase = 1; else if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base16" ) == COMPARE_EQUAL ) nBase = 0; String aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Graphic/Import/PCD" ) ); FilterConfigItem aFilterConfigItem( aFilterConfigPath ); aFilterConfigItem.WriteInt32( String( RTL_CONSTASCII_USTRINGPARAM( "Resolution" ) ), nBase ); } SfxFilterMatcher aMatch( String::CreateFromAscii("draw") ); *ppFilter = aMatch.GetFilter4FilterName( aName ); nReturn = ERRCODE_NONE; } else { nReturn = ERRCODE_ABORT; *ppFilter = NULL; } } } } } } else { nReturn = rMedium.GetError(); } return nReturn; } */ <|endoftext|>
<commit_before>/* main.cpp * landmarkswing main file - use landmark detection to detect changes in swinging direction, and move accordingly */ #include "createmodule.h" #include <iostream> #include <iomanip> #include <cstdlib> #include <unistd.h> #include <getopt.h> #include <boost/shared_ptr.hpp> #include <qi/os.hpp> #include <qi/path.hpp> #include <qi/log.hpp> #include <alcommon/almodule.h> #include <alcommon/alproxy.h> #include <alcommon/albroker.h> #include <alcommon/albrokermanager.h> #include <alproxies/almotionproxy.h> #include <alproxies/alrobotpostureproxy.h> int vectorOrder (std::vector<float> vec); // Wrong number of arguments void argErr(void) { // Standard usage message std::string usage = "Usage: landmarkswing [--pip robot_ip] [--pport port]"; std::cerr << usage << std::endl; exit(2); } int main(int argc, char* argv[]) { // Whether to print verbose output - default off bool verb = false; // Whether to manually load Libraries - default off bool init = false; // Libraries to load std::string cameraLibName = "cameratools"; std::string movementLibName = "movementtools"; // Name of camera module in library std::string cameraModuleName = "CameraTools"; std::string movementModuleName = "MovementTools"; // Set broker name, ip and port, finding first available port from 54000 const std::string brokerName = "LandmarkSwingBroker"; int brokerPort = qi::os::findAvailablePort(54000); const std::string brokerIp = "0.0.0.0"; // Default parent port and ip int pport = 9559; std::string pip = "127.0.0.1"; // Default time to run in seconds int timeToRun = 10; // Default number of previous widths to smooth over unsigned int landmarkSmoothing = 2; // Get any arguments while (true) { static int index = 0; // Struct of options // Columns are: // {Option name, Option required?, flag(not needed here), return value/character} static const struct option longopts[] = { {"pip", 1, 0, 'i'}, {"pport", 1, 0, 'p'}, {"smooth", 1, 0, 's'}, {"time", 0, 0, 't'}, {"verb", 0, 0, 'v'}, {"help", 0, 0, 'h'}, {0, 0, 0, 0 } }; // Get next option, and check return value switch(index = getopt_long(argc, argv, "i:p:t:s:vh", longopts, &index)) { // Print usage and quit case 'h': argErr(); break; // Set parent IP case 'i': if (optarg) pip = std::string(optarg); else argErr(); break; // Set parent port case 'p': if (optarg) pport = atoi(optarg); else argErr(); break; // Set smoothing case 's': if (optarg) landmarkSmoothing = atoi(optarg); else argErr(); break; // Set time to run case 't': if (optarg) timeToRun = atoi(optarg); else argErr(); break; // Set verbose output case 'v': verb = true; break; } if (index == -1) break; } // Need this for SOAP serialisation of floats to work setlocale(LC_NUMERIC, "C"); // Create a broker if(verb) std::cout << "Creating broker..." << std::endl; boost::shared_ptr<AL::ALBroker> broker; try { broker = AL::ALBroker::createBroker( brokerName, brokerIp, brokerPort, pip, pport, 0); } // Throw error and quit if a broker could not be created catch(...) { std::cerr << "Failed to connect broker to: " << pip << ":" << pport << std::endl; AL::ALBrokerManager::getInstance()->killAllBroker(); AL::ALBrokerManager::kill(); return 1; } // Add the broker to NAOqi AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock()); AL::ALBrokerManager::getInstance()->addBroker(broker); // Create an instance of the desired module // if (libPath == "") // CreateModule(cameraLibName, cameraModuleName, broker, verb, true); // else CreateModule(cameraLibName, cameraModuleName, broker, verb, true); CreateModule(movementLibName, movementModuleName, broker, verb, true); // Create a proxy to the module if(verb) std::cout << "Creating proxy to " << cameraModuleName << "..." << std::endl; AL::ALProxy camToolsProxy(cameraModuleName, pip, pport); if(verb) std::cout << "Creating proxy to " << movementModuleName << "..." << std::endl; AL::ALProxy moveToolsProxy(movementModuleName, pip, pport); // List of detected landmark info AL::ALValue landmarks; // Vectors of last landmark widths std::vector<float> landmark1Angles; std::vector<float> landmark2Angles; // IDs of desired landmarks const int landmark1ID = 108; const int landmark2ID = 68; // Whether each landmark has been detected this cycle bool landmark1Detected = false; bool landmark2Detected = false; // Current direction of movement, either +1 or -1 int currentDirection; // Start landmark detection camToolsProxy.callVoid("startLandmarkDetection"); // Get start time of simulation and store it qi::os::timeval startTime; qi::os::timeval currentTime; qi::os::gettimeofday(&startTime); qi::os::gettimeofday(&currentTime); // Run for time "timeToRun" while (currentTime.tv_sec - startTime.tv_sec < timeToRun) { // Reset landmark detection flags landmark1Detected = false; landmark2Detected = false; // Read memory for landmarks landmarks = camToolsProxy.genericCall("getLandmark", 0); //std::cout << std::endl << "*****" << std::endl << std::endl; // Check for landmark detection if (landmarks.isValid() && landmarks.isArray() && landmarks.getSize() >= 2) { // Get widths of desired landmarks, and store them in appropriate vectors for (unsigned int i = 0; i < landmarks[1].getSize(); i++) { // Relevant parameters in landmark vector int ID = landmarks [1][i][1][0]; float angleX = landmarks [1][i][0][1]; float angleY = landmarks [1][i][0][2]; float width = landmarks [1][i][0][3]; float height = landmarks [1][i][0][4]; switch (ID) { case landmark1ID: landmark1Detected = true; landmark1Angles.push_back(angleY); if (landmark1Angles.size() > landmarkSmoothing + 1) { landmark1Angles.erase(landmark1Angles.begin()); } break; case landmark2ID: landmark2Detected = true; landmark2Angles.push_back(angleY); if (landmark2Angles.size() > landmarkSmoothing + 1) { landmark2Angles.erase(landmark2Angles.begin()); } break; default: std::cout << "Unkown landmark detected" << std::endl; } // std::cout << "Mark ID: " << ID << std::endl; // std::cout << "Width: " << width << std::endl; // std::cout << "Height: " << height << std::endl; } // Check whether a landmark was detected this interval if (landmark1Detected || landmark2Detected) { // The order of each vector (+1, 0, -1) int order1 = vectorOrder(landmark1Angles); int order2 = vectorOrder(landmark2Angles); // Both landmarks detected if (landmark1Detected && landmark2Detected) { // Both landmarks moving in same direction //if (order1 == order2) { if (order1 > 0) { std::cout << "Moving forwards" << std::endl; moveToolsProxy.callVoid("swingForwards"); } else if (order1 < 0) { std::cout << "Moving backwards" << std::endl; moveToolsProxy.callVoid("swingBackwards"); } } } // Only first landmark detected else if (landmark1Detected) { if (order1 > 0) { std::cout << "Moving forwards" << std::endl; moveToolsProxy.callVoid("swingForwards"); } else if (order1 < 0) { std::cout << "Moving backwards" << std::endl; moveToolsProxy.callVoid("swingBackwards"); } } // Only second landmark detected else { if (order2 > 0) { std::cout << "Moving forwards" << std::endl; moveToolsProxy.callVoid("swingForwards"); } else if (order2 < 0) { std::cout << "Moving backwards" << std::endl; moveToolsProxy.callVoid("swingBackwards"); } } } } else { // std::cout << "No landmark detected" << std::endl; } qi::os::msleep(100); qi::os::gettimeofday(&currentTime); } // Stop Landmark Detection camToolsProxy.callVoid("stopLandmarkDetection"); // Get a handle to the module and close it { boost::shared_ptr<AL::ALModuleCore> module = broker->getModuleByName(cameraModuleName); if(verb) std::cout << "Closing module " << cameraModuleName << "..." << std::endl; module->exit(); } // Check module has closed if(verb) { std::cout << "Module " << cameraModuleName << " is "; if (!(broker->isModulePresent(cameraModuleName))) { std::cout << "not "; } std::cout << "present" << std::endl; } // Close the broker if(verb) std::cout << "Closing broker..." << std::endl; broker->shutdown(); // Exit program if(verb) std::cout << "Exiting..." << std::endl; return 0; } // Order of vector - 1 = ascending, 0 = neither, -1 = descending // Non-zero order requires entire vector to follow that order // Default to 0 (no order) int vectorOrder (std::vector<float> vec) { int order = 0; if (vec.size() > 1) { if (vec[1] > vec[0]) order = 1; else if (vec[1] < vec[0]) order = -1; else order = 0; } for (unsigned int i = 2; i < vec.size(); i++) { if (vec[i] > vec[i-1] && order == 1) continue; else if (vec[i] < vec[i-1] && order == -1) continue; else return 0; } return order; } <commit_msg>Updated landmarkswing to work for any number of landmarks<commit_after>/* main.cpp * landmarkswing main file - use landmark detection to detect changes in swinging direction, and move accordingly */ #include "createmodule.h" #include <iostream> #include <iomanip> #include <cstdlib> #include <unistd.h> #include <getopt.h> #include <boost/shared_ptr.hpp> #include <qi/os.hpp> #include <qi/path.hpp> #include <qi/log.hpp> #include <alcommon/almodule.h> #include <alcommon/alproxy.h> #include <alcommon/albroker.h> #include <alcommon/albrokermanager.h> #include <alproxies/almotionproxy.h> #include <alproxies/alrobotpostureproxy.h> int vectorOrder (std::vector<float> vec); bool vectorAll (std::vector<bool> vec); bool vectorAny (std::vector<bool> vec); // Wrong number of arguments void argErr(void) { // Standard usage message std::string usage = "Usage: landmarkswing [--pip robot_ip] [--pport port]"; std::cerr << usage << std::endl; exit(2); } int main(int argc, char* argv[]) { // Whether to print verbose output - default off bool verb = false; // Whether to manually load Libraries - default off bool init = false; // Libraries to load std::string cameraLibName = "cameratools"; std::string movementLibName = "movementtools"; // Name of camera module in library std::string cameraModuleName = "CameraTools"; std::string movementModuleName = "MovementTools"; // Set broker name, ip and port, finding first available port from 54000 const std::string brokerName = "LandmarkSwingBroker"; int brokerPort = qi::os::findAvailablePort(54000); const std::string brokerIp = "0.0.0.0"; // Default parent port and ip int pport = 9559; std::string pip = "127.0.0.1"; // Default time to run in seconds int timeToRun = 10; // Default number of previous widths to smooth over unsigned int landmarkSmoothing = 2; // Get any arguments while (true) { static int index = 0; // Struct of options // Columns are: // {Option name, Option required?, flag(not needed here), return value/character} static const struct option longopts[] = { {"pip", 1, 0, 'i'}, {"pport", 1, 0, 'p'}, {"smooth", 1, 0, 's'}, {"time", 0, 0, 't'}, {"verb", 0, 0, 'v'}, {"help", 0, 0, 'h'}, {0, 0, 0, 0 } }; // Get next option, and check return value switch(index = getopt_long(argc, argv, "i:p:t:s:vh", longopts, &index)) { // Print usage and quit case 'h': argErr(); break; // Set parent IP case 'i': if (optarg) pip = std::string(optarg); else argErr(); break; // Set parent port case 'p': if (optarg) pport = atoi(optarg); else argErr(); break; // Set smoothing case 's': if (optarg) landmarkSmoothing = atoi(optarg); else argErr(); break; // Set time to run case 't': if (optarg) timeToRun = atoi(optarg); else argErr(); break; // Set verbose output case 'v': verb = true; break; } if (index == -1) break; } // Need this for SOAP serialisation of floats to work setlocale(LC_NUMERIC, "C"); // Create a broker if(verb) std::cout << "Creating broker..." << std::endl; boost::shared_ptr<AL::ALBroker> broker; try { broker = AL::ALBroker::createBroker( brokerName, brokerIp, brokerPort, pip, pport, 0); } // Throw error and quit if a broker could not be created catch(...) { std::cerr << "Failed to connect broker to: " << pip << ":" << pport << std::endl; AL::ALBrokerManager::getInstance()->killAllBroker(); AL::ALBrokerManager::kill(); return 1; } // Add the broker to NAOqi AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock()); AL::ALBrokerManager::getInstance()->addBroker(broker); // Create an instance of the desired module // if (libPath == "") // CreateModule(cameraLibName, cameraModuleName, broker, verb, true); // else CreateModule(cameraLibName, cameraModuleName, broker, verb, true); CreateModule(movementLibName, movementModuleName, broker, verb, true); // Create a proxy to the module if(verb) std::cout << "Creating proxy to " << cameraModuleName << "..." << std::endl; AL::ALProxy camToolsProxy(cameraModuleName, pip, pport); if(verb) std::cout << "Creating proxy to " << movementModuleName << "..." << std::endl; AL::ALProxy moveToolsProxy(movementModuleName, pip, pport); // List of detected landmark info AL::ALValue landmarks; // Vectors of last landmark widths std::vector<std::vector<float> > landmarkAngles; // IDs of desired landmarks std::vector<int> landmarkIDs; landmarkIDs.push_back(108); landmarkIDs.push_back(68); unsigned int nLandmarks = landmarkIDs.size(); // Whether each landmark has been detected this cycle std::vector<bool> landmarksDetected(nLandmarks, false); // Current direction of movement, either +1 or -1 int currentDirection; // Start landmark detection camToolsProxy.callVoid("startLandmarkDetection"); // Get start time of simulation and store it qi::os::timeval startTime; qi::os::timeval currentTime; qi::os::gettimeofday(&startTime); qi::os::gettimeofday(&currentTime); // Run for time "timeToRun" while (currentTime.tv_sec - startTime.tv_sec < timeToRun) { // Reset landmark detection flags for (unsigned int i = 0; i < nLandmarks; i++) { landmarksDetected(i) = false; } // Read memory for landmarks landmarks = camToolsProxy.genericCall("getLandmark", 0); // Check for landmark detection if (landmarks.isValid() && landmarks.isArray() && landmarks.getSize() >= 2) { // Get widths of desired landmarks, and store them in appropriate vectors for (unsigned int i = 0; i < landmarks[1].getSize(); i++) { // Relevant parameters in landmark vector int ID = landmarks [1][i][1][0]; // float angleX = landmarks [1][i][0][1]; float angleY = landmarks [1][i][0][2]; // float width = landmarks [1][i][0][3]; // float height = landmarks [1][i][0][4]; for (unsigned int j = 0; j < nLandmarks; j++) { if (ID = landmarkIDs[j]) { landmarksDetected[j] = true; landmarkAngles[j].push_back(angleY); if (landmarkAngles[j].size() > landmarkSmoothing + 1) { landmarkAngles[j].erase(landmarkAngles[j].begin()); } } } } // Check whether a landmark was detected this interval if (vectorAny(landmarksDetected)) { // The order of each vector (+1, 0, -1) std::vector<int> orders; for (unsigned int i = 0; i < nLandmarks; i++) { orders.push_back(vectorOrder(landmarkAngles[j])); } double sum; for (unsigned int i = 0; i < nLandmarks; i++) { sum += vec[i]; } return static_cast<int>(sum / static_cast<double>(vec.size())); if (order1 > 0) { std::cout << "Moving forwards" << std::endl; moveToolsProxy.callVoid("swingForwards"); } else if (order1 < 0) { std::cout << "Moving backwards" << std::endl; moveToolsProxy.callVoid("swingBackwards"); } } } else { // std::cout << "No landmark detected" << std::endl; } qi::os::msleep(50); qi::os::gettimeofday(&currentTime); } // Stop Landmark Detection camToolsProxy.callVoid("stopLandmarkDetection"); // Get a handle to the module and close it { boost::shared_ptr<AL::ALModuleCore> module = broker->getModuleByName(cameraModuleName); if(verb) std::cout << "Closing module " << cameraModuleName << "..." << std::endl; module->exit(); } // Check module has closed if(verb) { std::cout << "Module " << cameraModuleName << " is "; if (!(broker->isModulePresent(cameraModuleName))) { std::cout << "not "; } std::cout << "present" << std::endl; } // Close the broker if(verb) std::cout << "Closing broker..." << std::endl; broker->shutdown(); // Exit program if(verb) std::cout << "Exiting..." << std::endl; return 0; } // Order of vector - 1 = ascending, 0 = neither, -1 = descending // Non-zero order requires entire vector to follow that order // Default to 0 (no order) int vectorOrder (std::vector<float> vec) { int order = 0; if (vec.size() > 1) { if (vec[1] > vec[0]) order = 1; else if (vec[1] < vec[0]) order = -1; else order = 0; } for (unsigned int i = 2; i < vec.size(); i++) { if (vec[i] > vec[i-1] && order == 1) continue; else if (vec[i] < vec[i-1] && order == -1) continue; else return 0; } return order; } // Check if all bools in vector are true bool vectorAll (std::vector<bool> vec) { for (unsigned int i = 0; i < vec.size(); i++) { if (!vec[i]) return false; } return true; } // Check if any bools in vector are true bool vectorAny (std::vector<bool> vec) { for (unsigned int i = 0; i < vec.size(); i++) { if (vec[i]) return true; } return false; } int vectorAverage (std::vector<int> vec) { } <|endoftext|>
<commit_before><commit_msg>Make "Reset to Defaults" reset geolocation permissions too<commit_after><|endoftext|>
<commit_before><commit_msg>Attempt to make DownloadTest UI test less flaky.<commit_after><|endoftext|>
<commit_before>/** * @file basicdeb.cpp * @brief Basic debugger, can be replaced with setDebuggerHook() * */ #include "angort.h" #include "debtoks.h" #include "../lib/opcodes.h" #include <histedit.h> #include "completer.h" using namespace angort; bool debuggerBreakHack=false; // we have our own instance of editline static EditLine *el=NULL; static History *hist=NULL; Tokeniser tok; static const char *getprompt(){return "] ";} static const char *usage = "abort terminate program (remain in debugger)\n" "stack show the stack\n" "print <n> detailed view of stack entry <n>\n" "?Var detailed view of global <Var>\n" "disasm disassemble current function\n" "frame show context frame\n" "help show this string\n" ; namespace debugger { static void disasm(Angort *a){ const Instruction *ip = a->wordbase; const Instruction *base = a->wordbase; for(;;){ int opcode = ip->opcode; a->showop(ip++,base,a->ip); printf("\n"); if(opcode == OP_END)break; } } static void process(const char *line,Angort *a){ tok.reset(line); char buf[256]; int i; for(;;){ try{ switch(tok.getnext()){ case T_END:return; case T_HELP:puts(usage);break; case T_STACK: a->dumpStack("<debug>"); break; case T_PRINT: i=tok.getnextint(); if(i<0){ printf("expected +ve integer stack index\n"); } else { Value *v = a->stack.peekptr(i); v->dump(); } break; case T_DISASM: disasm(a); break; case T_QUESTION: if(tok.getnextident(buf)){ int idx = a->findOrCreateGlobal(buf); Value *v = a->names.getVal(idx); v->dump(); } else { printf("expected ident, not %s\n",tok.getstring()); } break; case T_ABORT: a->stop(); break; case T_FRAME: a->dumpFrame(); break; default: printf("Unknown command %s\n",tok.getstring()); } } catch(Exception e){ printf("Error: %s\n",e.what()); } } } // autocompletion data generator class DebuggerAutocomplete : public AutocompleteIterator { int idx; public: virtual void first(){ idx=0; } virtual const char *next(){ while(debtoks[idx].word && debtoks[idx].word[0]=='*') idx++; if(!debtoks[idx].word)return NULL; return debtoks[idx++].word; } }; } void basicDebugger(Angort *a){ tok.init(); tok.settokens(debtoks); tok.setname("<debugger>"); printf("Debugger: TAB-TAB for command list, ctrl-D to exit and continue.\n" "abort to terminate program (remaining in debugger, ?var to query\n" "global variable.\n\n"); HistEvent ev; if(!el){ // make our editline if we don't have one el = el_init("angort-debugger",stdin,stdout,stderr); el_set(el,EL_PROMPT,&getprompt); el_set(el,EL_EDITOR,"emacs"); hist = history_init(); history(hist,&ev,H_SETSIZE,800); el_set(el,EL_HIST,history,hist); if(!hist) printf("warning: no history\n"); static debugger::DebuggerAutocomplete completer; setupAutocomplete(el,&completer,"\t\n "); } for(;;){ int count; debuggerBreakHack=true; const char *line = el_gets(el,&count); if(!line)break; debuggerBreakHack=false; if(count>1){ // trailing newline if(hist) history(hist,&ev,H_ENTER,line); debugger::process(line,a); } } putchar('\r'); } <commit_msg>debugger uses reverse polish too; I was getting confused.<commit_after>/** * @file basicdeb.cpp * @brief Basic debugger, can be replaced with setDebuggerHook() * */ #include "angort.h" #include "debtoks.h" #include "../lib/opcodes.h" #include <histedit.h> #include "completer.h" using namespace angort; bool debuggerBreakHack=false; // we have our own instance of editline static EditLine *el=NULL; static History *hist=NULL; Tokeniser tok; static const char *getprompt(){return "] ";} static const char *usage = "abort terminate program (remain in debugger)\n" "stack show the stack\n" "<n> print detailed view of stack entry <n>\n" "?Var detailed view of global <Var>\n" "disasm disassemble current function\n" "frame show context frame\n" "help show this string\n" ; namespace debugger { static void disasm(Angort *a){ const Instruction *ip = a->wordbase; const Instruction *base = a->wordbase; for(;;){ int opcode = ip->opcode; a->showop(ip++,base,a->ip); printf("\n"); if(opcode == OP_END)break; } } static void process(const char *line,Angort *a){ tok.reset(line); char buf[256]; int i; Stack<int,8> stack; for(;;){ try{ switch(tok.getnext()){ case T_INT: stack.push(tok.getint()); break; case T_END:return; case T_HELP:puts(usage);break; case T_STACK: a->dumpStack("<debug>"); break; case T_PRINT: i=stack.pop(); if(i<0){ printf("expected +ve integer stack index\n"); } else { Value *v = a->stack.peekptr(i); printf("Type: %s\n",v->t->name); v->dump(); } break; case T_DISASM: disasm(a); break; case T_QUESTION: if(tok.getnextident(buf)){ int idx = a->findOrCreateGlobal(buf); Value *v = a->names.getVal(idx); v->dump(); } else { printf("expected ident, not %s\n",tok.getstring()); } break; case T_ABORT: a->stop(); break; case T_FRAME: a->dumpFrame(); break; default: printf("Unknown command %s\n",tok.getstring()); } } catch(Exception e){ printf("Error: %s\n",e.what()); } } } // autocompletion data generator class DebuggerAutocomplete : public AutocompleteIterator { int idx; public: virtual void first(){ idx=0; } virtual const char *next(){ while(debtoks[idx].word && debtoks[idx].word[0]=='*') idx++; if(!debtoks[idx].word)return NULL; return debtoks[idx++].word; } }; } void basicDebugger(Angort *a){ tok.init(); tok.settokens(debtoks); tok.setname("<debugger>"); printf("Debugger: TAB-TAB for command list, ctrl-D to exit and continue.\n" "abort to terminate program (remaining in debugger, ?var to query\n" "global variable.\n\n"); HistEvent ev; if(!el){ // make our editline if we don't have one el = el_init("angort-debugger",stdin,stdout,stderr); el_set(el,EL_PROMPT,&getprompt); el_set(el,EL_EDITOR,"emacs"); hist = history_init(); history(hist,&ev,H_SETSIZE,800); el_set(el,EL_HIST,history,hist); if(!hist) printf("warning: no history\n"); static debugger::DebuggerAutocomplete completer; setupAutocomplete(el,&completer,"\t\n "); } for(;;){ int count; debuggerBreakHack=true; const char *line = el_gets(el,&count); if(!line)break; debuggerBreakHack=false; if(count>1){ // trailing newline if(hist) history(hist,&ev,H_ENTER,line); debugger::process(line,a); } } putchar('\r'); } <|endoftext|>
<commit_before>/********************************************************************* * * Copyright 2011 Intel Corporation * 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, 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 <string.h> #include <iostream> #include "cli.hpp" #include "os_path.hpp" #include "trace_tools.hpp" static const char *synopsis = "Identify differences between two traces."; static void usage(void) { std::cout << "usage: apitrace diff <trace-1> <trace-2>\n" << synopsis << "\n" "\n" " Both input files should be the result of running 'apitrace trace'.\n"; } static int command(int argc, char *argv[]) { int i; for (i = 0; i < argc; ++i) { const char *arg = argv[i]; if (arg[0] != '-') { break; } if (!strcmp(arg, "--")) { i++; break; } else if (!strcmp(arg, "--help")) { usage(); return 0; } else { std::cerr << "error: unknown option " << arg << "\n"; usage(); return 1; } } if (argc - i != 2) { std::cerr << "Error: diff requires exactly two trace files as arguments.\n"; usage(); return 1; } char *file1, *file2; file1 = argv[i]; file2 = argv[i+1]; #define CLI_DIFF_TRACEDIFF_COMMAND "tracediff.sh" os::Path command = trace::findFile("scripts/" CLI_DIFF_TRACEDIFF_COMMAND, APITRACE_SCRIPTS_INSTALL_DIR "/" CLI_DIFF_TRACEDIFF_COMMAND, true); char* args[4]; args[0] = (char *) command.str(); args[1] = file1; args[2] = file2; args[3] = NULL; #ifdef _WIN32 std::cerr << "The 'apitrace diff' command is not yet supported on this O/S.\n"; #else execv(command.str(), args); #endif std::cerr << "Error: Failed to execute " << argv[0] << "\n"; return 1; } const Command diff_command = { "diff", synopsis, usage, command }; <commit_msg>cli: Pass apitrace path to tracediff.sh.<commit_after>/********************************************************************* * * Copyright 2011 Intel Corporation * 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, 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 <string.h> #include <iostream> #include "cli.hpp" #include "os_path.hpp" #include "trace_tools.hpp" static const char *synopsis = "Identify differences between two traces."; static void usage(void) { std::cout << "usage: apitrace diff <trace-1> <trace-2>\n" << synopsis << "\n" "\n" " Both input files should be the result of running 'apitrace trace'.\n"; } static int command(int argc, char *argv[]) { int i; for (i = 0; i < argc; ++i) { const char *arg = argv[i]; if (arg[0] != '-') { break; } if (!strcmp(arg, "--")) { i++; break; } else if (!strcmp(arg, "--help")) { usage(); return 0; } else { std::cerr << "error: unknown option " << arg << "\n"; usage(); return 1; } } if (argc - i != 2) { std::cerr << "Error: diff requires exactly two trace files as arguments.\n"; usage(); return 1; } char *file1, *file2; file1 = argv[i]; file2 = argv[i+1]; #define CLI_DIFF_TRACEDIFF_COMMAND "tracediff.sh" os::Path command = trace::findFile("scripts/" CLI_DIFF_TRACEDIFF_COMMAND, APITRACE_SCRIPTS_INSTALL_DIR "/" CLI_DIFF_TRACEDIFF_COMMAND, true); char* args[4]; args[0] = (char *) command.str(); args[1] = file1; args[2] = file2; args[3] = NULL; #ifdef _WIN32 std::cerr << "The 'apitrace diff' command is not yet supported on this O/S.\n"; #else os::Path apitrace = os::getProcessName(); setenv("APITRACE", apitrace.str(), 1); execv(command.str(), args); #endif std::cerr << "Error: Failed to execute " << argv[0] << "\n"; return 1; } const Command diff_command = { "diff", synopsis, usage, command }; <|endoftext|>
<commit_before>#include "OnionEncryptor.hpp" namespace Dissent { namespace Crypto { void Print(const QVector<QByteArray> &datas); OnionEncryptor &OnionEncryptor::GetInstance() { static OnionEncryptor onion_encryptor; return onion_encryptor; } int OnionEncryptor::Encrypt(const QVector<AsymmetricKey *> &keys, const QByteArray &cleartext, QByteArray &ciphertext, QVector<QByteArray> *intermediate) { ciphertext = keys.first()->Encrypt(cleartext); if(ciphertext.isEmpty()) { return 0; } if(intermediate) { intermediate->append(ciphertext); } if(keys.count() == 1) { return -1; } for(int idx = 1; idx < keys.count() - 1; idx++) { ciphertext = keys[idx]->Encrypt(ciphertext); if(ciphertext.isEmpty()) { return idx; } if(intermediate) { intermediate->append(ciphertext); } } ciphertext = keys.last()->Encrypt(ciphertext); if(ciphertext.isEmpty()) { return keys.count() - 1; } return -1; } bool OnionEncryptor::Decrypt(AsymmetricKey *key, const QVector<QByteArray> &ciphertext, QVector<QByteArray> &cleartext, QVector<int> *bad) { cleartext.clear(); bool res = true; for(int idx = 0; idx < ciphertext.count(); idx++) { QByteArray data = key->Decrypt(ciphertext[idx]); if(data.isEmpty()) { res = false; if(bad) { bad->append(idx); } } cleartext.append(data); } return res; } void OnionEncryptor::RandomizeBlocks(QVector<QByteArray> &text) { CppRandom rand; for(int idx = 0; idx < text.count(); idx++) { int jdx = rand.GetInt(0, text.count()); if(jdx == idx) { continue; } QByteArray tmp = text[idx]; text[idx] = text[jdx]; text[jdx] = tmp; } } bool OnionEncryptor::VerifyOne(AsymmetricKey *key, const QVector<QByteArray> &cleartext, const QVector<QByteArray> &ciphertext) const { foreach(QByteArray cph, ciphertext) { QByteArray clr = key->Decrypt(cph); if(!cleartext.contains(clr)) { return false; } } return true; } bool OnionEncryptor::VerifyAll(const QVector<AsymmetricKey *> &keys, const QVector<QVector<QByteArray> > &onion, QBitArray &bad) { if(keys.count() != onion.count() - 1) { qWarning() << "Incorrect key to onion layers ratio: " << keys.count() << ":" << onion.count(); return false; } if(keys.count() != bad.count()) { bad = QBitArray(keys.count(), false); } bool res = true; for(int idx = 0; idx < keys.count(); idx++) { if(!VerifyOne(keys[idx], onion[idx], onion[idx + 1])) { bad[idx] = true; res = false; } } return res; } int OnionEncryptor::ReorderRandomBits( const QVector<QVector<QByteArray> > &in_bits, QVector<QVector<QByteArray> > &out_bits) { if(in_bits.isEmpty()) { qWarning() << "There should be at least one vector in in_bits"; return -2; } int keys = in_bits.count(); int msgs = in_bits[0].count(); for(int idx = 0; idx < keys; idx++) { if(in_bits[idx].count() != msgs) { qWarning() << "Not all in_bit vectors are of the same length"; return idx; } } for(int idx = 0; idx < msgs; idx++) { out_bits.append(QVector<QByteArray>(keys)); for(int jdx = 0; jdx < keys; jdx++) { out_bits[idx][jdx] = in_bits[jdx][idx]; } } return -1; } } } <commit_msg>[Crypto] Removed old debugging code<commit_after>#include "OnionEncryptor.hpp" namespace Dissent { namespace Crypto { OnionEncryptor &OnionEncryptor::GetInstance() { static OnionEncryptor onion_encryptor; return onion_encryptor; } int OnionEncryptor::Encrypt(const QVector<AsymmetricKey *> &keys, const QByteArray &cleartext, QByteArray &ciphertext, QVector<QByteArray> *intermediate) { ciphertext = keys.first()->Encrypt(cleartext); if(ciphertext.isEmpty()) { return 0; } if(intermediate) { intermediate->append(ciphertext); } if(keys.count() == 1) { return -1; } for(int idx = 1; idx < keys.count() - 1; idx++) { ciphertext = keys[idx]->Encrypt(ciphertext); if(ciphertext.isEmpty()) { return idx; } if(intermediate) { intermediate->append(ciphertext); } } ciphertext = keys.last()->Encrypt(ciphertext); if(ciphertext.isEmpty()) { return keys.count() - 1; } return -1; } bool OnionEncryptor::Decrypt(AsymmetricKey *key, const QVector<QByteArray> &ciphertext, QVector<QByteArray> &cleartext, QVector<int> *bad) { cleartext.clear(); bool res = true; for(int idx = 0; idx < ciphertext.count(); idx++) { QByteArray data = key->Decrypt(ciphertext[idx]); if(data.isEmpty()) { res = false; if(bad) { bad->append(idx); } } cleartext.append(data); } return res; } void OnionEncryptor::RandomizeBlocks(QVector<QByteArray> &text) { CppRandom rand; for(int idx = 0; idx < text.count(); idx++) { int jdx = rand.GetInt(0, text.count()); if(jdx == idx) { continue; } QByteArray tmp = text[idx]; text[idx] = text[jdx]; text[jdx] = tmp; } } bool OnionEncryptor::VerifyOne(AsymmetricKey *key, const QVector<QByteArray> &cleartext, const QVector<QByteArray> &ciphertext) const { foreach(QByteArray cph, ciphertext) { QByteArray clr = key->Decrypt(cph); if(!cleartext.contains(clr)) { return false; } } return true; } bool OnionEncryptor::VerifyAll(const QVector<AsymmetricKey *> &keys, const QVector<QVector<QByteArray> > &onion, QBitArray &bad) { if(keys.count() != onion.count() - 1) { qWarning() << "Incorrect key to onion layers ratio: " << keys.count() << ":" << onion.count(); return false; } if(keys.count() != bad.count()) { bad = QBitArray(keys.count(), false); } bool res = true; for(int idx = 0; idx < keys.count(); idx++) { if(!VerifyOne(keys[idx], onion[idx], onion[idx + 1])) { bad[idx] = true; res = false; } } return res; } int OnionEncryptor::ReorderRandomBits( const QVector<QVector<QByteArray> > &in_bits, QVector<QVector<QByteArray> > &out_bits) { if(in_bits.isEmpty()) { qWarning() << "There should be at least one vector in in_bits"; return -2; } int keys = in_bits.count(); int msgs = in_bits[0].count(); for(int idx = 0; idx < keys; idx++) { if(in_bits[idx].count() != msgs) { qWarning() << "Not all in_bit vectors are of the same length"; return idx; } } for(int idx = 0; idx < msgs; idx++) { out_bits.append(QVector<QByteArray>(keys)); for(int jdx = 0; jdx < keys; jdx++) { out_bits[idx][jdx] = in_bits[jdx][idx]; } } return -1; } } } <|endoftext|>
<commit_before>#include "EpsilonDashboard.h" #include <QApplication> #include <QLockFile> #include <QDebug> #include <QDir> int main(int argc, char* argv[]) { QString tmpDir = QDir::tempPath(); QLockFile lockFile(tmpDir + "/epsilonDashboard.lock"); /* Trying to close the Lock File, if the attempt is unsuccessful for 100 milliseconds, * then there is a Lock File already created by another process. * Therefore, we issue a warning and close the program */ if (!lockFile.tryLock(100)) { qDebug() << "An instance of dashboard already exists." << endl << "Quitting..." << endl; return 1; } else { qDebug() << "No other instance of dashboard exists." << endl"Launching dashboard..." << endl; } QScopedPointer<EpsilonDashboard> app; app.reset(new EpsilonDashboard(argc, argv)); return app->exec(); } <commit_msg>Added qdebugs<commit_after>#include "EpsilonDashboard.h" #include <QApplication> #include <QLockFile> #include <QDebug> #include <QDir> int main(int argc, char* argv[]) { QString tmpDir = QDir::tempPath(); QLockFile lockFile(tmpDir + "/epsilonDashboard.lock"); /* Trying to close the Lock File, if the attempt is unsuccessful for 100 milliseconds, * then there is a Lock File already created by another process. * Therefore, we issue a warning and close the program */ if (!lockFile.tryLock(100)) { qDebug() << "An instance of dashboard already exists." << endl; qDebug() << "Quitting..." << endl; return 1; } else { qDebug() << "No other instance of dashboard exists." << endl; qDebug() << "Launching dashboard..." << endl; } QScopedPointer<EpsilonDashboard> app; app.reset(new EpsilonDashboard(argc, argv)); return app->exec(); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <boost/regex.hpp> #include "Types.hpp" #include "Sequence.hpp" #include "Graph.hpp" #include "Path.hpp" #include "FitnessFunction.hpp" #include "GreedyPathFinder.hpp" #include "MeanOverlap.hpp" using namespace std; using namespace FireflyAssembler; VectorPointer<Sequence> deserializeSequences(string fileName) { boost::regex beginningOfSequence("^>.*"); VectorPointer<Sequence> sequences(new vector<Sequence>()); // Open file and create RecordReader. ifstream in(fileName.c_str()); if (!in.is_open()) { cerr << "Problem occurred in opening file." << endl; } // Read file record-wise. string line; while (!in.eof()) { getline(in,line); if (boost::regex_match(line, beginningOfSequence)) { sequences->push_back(Sequence()); } else { vector<Sequence>::iterator s = sequences->end() - 1; s->append(line); } } in.close(); } void usage() { cout << "Usage: FireflyAssembler <filename>" << endl << " This prints the contigs found in <filename> to standard out." << endl; }; int main(int argc, char * argv[]) { // TODO: Use Boost.program_options here later // Add greedy-or-firefly assembler options // Add fitness function options // Add distance metric options if (argc != 1) { usage(); } string filename(argv[1]); VectorPointer<Sequence> sequences(deserializeSequences(filename)); Graph graph; // load graph for (int i = 0; i < sequences->size(); i++) { graph.addSequence((*sequences)[i]); } PathFinderPointer pathFinder(new GreedyPathFinder()); FitnessFunctionPointer ff(new MeanOverlap()); VectorPointer<Sequence> contigs = pathFinder->findPath(graph, ff)->getContigs(); for (int j = 0; j < contigs->size(); j++) { cout << (*contigs)[j] << endl; } return 0; } <commit_msg>Move regex out of boost<commit_after>#include <iostream> #include <fstream> #include <regex> #include "Types.hpp" #include "Sequence.hpp" #include "Graph.hpp" #include "Path.hpp" #include "FitnessFunction.hpp" #include "GreedyPathFinder.hpp" #include "MeanOverlap.hpp" using namespace std; using namespace FireflyAssembler; VectorPointer<Sequence> deserializeSequences(string fileName) { regex beginningOfSequence("^>.*"); VectorPointer<Sequence> sequences(new vector<Sequence>()); // Open file and create RecordReader. ifstream in(fileName.c_str()); if (!in.is_open()) { cerr << "Problem occurred in opening file." << endl; } // Read file record-wise. string line; while (!in.eof()) { getline(in,line); if (regex_match(line, beginningOfSequence)) { sequences->push_back(Sequence()); } else { vector<Sequence>::iterator s = sequences->end() - 1; s->append(line); } } in.close(); } void usage() { cout << "Usage: FireflyAssembler <filename>" << endl << " This prints the contigs found in <filename> to standard out." << endl; }; int main(int argc, char * argv[]) { // TODO: Use Boost.program_options here later // Add greedy-or-firefly assembler options // Add fitness function options // Add distance metric options if (argc != 1) { usage(); } string filename(argv[1]); VectorPointer<Sequence> sequences(deserializeSequences(filename)); Graph graph; // load graph for (int i = 0; i < sequences->size(); i++) { graph.addSequence((*sequences)[i]); } PathFinderPointer pathFinder(new GreedyPathFinder()); FitnessFunctionPointer ff(new MeanOverlap()); VectorPointer<Sequence> contigs = pathFinder->findPath(graph, ff)->getContigs(); for (int j = 0; j < contigs->size(); j++) { cout << (*contigs)[j] << endl; } return 0; } <|endoftext|>
<commit_before>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #include <iostream> #include "core/ast.h" #include "core/codegen.h" #include "core/scope.h" #include "core/compiler.h" namespace clever { namespace ast { void Codegen::init() { } void Codegen::visit(IntLit* node) { node->setConstId(m_compiler->addConstant(new Value(node->getValue()))); } void Codegen::visit(DoubleLit* node) { node->setConstId(m_compiler->addConstant(new Value(node->getValue()))); } void Codegen::visit(StringLit* node) { node->setConstId(m_compiler->addConstant(new Value(node->getValue()))); } void Codegen::visit(Ident* node) { Symbol* sym = m_scope->getAny(node->getName()); if (!sym) { Compiler::errorf(node->getLocation(), "Variable `%S' not found!", node->getName()); } node->setValueId(sym->value_id); node->setScope(sym->scope); } void Codegen::visit(Block* node) { m_scope = node->getScope(); Visitor::visit(static_cast<NodeArray*>(node)); m_scope = m_scope->getParent(); } void Codegen::visit(VariableDecl* node) { node->getAssignment()->accept(*this); } void Codegen::visit(Assignment* node) { // TODO: allow assignment of any possible left hand side. Symbol* sym = static_cast<Ident*>(node->getLhs())->getSymbol(); Node* rhs = node->getRhs(); clever_assert_not_null(sym); if (node->isConditional()) { m_ir.push_back(IR(OP_JMPNZ, Operand(FETCH_VAR, sym->value_id, sym->scope->getId()), Operand(JMP_ADDR, m_ir.size() + 2))); } if (rhs) { rhs->accept(*this); } m_ir.push_back(IR(OP_ASSIGN, Operand(FETCH_VAR, sym->value_id, sym->scope->getId()))); if (!rhs) { m_ir.back().op2 = Operand(FETCH_TMP, m_compiler->getTempValue()); } else { if (rhs->isLiteral()) { m_ir.back().op2 = Operand(FETCH_CONST, static_cast<Literal*>(rhs)->getConstId()); } else if (rhs->getScope()) { m_ir.back().op2 = Operand(FETCH_VAR, rhs->getValueId()); } else { m_ir.back().op2 = Operand(FETCH_TMP, rhs->getValueId(), rhs->getScope()->getId()); } } } void Codegen::visit(FunctionCall* node) { // TODO: allow call for any possible callee Symbol* sym = static_cast<Ident*>(node->getCallee())->getSymbol(); clever_assert_not_null(sym); if (node->hasArgs()) { NodeList& args = node->getArgs()->getNodes(); NodeList::const_iterator it = args.begin(), end = args.end(); while (it != end) { Operand operand; (*it)->accept(*this); if ((*it)->isLiteral()) { operand.op_type = FETCH_CONST; operand.value_id = static_cast<Literal*>(*it)->getConstId(); } else { operand.op_type = (*it)->isEvaluable() ? FETCH_TMP : FETCH_VAR; operand.value_id = (*it)->getValueId(); if ((*it)->getScope()) { operand.scope_id = (*it)->getScope()->getId(); } } m_ir.push_back(IR(OP_SEND_VAL, operand)); ++it; } } m_ir.push_back(IR(OP_FCALL, Operand(FETCH_VAR, sym->value_id, sym->scope->getId()))); } void Codegen::visit(FunctionDecl* node) { size_t start_func = m_ir.size(); m_ir.push_back(IR(OP_JMP, Operand(JMP_ADDR, 0))); m_scope = node->getScope(); if (node->hasArgs()) { node->getArgs()->accept(*this); } node->getBlock()->accept(*this); m_scope = m_scope->getParent(); m_ir.push_back(IR(OP_LEAVE)); Symbol* sym = node->getIdent()->getSymbol(); Function* func = static_cast<Function*>(sym->scope->getValue(sym->value_id)->getObj()); func->setAddr(m_ir.size()+1); m_ir[start_func].op1.value_id = m_ir.size(); } void Codegen::visit(Return* node) { // TODO: return value m_ir.push_back(IR(OP_RET)); } void Codegen::visit(While* node) { size_t start_while = m_ir.size(); Node* cond = node->getCondition(); cond->accept(*this); if (cond->isLiteral()) { m_ir.push_back(IR(OP_JMPZ, Operand(FETCH_CONST, static_cast<Literal*>(cond)->getConstId()))); } else if (cond->getScope()) { m_ir.push_back(IR(OP_JMPZ, Operand(FETCH_VAR, cond->getValueId(), cond->getScope()->getId()))); } else { m_ir.push_back(IR(OP_JMPZ, Operand(FETCH_TMP, cond->getValueId()))); } node->getBlock()->accept(*this); m_ir.push_back(IR(OP_JMP, Operand(JMP_ADDR, start_while))); m_ir[start_while].op2.value_id = m_ir.size(); } void Codegen::visit(IncDec* node) { Opcode op; node->getVar()->accept(*this); switch (node->getOperator()) { case IncDec::PRE_INC: op = OP_PRE_INC; break; case IncDec::PRE_DEC: op = OP_PRE_DEC; break; case IncDec::POS_INC: op = OP_POS_INC; break; case IncDec::POS_DEC: op = OP_POS_DEC; break; } m_ir.push_back(IR(op, Operand(FETCH_VAR, node->getVar()->getValueId(), node->getVar()->getScope()->getId()))); size_t tmp_id = m_compiler->getTempValue(); m_ir.back().result = Operand(FETCH_TMP, tmp_id); node->setValueId(tmp_id); } void Codegen::visit(Arithmetic* node) { Node* lhs = node->getLhs(); Node* rhs = node->getRhs(); Opcode op; switch (node->getOperator()) { case Arithmetic::MOP_ADD: op = OP_ADD; break; case Arithmetic::MOP_SUB: op = OP_SUB; break; case Arithmetic::MOP_MUL: op = OP_MUL; break; case Arithmetic::MOP_DIV: op = OP_DIV; break; case Arithmetic::MOP_MOD: op = OP_MOD; break; } lhs->accept(*this); rhs->accept(*this); m_ir.push_back(IR(op)); if (lhs->isLiteral()) { m_ir.back().op1 = Operand(FETCH_CONST, static_cast<Literal*>(lhs)->getConstId()); } else { m_ir.back().op1 = Operand( lhs->isEvaluable() ? FETCH_TMP : FETCH_VAR, lhs->getValueId(), lhs->getScope()->getId()); } if (rhs->isLiteral()) { m_ir.back().op2 = Operand(FETCH_CONST, static_cast<Literal*>(rhs)->getConstId()); } else if (rhs->getScope()) { m_ir.back().op2 = Operand(FETCH_VAR, rhs->getValueId(), rhs->getScope()->getId()); } else { m_ir.back().op2 = Operand(FETCH_TMP, rhs->getValueId()); } size_t tmp_id = m_compiler->getTempValue(); m_ir.back().result = Operand(FETCH_TMP, tmp_id); node->setValueId(tmp_id); } }} // clever::ast <commit_msg>- Fixed function addr<commit_after>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #include <iostream> #include "core/ast.h" #include "core/codegen.h" #include "core/scope.h" #include "core/compiler.h" namespace clever { namespace ast { void Codegen::init() { } void Codegen::visit(IntLit* node) { node->setConstId(m_compiler->addConstant(new Value(node->getValue()))); } void Codegen::visit(DoubleLit* node) { node->setConstId(m_compiler->addConstant(new Value(node->getValue()))); } void Codegen::visit(StringLit* node) { node->setConstId(m_compiler->addConstant(new Value(node->getValue()))); } void Codegen::visit(Ident* node) { Symbol* sym = m_scope->getAny(node->getName()); if (!sym) { Compiler::errorf(node->getLocation(), "Variable `%S' not found!", node->getName()); } node->setValueId(sym->value_id); node->setScope(sym->scope); } void Codegen::visit(Block* node) { m_scope = node->getScope(); Visitor::visit(static_cast<NodeArray*>(node)); m_scope = m_scope->getParent(); } void Codegen::visit(VariableDecl* node) { node->getAssignment()->accept(*this); } void Codegen::visit(Assignment* node) { // TODO: allow assignment of any possible left hand side. Symbol* sym = static_cast<Ident*>(node->getLhs())->getSymbol(); Node* rhs = node->getRhs(); clever_assert_not_null(sym); if (node->isConditional()) { m_ir.push_back(IR(OP_JMPNZ, Operand(FETCH_VAR, sym->value_id, sym->scope->getId()), Operand(JMP_ADDR, m_ir.size() + 2))); } if (rhs) { rhs->accept(*this); } m_ir.push_back(IR(OP_ASSIGN, Operand(FETCH_VAR, sym->value_id, sym->scope->getId()))); if (!rhs) { m_ir.back().op2 = Operand(FETCH_TMP, m_compiler->getTempValue()); } else { if (rhs->isLiteral()) { m_ir.back().op2 = Operand(FETCH_CONST, static_cast<Literal*>(rhs)->getConstId()); } else if (rhs->getScope()) { m_ir.back().op2 = Operand(FETCH_VAR, rhs->getValueId()); } else { m_ir.back().op2 = Operand(FETCH_TMP, rhs->getValueId(), rhs->getScope()->getId()); } } } void Codegen::visit(FunctionCall* node) { // TODO: allow call for any possible callee Symbol* sym = static_cast<Ident*>(node->getCallee())->getSymbol(); clever_assert_not_null(sym); if (node->hasArgs()) { NodeList& args = node->getArgs()->getNodes(); NodeList::const_iterator it = args.begin(), end = args.end(); while (it != end) { Operand operand; (*it)->accept(*this); if ((*it)->isLiteral()) { operand.op_type = FETCH_CONST; operand.value_id = static_cast<Literal*>(*it)->getConstId(); } else { operand.op_type = (*it)->isEvaluable() ? FETCH_TMP : FETCH_VAR; operand.value_id = (*it)->getValueId(); if ((*it)->getScope()) { operand.scope_id = (*it)->getScope()->getId(); } } m_ir.push_back(IR(OP_SEND_VAL, operand)); ++it; } } m_ir.push_back(IR(OP_FCALL, Operand(FETCH_VAR, sym->value_id, sym->scope->getId()))); } void Codegen::visit(FunctionDecl* node) { size_t start_func = m_ir.size(); m_ir.push_back(IR(OP_JMP, Operand(JMP_ADDR, 0))); Symbol* sym = node->getIdent()->getSymbol(); Function* func = static_cast<Function*>(sym->scope->getValue(sym->value_id)->getObj()); func->setAddr(m_ir.size()); m_scope = node->getScope(); if (node->hasArgs()) { node->getArgs()->accept(*this); } node->getBlock()->accept(*this); m_scope = m_scope->getParent(); m_ir.push_back(IR(OP_LEAVE)); m_ir[start_func].op1.value_id = m_ir.size(); } void Codegen::visit(Return* node) { // TODO: return value m_ir.push_back(IR(OP_RET)); } void Codegen::visit(While* node) { size_t start_while = m_ir.size(); Node* cond = node->getCondition(); cond->accept(*this); if (cond->isLiteral()) { m_ir.push_back(IR(OP_JMPZ, Operand(FETCH_CONST, static_cast<Literal*>(cond)->getConstId()))); } else if (cond->getScope()) { m_ir.push_back(IR(OP_JMPZ, Operand(FETCH_VAR, cond->getValueId(), cond->getScope()->getId()))); } else { m_ir.push_back(IR(OP_JMPZ, Operand(FETCH_TMP, cond->getValueId()))); } node->getBlock()->accept(*this); m_ir.push_back(IR(OP_JMP, Operand(JMP_ADDR, start_while))); m_ir[start_while].op2.value_id = m_ir.size(); } void Codegen::visit(IncDec* node) { Opcode op; node->getVar()->accept(*this); switch (node->getOperator()) { case IncDec::PRE_INC: op = OP_PRE_INC; break; case IncDec::PRE_DEC: op = OP_PRE_DEC; break; case IncDec::POS_INC: op = OP_POS_INC; break; case IncDec::POS_DEC: op = OP_POS_DEC; break; } m_ir.push_back(IR(op, Operand(FETCH_VAR, node->getVar()->getValueId(), node->getVar()->getScope()->getId()))); size_t tmp_id = m_compiler->getTempValue(); m_ir.back().result = Operand(FETCH_TMP, tmp_id); node->setValueId(tmp_id); } void Codegen::visit(Arithmetic* node) { Node* lhs = node->getLhs(); Node* rhs = node->getRhs(); Opcode op; switch (node->getOperator()) { case Arithmetic::MOP_ADD: op = OP_ADD; break; case Arithmetic::MOP_SUB: op = OP_SUB; break; case Arithmetic::MOP_MUL: op = OP_MUL; break; case Arithmetic::MOP_DIV: op = OP_DIV; break; case Arithmetic::MOP_MOD: op = OP_MOD; break; } lhs->accept(*this); rhs->accept(*this); m_ir.push_back(IR(op)); if (lhs->isLiteral()) { m_ir.back().op1 = Operand(FETCH_CONST, static_cast<Literal*>(lhs)->getConstId()); } else { m_ir.back().op1 = Operand( lhs->isEvaluable() ? FETCH_TMP : FETCH_VAR, lhs->getValueId(), lhs->getScope()->getId()); } if (rhs->isLiteral()) { m_ir.back().op2 = Operand(FETCH_CONST, static_cast<Literal*>(rhs)->getConstId()); } else if (rhs->getScope()) { m_ir.back().op2 = Operand(FETCH_VAR, rhs->getValueId(), rhs->getScope()->getId()); } else { m_ir.back().op2 = Operand(FETCH_TMP, rhs->getValueId()); } size_t tmp_id = m_compiler->getTempValue(); m_ir.back().result = Operand(FETCH_TMP, tmp_id); node->setValueId(tmp_id); } }} // clever::ast <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2018, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "Gaffer/BackgroundTask.h" #include "Gaffer/ScriptNode.h" #include "IECore/MessageHandler.h" #include "boost/multi_index/member.hpp" #include "boost/multi_index/hashed_index.hpp" #include "boost/multi_index_container.hpp" #include "tbb/task.h" using namespace IECore; using namespace Gaffer; ////////////////////////////////////////////////////////////////////////// // Internal utilities ////////////////////////////////////////////////////////////////////////// namespace { class FunctionTask : public tbb::task { public : typedef std::function<void ()> Function; FunctionTask( const Function &f ) : m_f( f ) { } tbb::task *execute() override { m_f(); return nullptr; } private : Function m_f; }; const ScriptNode *scriptNode( const GraphComponent *subject ) { if( !subject ) { return nullptr; } else if( auto s = runTimeCast<const ScriptNode>( subject ) ) { return s; } else if( auto s = subject->ancestor<ScriptNode>() ) { return s; } else { // Unfortunately the GafferUI::View classes house internal // nodes which live outside any ScriptNode, but must still // take part in cancellation. This hack recovers the ScriptNode // for the node the view is currently connected to. while( subject ) { if( subject->isInstanceOf( "GafferUI::View" ) ) { return scriptNode( subject->getChild<Plug>( "in" )->getInput() ); } subject = subject->parent(); } return nullptr; } } struct ActiveTask { BackgroundTask *task; // Held via Ptr to keep the script alive // for the duration of the task. ConstScriptNodePtr subject; }; typedef boost::multi_index::multi_index_container< ActiveTask, boost::multi_index::indexed_by< boost::multi_index::hashed_unique< boost::multi_index::member<ActiveTask, BackgroundTask *, &ActiveTask::task> >, boost::multi_index::hashed_non_unique< boost::multi_index::member<ActiveTask, ConstScriptNodePtr, &ActiveTask::subject> > > > ActiveTasks; ActiveTasks &activeTasks() { static ActiveTasks a; return a; } } // namespace ////////////////////////////////////////////////////////////////////////// // BackgroundTask ////////////////////////////////////////////////////////////////////////// BackgroundTask::BackgroundTask( const Plug *subject, const Function &function ) : m_done( false ) { activeTasks().insert( ActiveTask{ this, scriptNode( subject ) } ); tbb::task *functionTask = new( tbb::task::allocate_root() ) FunctionTask( [this, function] { try { function( m_canceller ); } catch( const std::exception &e ) { IECore::msg( IECore::Msg::Error, "BackgroundTask", e.what() ); } catch( const IECore::Cancelled &e ) { // No need to do anything } catch( ... ) { IECore::msg( IECore::Msg::Error, "BackgroundTask", "Unknown error" ); } std::unique_lock<std::mutex> lock( m_mutex ); m_done = true; m_conditionVariable.notify_one(); } ); tbb::task::enqueue( *functionTask ); } BackgroundTask::~BackgroundTask() { cancelAndWait(); } void BackgroundTask::cancel() { m_canceller.cancel(); } void BackgroundTask::wait() { std::unique_lock<std::mutex> lock( m_mutex ); m_conditionVariable.wait( lock, [this]{ return m_done == true; } ); activeTasks().erase( this ); } void BackgroundTask::cancelAndWait() { m_canceller.cancel(); wait(); } bool BackgroundTask::done() const { return m_done; } void BackgroundTask::cancelAffectedTasks( const GraphComponent *actionSubject ) { const ActiveTasks &a = activeTasks(); if( !a.size() ) { return; } // Here our goal is to cancel any tasks which will be affected // by the edit about to be made to `actionSubject`. In theory // the most accurate thing to do might be to limit cancellation // to only the downstream affected plugs for `actionSubject`, but // for now we content ourselves with a cruder approach : we simply // cancel all tasks from the same ScriptNode. /// \todo Investigate fancier approaches. const ScriptNode *s = scriptNode( actionSubject ); auto range = a.get<1>().equal_range( s ); for( auto it = range.first; it != range.second; ) { // Cancellation invalidates iterator, so must increment first. auto nextIt = std::next( it ); it->task->cancelAndWait(); it = nextIt; } } <commit_msg>BackgroundTask : Improve cancellation speed<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2018, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "Gaffer/BackgroundTask.h" #include "Gaffer/ScriptNode.h" #include "IECore/MessageHandler.h" #include "boost/multi_index/member.hpp" #include "boost/multi_index/hashed_index.hpp" #include "boost/multi_index_container.hpp" #include "tbb/task.h" using namespace IECore; using namespace Gaffer; ////////////////////////////////////////////////////////////////////////// // Internal utilities ////////////////////////////////////////////////////////////////////////// namespace { class FunctionTask : public tbb::task { public : typedef std::function<void ()> Function; FunctionTask( const Function &f ) : m_f( f ) { } tbb::task *execute() override { m_f(); return nullptr; } private : Function m_f; }; const ScriptNode *scriptNode( const GraphComponent *subject ) { if( !subject ) { return nullptr; } else if( auto s = runTimeCast<const ScriptNode>( subject ) ) { return s; } else if( auto s = subject->ancestor<ScriptNode>() ) { return s; } else { // Unfortunately the GafferUI::View classes house internal // nodes which live outside any ScriptNode, but must still // take part in cancellation. This hack recovers the ScriptNode // for the node the view is currently connected to. while( subject ) { if( subject->isInstanceOf( "GafferUI::View" ) ) { return scriptNode( subject->getChild<Plug>( "in" )->getInput() ); } subject = subject->parent(); } return nullptr; } } struct ActiveTask { BackgroundTask *task; // Held via Ptr to keep the script alive // for the duration of the task. ConstScriptNodePtr subject; }; typedef boost::multi_index::multi_index_container< ActiveTask, boost::multi_index::indexed_by< boost::multi_index::hashed_unique< boost::multi_index::member<ActiveTask, BackgroundTask *, &ActiveTask::task> >, boost::multi_index::hashed_non_unique< boost::multi_index::member<ActiveTask, ConstScriptNodePtr, &ActiveTask::subject> > > > ActiveTasks; ActiveTasks &activeTasks() { static ActiveTasks a; return a; } } // namespace ////////////////////////////////////////////////////////////////////////// // BackgroundTask ////////////////////////////////////////////////////////////////////////// BackgroundTask::BackgroundTask( const Plug *subject, const Function &function ) : m_done( false ) { activeTasks().insert( ActiveTask{ this, scriptNode( subject ) } ); tbb::task *functionTask = new( tbb::task::allocate_root() ) FunctionTask( [this, function] { try { function( m_canceller ); } catch( const std::exception &e ) { IECore::msg( IECore::Msg::Error, "BackgroundTask", e.what() ); } catch( const IECore::Cancelled &e ) { // No need to do anything } catch( ... ) { IECore::msg( IECore::Msg::Error, "BackgroundTask", "Unknown error" ); } std::unique_lock<std::mutex> lock( m_mutex ); m_done = true; m_conditionVariable.notify_one(); } ); tbb::task::enqueue( *functionTask ); } BackgroundTask::~BackgroundTask() { cancelAndWait(); } void BackgroundTask::cancel() { m_canceller.cancel(); } void BackgroundTask::wait() { std::unique_lock<std::mutex> lock( m_mutex ); m_conditionVariable.wait( lock, [this]{ return m_done == true; } ); activeTasks().erase( this ); } void BackgroundTask::cancelAndWait() { m_canceller.cancel(); wait(); } bool BackgroundTask::done() const { return m_done; } void BackgroundTask::cancelAffectedTasks( const GraphComponent *actionSubject ) { const ActiveTasks &a = activeTasks(); if( !a.size() ) { return; } // Here our goal is to cancel any tasks which will be affected // by the edit about to be made to `actionSubject`. In theory // the most accurate thing to do might be to limit cancellation // to only the downstream affected plugs for `actionSubject`, but // for now we content ourselves with a cruder approach : we simply // cancel all tasks from the same ScriptNode. /// \todo Investigate fancier approaches. const ScriptNode *s = scriptNode( actionSubject ); auto range = a.get<1>().equal_range( s ); // Call cancel for everything first. for( auto it = range.first; it != range.second; ++it ) { it->task->cancel(); } // And then perform all the waits. This way the wait on one // task doesn't delay the start of cancellation for the next. for( auto it = range.first; it != range.second; ) { // Wait invalidates iterator, so must increment first. auto nextIt = std::next( it ); it->task->wait(); it = nextIt; } } <|endoftext|>
<commit_before><commit_msg>Allow process swaps for renderer navigations away from an extension. We still avoid them for navigations away from hosted apps.<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2003-2008 Rony Shapiro <ronys@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ /** * \file Windows-specific implementation of dir.h */ #include <afx.h> #include <Windows.h> #include "../dir.h" #include <direct.h> stringT pws_os::getexecdir() { // returns the directory part of ::GetModuleFileName() TCHAR acPath[MAX_PATH + 1]; if (GetModuleFileName( NULL, acPath, MAX_PATH + 1) != 0) { // guaranteed file name of at least one character after path '\' *(_tcsrchr(acPath, _T('\\')) + 1) = _T('\0'); } else { acPath[0] = TCHAR('\\'); acPath[1] = TCHAR('\0'); } return stringT(acPath); } stringT pws_os::getcwd() { charT *curdir = _tgetcwd(NULL, 512); // NULL means 512 doesn't matter stringT CurDir(curdir); free(curdir); return CurDir; } bool pws_os::chdir(const stringT &dir) { ASSERT(!dir.empty()); return (_tchdir(dir.c_str()) == 0); } // In following, drive will be empty on non-Windows platforms bool pws_os::splitpath(const stringT &path, stringT &drive, stringT &dir, stringT &file, stringT &ext) { TCHAR tdrv[_MAX_DRIVE]; TCHAR tdir[_MAX_DIR]; TCHAR tname[_MAX_FNAME]; TCHAR text[_MAX_EXT]; memset(tdrv, 0x00, sizeof(tdrv)); memset(tdir, 0x00, sizeof(tdir)); memset(tname, 0x00, sizeof(tname)); memset(text, 0x00, sizeof(text)); if (_tsplitpath_s(path.c_str(), tdrv, tdir, tname, text) == 0) { drive = tdrv; dir = tdir; file = tname; ext = text; return true; } else return false; } stringT pws_os::makepath(const stringT &drive, const stringT &dir, const stringT &file, const stringT &ext) { stringT retval; TCHAR path[_MAX_PATH]; if (_tmakepath_s(path, drive.c_str(), dir.c_str(), file.c_str(), ext.c_str()) == 0) retval = path; return retval; } <commit_msg>nanonit<commit_after>/* * Copyright (c) 2003-2008 Rony Shapiro <ronys@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ /** * \file Windows-specific implementation of dir.h */ #include <afx.h> #include <Windows.h> #include "../dir.h" #include <direct.h> stringT pws_os::getexecdir() { // returns the directory part of ::GetModuleFileName() TCHAR acPath[MAX_PATH + 1]; if (GetModuleFileName( NULL, acPath, MAX_PATH + 1) != 0) { // guaranteed file name of at least one character after path '\' *(_tcsrchr(acPath, _T('\\')) + 1) = _T('\0'); } else { acPath[0] = TCHAR('\\'); acPath[1] = TCHAR('\0'); } return stringT(acPath); } stringT pws_os::getcwd() { charT *curdir = _tgetcwd(NULL, 512); // NULL means 512 doesn't matter stringT CurDir(curdir); free(curdir); return CurDir; } bool pws_os::chdir(const stringT &dir) { ASSERT(!dir.empty()); return (_tchdir(dir.c_str()) == 0); } // In following, drive will be empty on non-Windows platforms bool pws_os::splitpath(const stringT &path, stringT &drive, stringT &dir, stringT &file, stringT &ext) { TCHAR tdrv[_MAX_DRIVE]; TCHAR tdir[_MAX_DIR]; TCHAR tname[_MAX_FNAME]; TCHAR text[_MAX_EXT]; memset(tdrv, 0, sizeof(tdrv)); memset(tdir, 0, sizeof(tdir)); memset(tname, 0, sizeof(tname)); memset(text, 0, sizeof(text)); if (_tsplitpath_s(path.c_str(), tdrv, tdir, tname, text) == 0) { drive = tdrv; dir = tdir; file = tname; ext = text; return true; } else return false; } stringT pws_os::makepath(const stringT &drive, const stringT &dir, const stringT &file, const stringT &ext) { stringT retval; TCHAR path[_MAX_PATH]; memset(path, 0, sizeof(path)); if (_tmakepath_s(path, drive.c_str(), dir.c_str(), file.c_str(), ext.c_str()) == 0) retval = path; return retval; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("third_party")); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("third_party/ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL(test_server.GetURL("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } // http://crbug.com/54150 TEST_F(PPAPITest, FLAKY_Graphics2D) { RunTest("Graphics2D"); } // TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating. // Possibly all the image allocations slow things down on a loaded bot too much. TEST_F(PPAPITest, FLAKY_ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } TEST_F(PPAPITest, URLLoader) { RunTestViaHTTP("URLLoader"); } // Flaky, http://crbug.com/51012 TEST_F(PPAPITest, FLAKY_PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } // Flaky, http://crbug.com/48544. TEST_F(PPAPITest, FLAKY_Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, UrlUtil) { RunTest("UrlUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } <commit_msg>Mark PPAPITest.URLLoader as flaky.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("third_party")); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("third_party/ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL(test_server.GetURL("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } // http://crbug.com/54150 TEST_F(PPAPITest, FLAKY_Graphics2D) { RunTest("Graphics2D"); } // TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating. // Possibly all the image allocations slow things down on a loaded bot too much. TEST_F(PPAPITest, FLAKY_ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } TEST_F(PPAPITest, FLAKY_URLLoader) { RunTestViaHTTP("URLLoader"); } // Flaky, http://crbug.com/51012 TEST_F(PPAPITest, FLAKY_PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } // Flaky, http://crbug.com/48544. TEST_F(PPAPITest, FLAKY_Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, UrlUtil) { RunTest("UrlUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } <|endoftext|>
<commit_before><commit_msg>Enabling shared worker tests for Linux/Mac. Windows is blocked on b27636.<commit_after><|endoftext|>
<commit_before><commit_msg>Enable WorkerTest.QueuedSharedWorkerShutdown because it seems to work 100% now. BUG=42641 TEST=WorkerTest.QueuedSharedWorkerShutdown<commit_after><|endoftext|>
<commit_before><commit_msg>Disable worker-cloneport.html. This is to avoid needlessly accumulating flakiness reports. We know it's flaky and are looking for the race condition. Landing for prasadt, original CR: http://codereview.chromium.org/1566006 BUG=35965 TEST=none<commit_after><|endoftext|>
<commit_before>/* * DIPlib 3.0 * This file contains definitions for common functions declared in framework.h. * * (c)2016-2017, Cris Luengo. * Based on original DIPlib code: (c)1995-2014, Delft University of Technology. * * 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 "diplib.h" #include "diplib/framework.h" namespace dip { namespace Framework { // Part of the next two functions void SingletonExpandedSize( UnsignedArray& size, UnsignedArray const& size2 ) { if( size.size() < size2.size() ) { size.resize( size2.size(), 1 ); } for( dip::uint jj = 0; jj < size2.size(); ++jj ) { if( size[ jj ] != size2[ jj ] ) { if( size[ jj ] == 1 ) { size[ jj ] = size2[ jj ]; } else if( size2[ jj ] != 1 ) { DIP_THROW( E::SIZES_DONT_MATCH ); } } } } // Figure out what the size of the images must be. UnsignedArray SingletonExpandedSize( ImageConstRefArray const& in ) { UnsignedArray size = in[ 0 ].get().Sizes(); for( dip::uint ii = 1; ii < in.size(); ++ii ) { UnsignedArray size2 = in[ ii ].get().Sizes(); SingletonExpandedSize( size, size2 ); } return size; } // Idem as above. UnsignedArray SingletonExpandedSize( ImageArray const& in ) { UnsignedArray size = in[ 0 ].Sizes(); for( dip::uint ii = 1; ii < in.size(); ++ii ) { UnsignedArray size2 = in[ ii ].Sizes(); SingletonExpandedSize( size, size2 ); } return size; } dip::uint SingletonExpendedTensorElements( ImageArray const& in ) { dip::uint tsize = in[ 0 ].TensorElements(); for( dip::uint ii = 1; ii < in.size(); ++ii ) { dip::uint tsize2 = in[ ii ].TensorElements(); if( tsize != tsize2 ) { if( tsize == 1 ) { tsize = tsize2; } else if( tsize2 != 1 ) { DIP_THROW( E::SIZES_DONT_MATCH ); } } } return tsize; } static dip::uint OptimalProcessingDim_internal( UnsignedArray const& sizes, IntegerArray const& strides ) { constexpr dip::uint SMALL_IMAGE = 63; // A good value would depend on the size of cache. dip::uint processingDim = 0; for( dip::uint ii = 1; ii < strides.size(); ++ii ) { if( strides[ ii ] < strides[ processingDim ] ) { if( ( sizes[ ii ] > SMALL_IMAGE ) || ( sizes[ ii ] > sizes[ processingDim ] ) ) { processingDim = ii; } } else if( ( sizes[ processingDim ] <= SMALL_IMAGE ) && ( sizes[ ii ] > sizes[ processingDim ] ) ) { processingDim = ii; } } return processingDim; } // Find best processing dimension, which is the one with the smallest stride, // except if that dimension is very small and there's a longer dimension. dip::uint OptimalProcessingDim( Image const& in ) { DIP_THROW_IF( !in.IsForged(), E::IMAGE_NOT_FORGED ); return OptimalProcessingDim_internal( in.Sizes(), in.Strides() ); } // Find the best processing dimension as above, but giving preference to a dimension // where `kernelSizes` is large also. dip::uint OptimalProcessingDim( Image const& in, UnsignedArray const& kernelSizes ) { DIP_THROW_IF( !in.IsForged(), E::IMAGE_NOT_FORGED ); UnsignedArray sizes = in.Sizes(); DIP_THROW_IF( sizes.size() != kernelSizes.size(), E::ARRAY_ILLEGAL_SIZE ); for( dip::uint ii = 0; ii < sizes.size(); ++ii ) { if( kernelSizes[ ii ] == 1 ) { sizes[ ii ] = 1; // this will surely force the algorithm to not return this dimension as optimal processing dimension } } // TODO: a kernel of 1000x2 should definitely return the dimension where it's 1000 as the optimal dimension. Or? return OptimalProcessingDim_internal( sizes, in.Strides() ); } } // namespace Framework } // namespace dip <commit_msg>Fixed `dip::Framework::OptimalProcessingDim` to use absolute strides and ignore zero stride.<commit_after>/* * DIPlib 3.0 * This file contains definitions for common functions declared in framework.h. * * (c)2016-2017, Cris Luengo. * Based on original DIPlib code: (c)1995-2014, Delft University of Technology. * * 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 "diplib.h" #include "diplib/framework.h" namespace dip { namespace Framework { // Part of the next two functions void SingletonExpandedSize( UnsignedArray& size, UnsignedArray const& size2 ) { if( size.size() < size2.size() ) { size.resize( size2.size(), 1 ); } for( dip::uint jj = 0; jj < size2.size(); ++jj ) { if( size[ jj ] != size2[ jj ] ) { if( size[ jj ] == 1 ) { size[ jj ] = size2[ jj ]; } else if( size2[ jj ] != 1 ) { DIP_THROW( E::SIZES_DONT_MATCH ); } } } } // Figure out what the size of the images must be. UnsignedArray SingletonExpandedSize( ImageConstRefArray const& in ) { UnsignedArray size = in[ 0 ].get().Sizes(); for( dip::uint ii = 1; ii < in.size(); ++ii ) { UnsignedArray size2 = in[ ii ].get().Sizes(); SingletonExpandedSize( size, size2 ); } return size; } // Idem as above. UnsignedArray SingletonExpandedSize( ImageArray const& in ) { UnsignedArray size = in[ 0 ].Sizes(); for( dip::uint ii = 1; ii < in.size(); ++ii ) { UnsignedArray size2 = in[ ii ].Sizes(); SingletonExpandedSize( size, size2 ); } return size; } dip::uint SingletonExpendedTensorElements( ImageArray const& in ) { dip::uint tsize = in[ 0 ].TensorElements(); for( dip::uint ii = 1; ii < in.size(); ++ii ) { dip::uint tsize2 = in[ ii ].TensorElements(); if( tsize != tsize2 ) { if( tsize == 1 ) { tsize = tsize2; } else if( tsize2 != 1 ) { DIP_THROW( E::SIZES_DONT_MATCH ); } } } return tsize; } static dip::uint OptimalProcessingDim_internal( UnsignedArray const& sizes, IntegerArray const& strides ) { constexpr dip::uint SMALL_IMAGE = 63; // A good value would depend on the size of cache. dip::uint processingDim = 0; for( dip::uint ii = 1; ii < strides.size(); ++ii ) { if(( strides[ ii ] != 0 ) && ( std::abs( strides[ ii ] ) < std::abs( strides[ processingDim ] ))) { if( ( sizes[ ii ] > SMALL_IMAGE ) || ( sizes[ ii ] > sizes[ processingDim ] ) ) { processingDim = ii; } } else if( ( sizes[ processingDim ] <= SMALL_IMAGE ) && ( sizes[ ii ] > sizes[ processingDim ] ) ) { processingDim = ii; } } return processingDim; } // Find best processing dimension, which is the one with the smallest stride, // except if that dimension is very small and there's a longer dimension. dip::uint OptimalProcessingDim( Image const& in ) { DIP_THROW_IF( !in.IsForged(), E::IMAGE_NOT_FORGED ); return OptimalProcessingDim_internal( in.Sizes(), in.Strides() ); } // Find the best processing dimension as above, but giving preference to a dimension // where `kernelSizes` is large also. dip::uint OptimalProcessingDim( Image const& in, UnsignedArray const& kernelSizes ) { DIP_THROW_IF( !in.IsForged(), E::IMAGE_NOT_FORGED ); UnsignedArray sizes = in.Sizes(); DIP_THROW_IF( sizes.size() != kernelSizes.size(), E::ARRAY_ILLEGAL_SIZE ); for( dip::uint ii = 0; ii < sizes.size(); ++ii ) { if( kernelSizes[ ii ] == 1 ) { sizes[ ii ] = 1; // this will surely force the algorithm to not return this dimension as optimal processing dimension } } // TODO: a kernel of 1000x2 should definitely return the dimension where it's 1000 as the optimal dimension. Or? return OptimalProcessingDim_internal( sizes, in.Strides() ); } } // namespace Framework } // namespace dip <|endoftext|>
<commit_before>#pragma once #include "physics/forkable.hpp" namespace principia { namespace physics { template<typename Tr4jectory> void Forkable<Tr4jectory>::DeleteFork(not_null<Tr4jectory**> const trajectory) { CHECK_NOTNULL(*trajectory); std::experimental::optional<Instant> const fork_time = (*trajectory)->ForkTime(); CHECK(fork_time); // Find the position of |*forkable| among our children and remove it. auto const range = children_.equal_range(*fork_time); for (auto it = range.first; it != range.second; ++it) { if (it->second.get() == *trajectory) { children_.erase(it); *trajectory = nullptr; return; } } LOG(FATAL) << "argument is not a child of this trajectory"; } template<typename Tr4jectory> bool Forkable<Tr4jectory>::is_root() const { return parent_ == nullptr; } template<typename Tr4jectory> not_null<Tr4jectory const*> Forkable<Tr4jectory>::root() const { not_null<Tr4jectory const*> ancestor = that(); while (ancestor->parent_ != nullptr) { ancestor = ancestor->parent_; } return ancestor; } template<typename Tr4jectory> not_null<Tr4jectory*> Forkable<Tr4jectory>::root() { not_null<Tr4jectory*> ancestor = that(); while (ancestor->parent_ != nullptr) { ancestor = ancestor->parent_; } return ancestor; } template<typename Tr4jectory> std::experimental::optional<Instant> Forkable<Tr4jectory>::ForkTime() const { if (is_root()) { return std::experimental::nullopt; } else { return (*position_in_parent_children_)->first; } } template<typename Tr4jectory> bool Forkable<Tr4jectory>::Iterator::operator==(Iterator const& right) const { return ancestry_ == right.ancestry_ && current_ == right.current_; } template<typename Tr4jectory> bool Forkable<Tr4jectory>::Iterator::operator!=(Iterator const& right) const { return !(*this == right); } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator& Forkable<Tr4jectory>::Iterator::operator++() { CHECK(!ancestry_.empty()); CHECK(current_ != ancestry_.front()->timeline_end()); // Check if there is a next child in the ancestry. auto ancestry_it = ancestry_.begin(); if (++ancestry_it != ancestry_.end()) { // There is a next child. See if we reached its fork time. Instant const& current_time = ForkableTraits<Tr4jectory>::time(current_); not_null<Tr4jectory const*> child = *ancestry_it; Instant child_fork_time = (*child->position_in_parent_children_)->first; if (current_time == child_fork_time) { // We have reached the fork time of the next child. There may be several // forks at that time so we must skip them until we find a fork that is at // a different time or the end of the children. do { current_ = child->timeline_begin(); // May be at end. ancestry_.pop_front(); if (++ancestry_it == ancestry_.end()) { break; } child = *ancestry_it; child_fork_time = (*child->position_in_parent_children_)->first; } while (current_time == child_fork_time); CheckNormalizedIfEnd(); return *this; } } // Business as usual, keep moving along the same timeline. ++current_; CheckNormalizedIfEnd(); return *this; } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator& Forkable<Tr4jectory>::Iterator::operator--() { CHECK(!ancestry_.empty()); not_null<Tr4jectory const*> ancestor = ancestry_.front(); if (current_ == ancestor->timeline_begin()) { CHECK_NOTNULL(ancestor->parent_); // At the beginning of the first timeline. Push the parent in front of the // ancestry and set |current_| to the fork point. If the timeline is empty, // keep going until we find a non-empty one or the root. do { current_ = *ancestor->position_in_parent_timeline_; ancestor = ancestor->parent_; ancestry_.push_front(ancestor); } while (current_ == ancestor->timeline_end() && ancestor->parent_ != nullptr); return *this; } --current_; return *this; } template<typename Tr4jectory> typename Forkable<Tr4jectory>::TimelineConstIterator Forkable<Tr4jectory>::Iterator::current() const { return current_; } template<typename Tr4jectory> not_null<Tr4jectory const*> Forkable<Tr4jectory>::Iterator::trajectory() const { CHECK(!ancestry_.empty()); return ancestry_.back(); } template<typename Tr4jectory> void Forkable<Tr4jectory>::Iterator::NormalizeIfEnd() { CHECK(!ancestry_.empty()); if (current_ == ancestry_.front()->timeline_end() && ancestry_.size() > 1) { ancestry_.erase(ancestry_.begin(), --ancestry_.end()); current_ = ancestry_.front()->timeline_end(); } } template<typename Tr4jectory> void Forkable<Tr4jectory>::Iterator::CheckNormalizedIfEnd() { CHECK(current_ != ancestry_.front()->timeline_end() || ancestry_.size() == 1); } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator Forkable<Tr4jectory>::Begin() const { not_null<Tr4jectory const*> ancestor = root(); return Wrap(ancestor, ancestor->timeline_begin()); } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator Forkable<Tr4jectory>::End() const { not_null<Tr4jectory const*> const ancestor = that(); Iterator iterator; iterator.ancestry_.push_front(ancestor); iterator.current_ = ancestor->timeline_end(); iterator.CheckNormalizedIfEnd(); return iterator; } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator Forkable<Tr4jectory>::Find(Instant const& time) const { Iterator iterator; // Go up the ancestry chain until we find a timeline that covers |time| (that // is, |time| is after the first time of the timeline). Set |current_| to // the location of |time|, which may be |end()|. The ancestry has |forkable| // at the back, and the object containing |current_| at the front. Tr4jectory const* ancestor = that(); do { iterator.ancestry_.push_front(ancestor); if (!ancestor->timeline_empty() && ForkableTraits<Tr4jectory>::time(ancestor->timeline_begin()) <= time) { iterator.current_ = ancestor->timeline_find(time); // May be at end. break; } iterator.current_ = ancestor->timeline_end(); ancestor = ancestor->parent_; } while (ancestor != nullptr); iterator.NormalizeIfEnd(); return iterator; } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator Forkable<Tr4jectory>::LowerBound(Instant const& time) const { Iterator iterator; // Go up the ancestry chain until we find a timeline that covers |time| (that // is, |time| is after the first time of the timeline). Set |current_| to // the location of |time|, which may be |end()|. The ancestry has |forkable| // at the back, and the object containing |current_| at the front. Tr4jectory const* ancestor = that(); do { iterator.ancestry_.push_front(ancestor); if (!ancestor->timeline_empty() && ForkableTraits<Tr4jectory>::time(ancestor->timeline_begin()) <= time) { iterator.current_ = ancestor->timeline_lower_bound(time); // May be at end. break; } iterator.current_ = ancestor->timeline_begin(); ancestor = ancestor->parent_; } while (ancestor != nullptr); iterator.NormalizeIfEnd(); return iterator; } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator Forkable<Tr4jectory>::Wrap( not_null<const Tr4jectory*> const ancestor, TimelineConstIterator const position_in_ancestor_timeline) const { Iterator iterator; // Go up the ancestry chain until we find |ancestor| and set |current_| to // |position_in_ancestor_timeline|. The ancestry has |forkable| // at the back, and the object containing |current_| at the front. not_null<Tr4jectory const*> ancest0r = that(); do { iterator.ancestry_.push_front(ancest0r); if (ancestor == ancest0r) { iterator.current_ = position_in_ancestor_timeline; // May be at end. iterator.CheckNormalizedIfEnd(); return iterator; } iterator.current_ = ancest0r->timeline_end(); ancest0r = ancest0r->parent_; } while (ancest0r != nullptr); LOG(FATAL) << "The ancestor parameter is not an ancestor of this trajectory"; base::noreturn(); } template<typename Tr4jectory> void Forkable<Tr4jectory>::WritePointerToMessage( not_null<serialization::Trajectory::Pointer*> const message) const { not_null<Tr4jectory const*> ancestor = that(); while (ancestor->parent_ != nullptr) { auto const position_in_parent_children = position_in_parent_children_; auto const position_in_parent_timeline = position_in_parent_timeline_; ancestor = ancestor->parent_; int const children_distance = std::distance(ancestor->children_.begin(), *position_in_parent_children); int const timeline_distance = std::distance(ancestor->timeline_begin(), *position_in_parent_timeline); auto* const fork_message = message->add_fork(); fork_message->set_children_distance(children_distance); fork_message->set_timeline_distance(timeline_distance); } } template<typename Tr4jectory> not_null<Tr4jectory*> Forkable<Tr4jectory>::ReadPointerFromMessage( serialization::Trajectory::Pointer const& message, not_null<Tr4jectory*> const trajectory) { CHECK(trajectory->is_root()); not_null<Tr4jectory*> descendant = trajectory; for (auto const& fork_message : message.fork()) { int const children_distance = fork_message.children_distance(); int const timeline_distance = fork_message.timeline_distance(); auto children_it = descendant->children_.begin(); auto timeline_it = descendant->timeline_begin(); std::advance(children_it, children_distance); std::advance(timeline_it, timeline_distance); descendant = children_it->second.get(); } return descendant; } template<typename Tr4jectory> not_null<Tr4jectory*> Forkable<Tr4jectory>::NewFork(Instant const & time) { std::experimental::optional<Instant> const fork_time = ForkTime(); CHECK(timeline_find(time) != timeline_end() || (fork_time && time == *fork_time)) << "NewFork at nonexistent time " << time; // May be at |timeline_end()| if |time| is the fork time of this object. auto timeline_it = timeline_find(time); // First create a child in the multimap. auto const child_it = children_.emplace(time, std::make_unique<Tr4jectory>()); // Now set the members of the child object. std::unique_ptr<Tr4jectory> const& child_forkable = child_it->second; child_forkable->parent_ = that(); child_forkable->position_in_parent_children_ = child_it; child_forkable->position_in_parent_timeline_ = timeline_it; return child_forkable.get(); } template<typename Tr4jectory> void Forkable<Tr4jectory>::DeleteAllForksAfter(Instant const& time) { // Get an iterator denoting the first entry with time > |time|. Remove that // entry and all the entries that follow it. This preserve any entry with // time == |time|. CHECK(is_root() || time >= *ForkTime()) << "DeleteAllForksAfter before the fork time"; auto const it = children_.upper_bound(time); children_.erase(it, children_.end()); } template<typename Tr4jectory> void Forkable<Tr4jectory>::DeleteAllForksBefore(Instant const& time) { CHECK(is_root()) << "DeleteAllForksBefore on a nonroot trajectory"; // Get an iterator denoting the first entry with time > |time|. Remove all // the entries that precede it. This removes any entry with time == |time|. auto it = children_.upper_bound(time); children_.erase(children_.begin(), it); } template<typename Tr4jectory> void Forkable<Tr4jectory>::WriteSubTreeToMessage( not_null<serialization::Trajectory*> const message) const { std::experimental::optional<Instant> last_instant; serialization::Trajectory::Litter* litter = nullptr; for (auto const& pair : children_) { Instant const& fork_time = pair.first; std::unique_ptr<Tr4jectory> const& child = pair.second; if (!last_instant || fork_time != last_instant) { last_instant = fork_time; litter = message->add_children(); fork_time.WriteToMessage(litter->mutable_fork_time()); } child->WriteSubTreeToMessage(litter->add_trajectories()); } } template<typename Tr4jectory> void Forkable<Tr4jectory>::FillSubTreeFromMessage( serialization::Trajectory const& message) { for (serialization::Trajectory::Litter const& litter : message.children()) { Instant const fork_time = Instant::ReadFromMessage(litter.fork_time()); for (serialization::Trajectory const& child : litter.trajectories()) { NewFork(fork_time)->FillSubTreeFromMessage(child); } } } } // namespace physics } // namespace principia <commit_msg>Const iterator.<commit_after>#pragma once #include "physics/forkable.hpp" namespace principia { namespace physics { template<typename Tr4jectory> void Forkable<Tr4jectory>::DeleteFork(not_null<Tr4jectory**> const trajectory) { CHECK_NOTNULL(*trajectory); std::experimental::optional<Instant> const fork_time = (*trajectory)->ForkTime(); CHECK(fork_time); // Find the position of |*forkable| among our children and remove it. auto const range = children_.equal_range(*fork_time); for (auto it = range.first; it != range.second; ++it) { if (it->second.get() == *trajectory) { children_.erase(it); *trajectory = nullptr; return; } } LOG(FATAL) << "argument is not a child of this trajectory"; } template<typename Tr4jectory> bool Forkable<Tr4jectory>::is_root() const { return parent_ == nullptr; } template<typename Tr4jectory> not_null<Tr4jectory const*> Forkable<Tr4jectory>::root() const { not_null<Tr4jectory const*> ancestor = that(); while (ancestor->parent_ != nullptr) { ancestor = ancestor->parent_; } return ancestor; } template<typename Tr4jectory> not_null<Tr4jectory*> Forkable<Tr4jectory>::root() { not_null<Tr4jectory*> ancestor = that(); while (ancestor->parent_ != nullptr) { ancestor = ancestor->parent_; } return ancestor; } template<typename Tr4jectory> std::experimental::optional<Instant> Forkable<Tr4jectory>::ForkTime() const { if (is_root()) { return std::experimental::nullopt; } else { return (*position_in_parent_children_)->first; } } template<typename Tr4jectory> bool Forkable<Tr4jectory>::Iterator::operator==(Iterator const& right) const { return ancestry_ == right.ancestry_ && current_ == right.current_; } template<typename Tr4jectory> bool Forkable<Tr4jectory>::Iterator::operator!=(Iterator const& right) const { return !(*this == right); } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator& Forkable<Tr4jectory>::Iterator::operator++() { CHECK(!ancestry_.empty()); CHECK(current_ != ancestry_.front()->timeline_end()); // Check if there is a next child in the ancestry. auto ancestry_it = ancestry_.begin(); if (++ancestry_it != ancestry_.end()) { // There is a next child. See if we reached its fork time. Instant const& current_time = ForkableTraits<Tr4jectory>::time(current_); not_null<Tr4jectory const*> child = *ancestry_it; Instant child_fork_time = (*child->position_in_parent_children_)->first; if (current_time == child_fork_time) { // We have reached the fork time of the next child. There may be several // forks at that time so we must skip them until we find a fork that is at // a different time or the end of the children. do { current_ = child->timeline_begin(); // May be at end. ancestry_.pop_front(); if (++ancestry_it == ancestry_.end()) { break; } child = *ancestry_it; child_fork_time = (*child->position_in_parent_children_)->first; } while (current_time == child_fork_time); CheckNormalizedIfEnd(); return *this; } } // Business as usual, keep moving along the same timeline. ++current_; CheckNormalizedIfEnd(); return *this; } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator& Forkable<Tr4jectory>::Iterator::operator--() { CHECK(!ancestry_.empty()); not_null<Tr4jectory const*> ancestor = ancestry_.front(); if (current_ == ancestor->timeline_begin()) { CHECK_NOTNULL(ancestor->parent_); // At the beginning of the first timeline. Push the parent in front of the // ancestry and set |current_| to the fork point. If the timeline is empty, // keep going until we find a non-empty one or the root. do { current_ = *ancestor->position_in_parent_timeline_; ancestor = ancestor->parent_; ancestry_.push_front(ancestor); } while (current_ == ancestor->timeline_end() && ancestor->parent_ != nullptr); return *this; } --current_; return *this; } template<typename Tr4jectory> typename Forkable<Tr4jectory>::TimelineConstIterator Forkable<Tr4jectory>::Iterator::current() const { return current_; } template<typename Tr4jectory> not_null<Tr4jectory const*> Forkable<Tr4jectory>::Iterator::trajectory() const { CHECK(!ancestry_.empty()); return ancestry_.back(); } template<typename Tr4jectory> void Forkable<Tr4jectory>::Iterator::NormalizeIfEnd() { CHECK(!ancestry_.empty()); if (current_ == ancestry_.front()->timeline_end() && ancestry_.size() > 1) { ancestry_.erase(ancestry_.begin(), --ancestry_.end()); current_ = ancestry_.front()->timeline_end(); } } template<typename Tr4jectory> void Forkable<Tr4jectory>::Iterator::CheckNormalizedIfEnd() { CHECK(current_ != ancestry_.front()->timeline_end() || ancestry_.size() == 1); } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator Forkable<Tr4jectory>::Begin() const { not_null<Tr4jectory const*> ancestor = root(); return Wrap(ancestor, ancestor->timeline_begin()); } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator Forkable<Tr4jectory>::End() const { not_null<Tr4jectory const*> const ancestor = that(); Iterator iterator; iterator.ancestry_.push_front(ancestor); iterator.current_ = ancestor->timeline_end(); iterator.CheckNormalizedIfEnd(); return iterator; } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator Forkable<Tr4jectory>::Find(Instant const& time) const { Iterator iterator; // Go up the ancestry chain until we find a timeline that covers |time| (that // is, |time| is after the first time of the timeline). Set |current_| to // the location of |time|, which may be |end()|. The ancestry has |forkable| // at the back, and the object containing |current_| at the front. Tr4jectory const* ancestor = that(); do { iterator.ancestry_.push_front(ancestor); if (!ancestor->timeline_empty() && ForkableTraits<Tr4jectory>::time(ancestor->timeline_begin()) <= time) { iterator.current_ = ancestor->timeline_find(time); // May be at end. break; } iterator.current_ = ancestor->timeline_end(); ancestor = ancestor->parent_; } while (ancestor != nullptr); iterator.NormalizeIfEnd(); return iterator; } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator Forkable<Tr4jectory>::LowerBound(Instant const& time) const { Iterator iterator; // Go up the ancestry chain until we find a timeline that covers |time| (that // is, |time| is after the first time of the timeline). Set |current_| to // the location of |time|, which may be |end()|. The ancestry has |forkable| // at the back, and the object containing |current_| at the front. Tr4jectory const* ancestor = that(); do { iterator.ancestry_.push_front(ancestor); if (!ancestor->timeline_empty() && ForkableTraits<Tr4jectory>::time(ancestor->timeline_begin()) <= time) { iterator.current_ = ancestor->timeline_lower_bound(time); // May be at end. break; } iterator.current_ = ancestor->timeline_begin(); ancestor = ancestor->parent_; } while (ancestor != nullptr); iterator.NormalizeIfEnd(); return iterator; } template<typename Tr4jectory> typename Forkable<Tr4jectory>::Iterator Forkable<Tr4jectory>::Wrap( not_null<const Tr4jectory*> const ancestor, TimelineConstIterator const position_in_ancestor_timeline) const { Iterator iterator; // Go up the ancestry chain until we find |ancestor| and set |current_| to // |position_in_ancestor_timeline|. The ancestry has |forkable| // at the back, and the object containing |current_| at the front. not_null<Tr4jectory const*> ancest0r = that(); do { iterator.ancestry_.push_front(ancest0r); if (ancestor == ancest0r) { iterator.current_ = position_in_ancestor_timeline; // May be at end. iterator.CheckNormalizedIfEnd(); return iterator; } iterator.current_ = ancest0r->timeline_end(); ancest0r = ancest0r->parent_; } while (ancest0r != nullptr); LOG(FATAL) << "The ancestor parameter is not an ancestor of this trajectory"; base::noreturn(); } template<typename Tr4jectory> void Forkable<Tr4jectory>::WritePointerToMessage( not_null<serialization::Trajectory::Pointer*> const message) const { not_null<Tr4jectory const*> ancestor = that(); while (ancestor->parent_ != nullptr) { auto const position_in_parent_children = position_in_parent_children_; auto const position_in_parent_timeline = position_in_parent_timeline_; ancestor = ancestor->parent_; int const children_distance = std::distance(ancestor->children_.begin(), *position_in_parent_children); int const timeline_distance = std::distance(ancestor->timeline_begin(), *position_in_parent_timeline); auto* const fork_message = message->add_fork(); fork_message->set_children_distance(children_distance); fork_message->set_timeline_distance(timeline_distance); } } template<typename Tr4jectory> not_null<Tr4jectory*> Forkable<Tr4jectory>::ReadPointerFromMessage( serialization::Trajectory::Pointer const& message, not_null<Tr4jectory*> const trajectory) { CHECK(trajectory->is_root()); not_null<Tr4jectory*> descendant = trajectory; for (auto const& fork_message : message.fork()) { int const children_distance = fork_message.children_distance(); int const timeline_distance = fork_message.timeline_distance(); auto children_it = descendant->children_.begin(); auto timeline_it = descendant->timeline_begin(); std::advance(children_it, children_distance); std::advance(timeline_it, timeline_distance); descendant = children_it->second.get(); } return descendant; } template<typename Tr4jectory> not_null<Tr4jectory*> Forkable<Tr4jectory>::NewFork(Instant const & time) { std::experimental::optional<Instant> const fork_time = ForkTime(); CHECK(timeline_find(time) != timeline_end() || (fork_time && time == *fork_time)) << "NewFork at nonexistent time " << time; // May be at |timeline_end()| if |time| is the fork time of this object. auto timeline_it = timeline_find(time); // First create a child in the multimap. auto const child_it = children_.emplace(time, std::make_unique<Tr4jectory>()); typename Children::const_iterator const_child_it = child_it; // Now set the members of the child object. std::unique_ptr<Tr4jectory> const& child_forkable = const_child_it->second; child_forkable->parent_ = that(); child_forkable->position_in_parent_children_ = const_child_it; child_forkable->position_in_parent_timeline_ = timeline_it; return child_forkable.get(); } template<typename Tr4jectory> void Forkable<Tr4jectory>::DeleteAllForksAfter(Instant const& time) { // Get an iterator denoting the first entry with time > |time|. Remove that // entry and all the entries that follow it. This preserve any entry with // time == |time|. CHECK(is_root() || time >= *ForkTime()) << "DeleteAllForksAfter before the fork time"; auto const it = children_.upper_bound(time); children_.erase(it, children_.end()); } template<typename Tr4jectory> void Forkable<Tr4jectory>::DeleteAllForksBefore(Instant const& time) { CHECK(is_root()) << "DeleteAllForksBefore on a nonroot trajectory"; // Get an iterator denoting the first entry with time > |time|. Remove all // the entries that precede it. This removes any entry with time == |time|. auto it = children_.upper_bound(time); children_.erase(children_.begin(), it); } template<typename Tr4jectory> void Forkable<Tr4jectory>::WriteSubTreeToMessage( not_null<serialization::Trajectory*> const message) const { std::experimental::optional<Instant> last_instant; serialization::Trajectory::Litter* litter = nullptr; for (auto const& pair : children_) { Instant const& fork_time = pair.first; std::unique_ptr<Tr4jectory> const& child = pair.second; if (!last_instant || fork_time != last_instant) { last_instant = fork_time; litter = message->add_children(); fork_time.WriteToMessage(litter->mutable_fork_time()); } child->WriteSubTreeToMessage(litter->add_trajectories()); } } template<typename Tr4jectory> void Forkable<Tr4jectory>::FillSubTreeFromMessage( serialization::Trajectory const& message) { for (serialization::Trajectory::Litter const& litter : message.children()) { Instant const fork_time = Instant::ReadFromMessage(litter.fork_time()); for (serialization::Trajectory const& child : litter.trajectories()) { NewFork(fork_time)->FillSubTreeFromMessage(child); } } } } // namespace physics } // namespace principia <|endoftext|>
<commit_before><commit_msg>PostProcessManager: fix setMinMaxLevels for StructureMipmap.<commit_after><|endoftext|>
<commit_before>/** * @copyright Copyright (c) 2014, Wojciech Krzemien * @file JPetTaskIO.cpp * @author Wojciech Krzemien, wojciech.krzemien@if.uj.edu.pl */ #include "JPetTaskIO.h" #include <cassert> #include "../JPetReader/JPetReader.h" #include "../JPetTreeHeader/JPetTreeHeader.h" #include "../JPetTask/JPetTask.h" #include "../../framework/JPetHLDReader/JPetHLDReader.h" #include "../../JPetLoggerInclude.h" JPetTaskIO::JPetTaskIO(): fWriter(0), fReader(0), fHeader(0) { } void JPetTaskIO::init(const JPetOptions::Options& opts) { setOptions(JPetOptions(opts)); auto inputFilename = fOptions.getInputFile(); auto outputFilename = fOptions.getOutputFile(); createInputObjects(inputFilename); createOutputObjects(outputFilename); } void JPetTaskIO::exec() { assert(fTask); assert(fReader); assert(fParamManager); fTask->setParamManager(fParamManager); JPetTaskInterface::Options emptyOpts; fTask->init(emptyOpts); //prepare current task for file auto firstEvent = 0ll; auto lastEvent = 0ll; setUserLimits(fOptions, firstEvent, lastEvent); assert(lastEvent > 0); for (auto i = firstEvent; i < lastEvent; i++) { fTask->setEvent(&(static_cast<TNamed&>(fReader->getCurrentEvent()))); if (fOptions.isProgressBar()) { manageProgressBar(i, lastEvent); } fTask->exec(); fReader->nextEvent(); } fTask->terminate(); } void JPetTaskIO::terminate() { assert(fReader); assert(fWriter); assert(fHeader); INFO(Form("Finished processing %s.", "A")); fWriter->writeHeader(fHeader); // store the parametric objects in the ouptut ROOT file getParamManager().saveParametersToFile( fWriter); getParamManager().clearParameters(); fWriter->closeFile(); fReader->closeFile(); } void JPetTaskIO::createInputObjects(const char* inputFilename) { auto treeName = ""; if (fOptions.getInputFileType() == JPetOptions::kHld ) { fReader = new JPetHLDReader; treeName = "T"; } else { fReader = new JPetReader; treeName = "tree"; } if ( fReader->openFileAndLoadData( inputFilename, treeName )) { if (fOptions.getInputFileType() == JPetOptions::kHld ) { // create a header to be stored along with the output tree fHeader = new JPetTreeHeader(26); // add general info to the Tree header //fHeader->setBaseFileName( //JPetManager::GetManager().getInputFileNames()[0].c_str()); //// add info about this module to the processing stages' history in Tree header //fHeader->addStageInfo(this->GetName(), this->GetTitle(), MODULE_VERSION, //JPetManager::GetManager().GetTimeString()); } else { assert(fParamManager); fParamManager->readParametersFromFile(dynamic_cast<JPetReader*> (fReader)); // read the header from the previous analysis stage // fHeader = dynamic_cast<JPetReader*>(fReader)->getHeaderClone(); //fParamManager.readParametersFromFile( fReader ); } } else { ERROR(inputFilename + std::string(": Unable to open the input file")); exit(-1); } } void JPetTaskIO::createOutputObjects(const char* outputFilename) { fWriter = new JPetWriter( outputFilename ); fTask->setWriter(fWriter); } void JPetTaskIO::manageProgressBar(long long done, long long end) { printf("\r[%6.4f%% %%]", setProgressBar(done, end)); } float JPetTaskIO::setProgressBar(int currentEventNumber, int numberOfEvents) { return ( ((float)currentEventNumber) / numberOfEvents ) * 100; } const JPetParamBank& JPetTaskIO::getParamBank() { return fParamManager->getParamBank(); } JPetTaskIO::~JPetTaskIO() { if (fTask) delete fTask; if (fWriter) delete fWriter; if (fReader) delete fReader; } /// Sets values of firstEvent and lastEvent based on user options opts and total number of events from JPetReader void JPetTaskIO::setUserLimits(const JPetOptions& opts, long long& firstEvent, long long& lastEvent) const { assert(fReader); const auto kLastEvent = opts.getLastEvent(); const auto kFirstEvent = opts.getFirstEvent(); const auto kEventNum = fReader->getNbOfAllEvents(); if (kLastEvent < 0) { lastEvent = kEventNum; } else { lastEvent = kLastEvent < kEventNum ? kLastEvent : kEventNum; } firstEvent = kFirstEvent; assert(firstEvent <= lastEvent); } <commit_msg>Remove bug from JPetTaskIO. Add some asserts and cross-checks<commit_after>/** * @copyright Copyright (c) 2014, Wojciech Krzemien * @file JPetTaskIO.cpp * @author Wojciech Krzemien, wojciech.krzemien@if.uj.edu.pl */ #include "JPetTaskIO.h" #include <cassert> #include "../JPetReader/JPetReader.h" #include "../JPetTreeHeader/JPetTreeHeader.h" #include "../JPetTask/JPetTask.h" #include "../../framework/JPetHLDReader/JPetHLDReader.h" #include "../../JPetLoggerInclude.h" JPetTaskIO::JPetTaskIO(): fWriter(0), fReader(0), fHeader(0) { } void JPetTaskIO::init(const JPetOptions::Options& opts) { setOptions(JPetOptions(opts)); auto inputFilename = fOptions.getInputFile(); auto outputFilename = fOptions.getOutputFile(); createInputObjects(inputFilename); createOutputObjects(outputFilename); } void JPetTaskIO::exec() { assert(fTask); assert(fReader); assert(fParamManager); fTask->setParamManager(fParamManager); JPetTaskInterface::Options emptyOpts; fTask->init(emptyOpts); //prepare current task for file auto firstEvent = 0ll; auto lastEvent = 0ll; setUserLimits(fOptions, firstEvent, lastEvent); assert(lastEvent > 0); for (auto i = firstEvent; i < lastEvent; i++) { fTask->setEvent(&(static_cast<TNamed&>(fReader->getCurrentEvent()))); if (fOptions.isProgressBar()) { manageProgressBar(i, lastEvent); } fTask->exec(); fReader->nextEvent(); } fTask->terminate(); } void JPetTaskIO::terminate() { assert(fReader); assert(fWriter); assert(fHeader); INFO(Form("Finished processing %s.", "A")); fWriter->writeHeader(fHeader); // store the parametric objects in the ouptut ROOT file getParamManager().saveParametersToFile( fWriter); getParamManager().clearParameters(); fWriter->closeFile(); fReader->closeFile(); } void JPetTaskIO::createInputObjects(const char* inputFilename) { auto treeName = ""; if (fOptions.getInputFileType() == JPetOptions::kHld ) { fReader = new JPetHLDReader; treeName = "T"; } else { fReader = new JPetReader; treeName = "tree"; } if ( fReader->openFileAndLoadData( inputFilename, treeName )) { if (fOptions.getInputFileType() == JPetOptions::kHld ) { // create a header to be stored along with the output tree fHeader = new JPetTreeHeader(26); // add general info to the Tree header //fHeader->setBaseFileName( //JPetManager::GetManager().getInputFileNames()[0].c_str()); //// add info about this module to the processing stages' history in Tree header //fHeader->addStageInfo(this->GetName(), this->GetTitle(), MODULE_VERSION, //JPetManager::GetManager().GetTimeString()); } else { assert(fParamManager); fParamManager->readParametersFromFile(dynamic_cast<JPetReader*> (fReader)); // read the header from the previous analysis stage // fHeader = dynamic_cast<JPetReader*>(fReader)->getHeaderClone(); //fParamManager.readParametersFromFile( fReader ); } } else { ERROR(inputFilename + std::string(": Unable to open the input file")); exit(-1); } } void JPetTaskIO::createOutputObjects(const char* outputFilename) { fWriter = new JPetWriter( outputFilename ); fTask->setWriter(fWriter); } void JPetTaskIO::manageProgressBar(long long done, long long end) { printf("\r[%6.4f%% %%]", setProgressBar(done, end)); } float JPetTaskIO::setProgressBar(int currentEventNumber, int numberOfEvents) { return ( ((float)currentEventNumber) / numberOfEvents ) * 100; } const JPetParamBank& JPetTaskIO::getParamBank() { return fParamManager->getParamBank(); } JPetTaskIO::~JPetTaskIO() { if (fTask) delete fTask; if (fWriter) delete fWriter; if (fReader) delete fReader; } /// Sets values of firstEvent and lastEvent based on user options opts and total number of events from JPetReader void JPetTaskIO::setUserLimits(const JPetOptions& opts, long long& firstEvent, long long& lastEvent) const { assert(fReader); const auto kLastEvent = opts.getLastEvent(); const auto kFirstEvent = opts.getFirstEvent(); const auto kEventNum = fReader->getNbOfAllEvents(); if (kLastEvent < 0) { lastEvent = kEventNum; } else { lastEvent = kLastEvent < kEventNum ? kLastEvent : kEventNum; } if ( kFirstEvent < 0) { firstEvent = 0; } else { firstEvent = kFirstEvent; } assert(firstEvent>=0); assert(lastEvent>=0); assert(firstEvent <= lastEvent); } <|endoftext|>
<commit_before>#include <cfloat> #include "Steering.h" #include "Math.h" #include "Random.h" namespace Common { Steering::Steering(const Vehicle& e) : mUnit(e) { } Vector3 Steering::seek(const Vector3& tgtpos) { Vector3 desiredVelocity = (tgtpos - mUnit.getPosition()).normalized() * mUnit.getMaxSpeed(); return desiredVelocity - mUnit.getVelocity(); } Vector3 Steering::flee(const Vector3& threatpos) { Vector3 desiredVelocity = (mUnit.getPosition() - threatpos).normalized() * mUnit.getMaxSpeed(); return desiredVelocity - mUnit.getVelocity(); } Vector3 Steering::arrive(const Vector3& tgtpos) { auto dist = tgtpos - mUnit.getPosition(); float distlen = dist.length(); if(distlen < 0.0001f) return Vector3(); float speed = std::min(distlen / 0.6f, mUnit.getMaxSpeed()); Vector3 desiredVelocity = dist * (speed / distlen); return desiredVelocity - mUnit.getVelocity(); } Vector3 Steering::pursuit(const Vehicle& tgt) { Vector3 totgt = tgt.getPosition() - mUnit.getPosition(); float relHeading = mUnit.getVelocity().dot(tgt.getVelocity()); if((totgt.dot(mUnit.getPosition()) > 0.0f) && (relHeading < -0.95f)) { return seek(tgt.getPosition()); } float lookAheadTime = totgt.length() * (1.0f / (mUnit.getMaxSpeed() + tgt.getSpeed())); return seek(tgt.getPosition() + tgt.getVelocity() * lookAheadTime); } Vector3 Steering::evade(const Vehicle& threat) { Vector3 tothreat = threat.getPosition() - mUnit.getPosition(); float lookAheadTime = tothreat.length() * (1.0f / mUnit.getMaxSpeed() + threat.getSpeed()); return flee(threat.getPosition() + threat.getVelocity() * lookAheadTime); } Vector3 Steering::wander(float radius, float distance, float jitter) { mWanderTarget += Vector3(Random::clamped() * jitter, Random::clamped() * jitter, 0.0f); mWanderTarget.normalize(); mWanderTarget *= radius; Vector3 target = mUnit.getPosition() + mUnit.getVelocity().normalized() * distance + mWanderTarget; return target - mUnit.getPosition(); } Vector3 Steering::obstacleAvoidance(const std::vector<Obstacle*> obstacles) { Obstacle* nearest = nullptr; float distToNearest = FLT_MAX; if(mUnit.getVelocity().null()) return Vector3(); float minObstacleDistance = mUnit.getVelocity().length() * 0.5f; for(auto o : obstacles) { float heading = mUnit.getVelocity().dot(o->getPosition() - mUnit.getPosition()); if(heading < 0.0f) { continue; } float rad = mUnit.getRadius() + o->getRadius(); float dist = Math::pointToSegmentDistance(mUnit.getPosition(), mUnit.getPosition() + mUnit.getVelocity() * 0.5f, o->getPosition()) - rad; if(dist < distToNearest && dist < minObstacleDistance) { distToNearest = dist; nearest = o; } } if(!nearest) { return Vector3(); } Vector3 vecFromObj = Entity::vectorFromTo(*nearest, mUnit); if(vecFromObj.length() < mUnit.getRadius() + nearest->getRadius()) { // we're inside the obstacle return vecFromObj.normalized() * 100.0f; } distToNearest = std::max(0.01f, distToNearest); float velmultiplier = 0.1f + mUnit.getVelocity().length() * 0.5f; float multiplier = velmultiplier / distToNearest; Vector3 res = vecFromObj.normalized() * multiplier; return res; } Vector3 Steering::cohesion(const std::vector<Entity*> neighbours) { Vector3 centerOfMass; int count = 0; for(auto n : neighbours) { if(n == &mUnit) continue; centerOfMass += n->getPosition(); count++; } if(count) { centerOfMass *= (1.0f / count); return seek(centerOfMass); } else { return Vector3(); } } Vector3 Steering::separation(const std::vector<Entity*> neighbours) { Vector3 res; for(auto n : neighbours) { if(n == &mUnit) continue; Vector3 toMe = mUnit.getPosition() - n->getPosition(); if(toMe.null()) continue; res += toMe.normalized() / toMe.length(); } return res; } bool Steering::accumulate(Vector3& runningTotal, const Vector3& add) { float magnitude = runningTotal.length(); float remaining = mUnit.getMaxAcceleration() - magnitude; if(remaining <= 0.0f) return false; double toAdd = add.length(); if(toAdd < remaining) { runningTotal += add; return true; } else { runningTotal += add.normalized() * remaining; return false; } } Vector3 Steering::wallAvoidance(const std::vector<Wall*> walls) { Vector3 nearestPointOnWall; float distToNearest = FLT_MAX; if(mUnit.getVelocity().null()) return Vector3(); for(auto w : walls) { bool found = false; Math::segmentSegmentIntersection2D(mUnit.getPosition(), mUnit.getPosition() + mUnit.getVelocity() * 0.5f, w->getStart(), w->getEnd(), &found); if(found) { Vector3 nearest; float dist = Math::pointToSegmentDistance(w->getStart(), w->getEnd(), mUnit.getPosition(), &nearest); if(dist < distToNearest) { distToNearest = dist; nearestPointOnWall = nearest; } } } if(distToNearest == FLT_MAX) { return Vector3(); } Vector3 vecFromPoint = mUnit.getPosition() - nearestPointOnWall; Vector3 res = vecFromPoint.normalized() * 100.0f; return res; } } <commit_msg>fix wall avoidance<commit_after>#include <cfloat> #include "Steering.h" #include "Math.h" #include "Random.h" namespace Common { Steering::Steering(const Vehicle& e) : mUnit(e) { } Vector3 Steering::seek(const Vector3& tgtpos) { Vector3 desiredVelocity = (tgtpos - mUnit.getPosition()).normalized() * mUnit.getMaxSpeed(); return desiredVelocity - mUnit.getVelocity(); } Vector3 Steering::flee(const Vector3& threatpos) { Vector3 desiredVelocity = (mUnit.getPosition() - threatpos).normalized() * mUnit.getMaxSpeed(); return desiredVelocity - mUnit.getVelocity(); } Vector3 Steering::arrive(const Vector3& tgtpos) { auto dist = tgtpos - mUnit.getPosition(); float distlen = dist.length(); if(distlen < 0.0001f) return Vector3(); float speed = std::min(distlen / 0.6f, mUnit.getMaxSpeed()); Vector3 desiredVelocity = dist * (speed / distlen); return desiredVelocity - mUnit.getVelocity(); } Vector3 Steering::pursuit(const Vehicle& tgt) { Vector3 totgt = tgt.getPosition() - mUnit.getPosition(); float relHeading = mUnit.getVelocity().dot(tgt.getVelocity()); if((totgt.dot(mUnit.getPosition()) > 0.0f) && (relHeading < -0.95f)) { return seek(tgt.getPosition()); } float lookAheadTime = totgt.length() * (1.0f / (mUnit.getMaxSpeed() + tgt.getSpeed())); return seek(tgt.getPosition() + tgt.getVelocity() * lookAheadTime); } Vector3 Steering::evade(const Vehicle& threat) { Vector3 tothreat = threat.getPosition() - mUnit.getPosition(); float lookAheadTime = tothreat.length() * (1.0f / mUnit.getMaxSpeed() + threat.getSpeed()); return flee(threat.getPosition() + threat.getVelocity() * lookAheadTime); } Vector3 Steering::wander(float radius, float distance, float jitter) { mWanderTarget += Vector3(Random::clamped() * jitter, Random::clamped() * jitter, 0.0f); mWanderTarget.normalize(); mWanderTarget *= radius; Vector3 target = mUnit.getPosition() + mUnit.getVelocity().normalized() * distance + mWanderTarget; return target - mUnit.getPosition(); } Vector3 Steering::obstacleAvoidance(const std::vector<Obstacle*> obstacles) { Obstacle* nearest = nullptr; float distToNearest = FLT_MAX; if(mUnit.getVelocity().null()) return Vector3(); float minObstacleDistance = mUnit.getVelocity().length() * 0.5f; for(auto o : obstacles) { float heading = mUnit.getVelocity().dot(o->getPosition() - mUnit.getPosition()); if(heading < 0.0f) { continue; } float rad = mUnit.getRadius() + o->getRadius(); float dist = Math::pointToSegmentDistance(mUnit.getPosition(), mUnit.getPosition() + mUnit.getVelocity() * 0.5f, o->getPosition()) - rad; if(dist < distToNearest && dist < minObstacleDistance) { distToNearest = dist; nearest = o; } } if(!nearest) { return Vector3(); } Vector3 vecFromObj = Entity::vectorFromTo(*nearest, mUnit); if(vecFromObj.length() < mUnit.getRadius() + nearest->getRadius()) { // we're inside the obstacle return vecFromObj.normalized() * 100.0f; } distToNearest = std::max(0.01f, distToNearest); float velmultiplier = 0.1f + mUnit.getVelocity().length() * 0.5f; float multiplier = velmultiplier / distToNearest; Vector3 res = vecFromObj.normalized() * multiplier; return res; } Vector3 Steering::cohesion(const std::vector<Entity*> neighbours) { Vector3 centerOfMass; int count = 0; for(auto n : neighbours) { if(n == &mUnit) continue; centerOfMass += n->getPosition(); count++; } if(count) { centerOfMass *= (1.0f / count); return seek(centerOfMass); } else { return Vector3(); } } Vector3 Steering::separation(const std::vector<Entity*> neighbours) { Vector3 res; for(auto n : neighbours) { if(n == &mUnit) continue; Vector3 toMe = mUnit.getPosition() - n->getPosition(); if(toMe.null()) continue; res += toMe.normalized() / toMe.length(); } return res; } bool Steering::accumulate(Vector3& runningTotal, const Vector3& add) { float magnitude = runningTotal.length(); float remaining = mUnit.getMaxAcceleration() - magnitude; if(remaining <= 0.0f) return false; double toAdd = add.length(); if(toAdd < remaining) { runningTotal += add; return true; } else { runningTotal += add.normalized() * remaining; return false; } } Vector3 Steering::wallAvoidance(const std::vector<Wall*> walls) { Vector3 nearestPointOnWall; float distToNearest = FLT_MAX; for(auto w : walls) { bool found = false; Math::segmentSegmentIntersection2D(mUnit.getPosition(), mUnit.getPosition() + mUnit.getVelocity() * 0.5f, w->getStart(), w->getEnd(), &found); Vector3 nearest; float dist = Math::pointToSegmentDistance(w->getStart(), w->getEnd(), mUnit.getPosition(), &nearest); if(found || dist < mUnit.getMaxSpeed() * 0.5f) { if(dist < distToNearest) { distToNearest = dist; nearestPointOnWall = nearest; } } } if(distToNearest == FLT_MAX) { return Vector3(); } Vector3 vecFromPoint = mUnit.getPosition() - nearestPointOnWall; Vector3 res = vecFromPoint.normalized() * 10.0f; return res; } } <|endoftext|>
<commit_before>/******************************************************************************* * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 1 * * (c) 2006-2007 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation; either version 2.1 of the License, or (at your * * option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * * * Contact information: contact@sofa-framework.org * * * * Authors: J. Allard, P-J. Bensoussan, S. Cotin, C. Duriez, H. Delingette, * * F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, M. Nesme, P. Neumann, * * and F. Poyer * *******************************************************************************/ #if defined (WIN32) # include <windows.h> #elif defined (__linux__) # include <X11/Xlib.h> # include <X11/Xutil.h> # include <GL/glx.h> # include <GL/gl.h> #elif defined (__APPLE__) # include <OpenGL/gl.h> #endif #include <string.h> #include <sofa/helper/gl/glfont.h> #ifdef SGI_CC extern "C" Display * glXGetCurrentDisplayEXT (void); #endif namespace sofa { namespace helper { namespace gl { static GLuint LettersDL=0; #if __APPLE__ // nothing yet void glfntInit(void) {} void glfntClose(void) {} void glfntWriteBitmap(float x,float y,char *s) {} #endif #ifdef WIN32 void glfntInit(void) { HDC hdc; if (LettersDL!=0) return; hdc=wglGetCurrentDC(); SelectObject(hdc,GetStockObject(SYSTEM_FONT)); LettersDL=glGenLists(128); wglUseFontBitmaps(hdc,32,127,LettersDL+32); } void glfntClose(void) { if (LettersDL==0) return; glDeleteLists(LettersDL,128); LettersDL=0; } void glfntWriteBitmap(float x,float y,char *s) { GLint CurBase; if (LettersDL==0) return; glRasterPos2f(x,y); glGetIntegerv(GL_LIST_BASE,&CurBase); glListBase(LettersDL); glCallLists(strlen(s),GL_UNSIGNED_BYTE,s); glListBase(CurBase); } #endif // WIN32 #ifdef __linux__ static unsigned int last; void glfntInit(void) { Display *dpy; XFontStruct *fontInfo; Font id; unsigned int first; if (LettersDL!=0) return; #ifdef SGI_CC dpy=glXGetCurrentDisplayEXT(); #else dpy=glXGetCurrentDisplay(); #endif if (dpy==NULL) return; fontInfo = XLoadQueryFont(dpy, "-adobe-times-medium-r-normal--17-120-100-100-p-88-iso8859-1"); if (fontInfo == NULL) return; id = fontInfo->fid; first = fontInfo->min_char_or_byte2; last = fontInfo->max_char_or_byte2; if (first<32) first=32; if (last>127) last=127; LettersDL=glGenLists(last+1); if (LettersDL==0) return; glXUseXFont(id, first, last-first+1, LettersDL+first); } void glfntClose(void) { if (LettersDL==0) return; glDeleteLists(LettersDL,last+1); LettersDL=0; } void glfntWriteBitmap(float x,float y,char *s) { GLint CurBase; if (LettersDL==0) return; glRasterPos2f(x,y); glGetIntegerv(GL_LIST_BASE,&CurBase); glListBase(LettersDL); glCallLists(strlen(s),GL_UNSIGNED_BYTE,s); glListBase(CurBase); } #endif // __linux__ } // namespace gl } // namespace helper } // namespace sofa <commit_msg>r1551/sofa-dev : FIX compilation on Windows<commit_after>/******************************************************************************* * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 1 * * (c) 2006-2007 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation; either version 2.1 of the License, or (at your * * option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * * * Contact information: contact@sofa-framework.org * * * * Authors: J. Allard, P-J. Bensoussan, S. Cotin, C. Duriez, H. Delingette, * * F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, M. Nesme, P. Neumann, * * and F. Poyer * *******************************************************************************/ #if defined (WIN32) # include <windows.h> # include <GL/gl.h> #elif defined (__linux__) # include <X11/Xlib.h> # include <X11/Xutil.h> # include <GL/glx.h> # include <GL/gl.h> #elif defined (__APPLE__) # include <OpenGL/gl.h> #endif #include <string.h> #include <sofa/helper/gl/glfont.h> #ifdef SGI_CC extern "C" Display * glXGetCurrentDisplayEXT (void); #endif namespace sofa { namespace helper { namespace gl { static GLuint LettersDL=0; #if __APPLE__ // nothing yet void glfntInit(void) {} void glfntClose(void) {} void glfntWriteBitmap(float x,float y,char *s) {} #endif #ifdef WIN32 void glfntInit(void) { HDC hdc; if (LettersDL!=0) return; hdc=wglGetCurrentDC(); SelectObject(hdc,GetStockObject(SYSTEM_FONT)); LettersDL=glGenLists(128); wglUseFontBitmaps(hdc,32,127,LettersDL+32); } void glfntClose(void) { if (LettersDL==0) return; glDeleteLists(LettersDL,128); LettersDL=0; } void glfntWriteBitmap(float x,float y,char *s) { GLint CurBase; if (LettersDL==0) return; glRasterPos2f(x,y); glGetIntegerv(GL_LIST_BASE,&CurBase); glListBase(LettersDL); glCallLists(strlen(s),GL_UNSIGNED_BYTE,s); glListBase(CurBase); } #endif // WIN32 #ifdef __linux__ static unsigned int last; void glfntInit(void) { Display *dpy; XFontStruct *fontInfo; Font id; unsigned int first; if (LettersDL!=0) return; #ifdef SGI_CC dpy=glXGetCurrentDisplayEXT(); #else dpy=glXGetCurrentDisplay(); #endif if (dpy==NULL) return; fontInfo = XLoadQueryFont(dpy, "-adobe-times-medium-r-normal--17-120-100-100-p-88-iso8859-1"); if (fontInfo == NULL) return; id = fontInfo->fid; first = fontInfo->min_char_or_byte2; last = fontInfo->max_char_or_byte2; if (first<32) first=32; if (last>127) last=127; LettersDL=glGenLists(last+1); if (LettersDL==0) return; glXUseXFont(id, first, last-first+1, LettersDL+first); } void glfntClose(void) { if (LettersDL==0) return; glDeleteLists(LettersDL,last+1); LettersDL=0; } void glfntWriteBitmap(float x,float y,char *s) { GLint CurBase; if (LettersDL==0) return; glRasterPos2f(x,y); glGetIntegerv(GL_LIST_BASE,&CurBase); glListBase(LettersDL); glCallLists(strlen(s),GL_UNSIGNED_BYTE,s); glListBase(CurBase); } #endif // __linux__ } // namespace gl } // namespace helper } // namespace sofa <|endoftext|>
<commit_before>// RUN: cat %s | %cling | FileCheck %s // Test Interpreter::lookupScope() #include "cling/Interpreter/Interpreter.h" #include "clang/AST/Type.h" typedef int Int_t; .rawInput 1 template <typename T> struct W { T member; }; .rawInput 0 const clang::Type* resType = 0; gCling->lookupScope("W<Int_t>", &resType); //resType->dump(); clang::QualType(resType,0).getAsString().c_str() //CHECK: (const char * const) "W<Int_t>" <commit_msg>Test looking up a class in a nested namespace scope.<commit_after>// RUN: cat %s | %cling 2>&1 | FileCheck %s // Test Interpreter::lookupScope() #include "cling/Interpreter/Interpreter.h" #include "clang/AST/Decl.h" #include "clang/AST/Type.h" #include "llvm/Support/Casting.h" #include <cstdio> using namespace std; .rawInput 1 class A {}; .rawInput 0 const clang::Decl* cl_A = gCling->lookupScope("A"); printf("cl_A: 0x%lx\n", (unsigned long) cl_A); //CHECK: cl_A: 0x{{[1-9a-f][0-9a-f]*$}} llvm::cast<clang::NamedDecl>(cl_A)->getQualifiedNameAsString().c_str() //CHECK-NEXT: (const char * const) "A" .rawInput 1 namespace N { class A {}; } .rawInput 0 const clang::Decl* cl_A_in_N = gCling->lookupScope("N::A"); printf("cl_A_in_N: 0x%lx\n", (unsigned long) cl_A_in_N); //CHECK: cl_A_in_N: 0x{{[1-9a-f][0-9a-f]*$}} llvm::cast<clang::NamedDecl>(cl_A_in_N)->getQualifiedNameAsString().c_str() //CHECK-NEXT: (const char * const) "N::A" .rawInput 1 namespace N { namespace M { namespace P { class A {}; } } } .rawInput 0 const clang::Decl* cl_A_in_NMP = gCling->lookupScope("N::M::P::A"); cl_A_in_NMP //CHECK: (const clang::Decl *) 0x{{[1-9a-f][0-9a-f]*$}} llvm::cast<clang::NamedDecl>(cl_A_in_NMP)->getQualifiedNameAsString().c_str() //CHECK-NEXT: (const char * const) "N::M::P::A" .rawInput 1 template <class T> class B { T b; }; .rawInput 0 const clang::Decl* cl_B_int = gCling->lookupScope("B<int>"); printf("cl_B_int: 0x%lx\n", (unsigned long) cl_B_int); //CHECK-NEXT: cl_B_int: 0x{{[1-9a-f][0-9a-f]*$}} // // Test optional returned type is as spelled by the user. // typedef int Int_t; .rawInput 1 template <typename T> struct W { T member; }; .rawInput 0 const clang::Type* resType = 0; gCling->lookupScope("W<Int_t>", &resType); //resType->dump(); clang::QualType(resType,0).getAsString().c_str() //CHECK-NEXT: (const char * const) "W<Int_t>" <|endoftext|>
<commit_before>// // TSLogger.hpp // cppcommon // // Created by Sean Grimes on 12/28/16. // Copyright © 2016 Sean Grimes. All rights reserved. // #pragma once /** \brief Use FUNC to pass function name \details FUNC is defined as __PRETTY_FUNCTION__ and will pass the function name to the logger when the logger is called. This is always an optional variable on logging fucntions */ #define FUNC __PRETTY_FUNCTION__ #include <string> #include <sstream> #include <fstream> #include <ctime> #include <chrono> #include <iomanip> #include <cstdlib> #include <thread> #include "tsqueue.hpp" /** \brief Log message type used by the logger \author Sean Grimes, spg63@cs.drexel.edu \date 12-27-16 */ struct logmessage_t{ logmessage_t() = default; logmessage_t(const std::string& message_to_be_logged, const std::string &function_name, const std::string &type) : message_to_be_logged_(message_to_be_logged) , function_name_(function_name) , log_message_type_(type) {} std::string message_to_be_logged_; std::string function_name_; std::string log_message_type_; }; /** \brief Thread safe async logger for c++ \details Uses a single background thread, pulling from an internal queue, to write messages to log file. It will automatically add timestamps to the messages. Writing to the log file is not buffered (outside of the queue), messages are written one at a time in an attempt to have complete logs if the event of an unhandled exception. Buffering may be implmented in the future. \n FUNC is a defined macro that can be (optionally) passed to all logging functions to display the calling function name in the log message. \author Sean Grimes, spg63@cs.drexel.edu \date 12-28-16 */ class TSLogger{ public: /** \brief default c'tor \details By default logs are written to "log.txt" in the CWD, and the backing queue using a timeout of 10 milliseconds */ TSLogger() : TSLogger("log.txt", std::chrono::milliseconds(10)) {} /** \brief custom log file c'tor \details Write to logfile of your choice, backing queue timeout is 10 milliseconds @param logFile The log file */ TSLogger(std::string logFile) : TSLogger(logFile, std::chrono::milliseconds(10)) {} /** \brief Your choice c'tor \details Set log file and backing queue timeout @param logFile The log file @param queue_cond_var_time Timeout for backing queue, std::chrono::milliseconds */ TSLogger(std::string logFile, std::chrono::milliseconds queue_cond_var_timeout) : logFile_(logFile) , timeout_(queue_cond_var_timeout) { consumer_ = std::thread(&TSLogger::pop_and_write, this); } TSLogger(const TSLogger &) = delete; TSLogger(const TSLogger &&) = delete; void operator=(const TSLogger &) = delete; void operator=(const TSLogger &&) = delete; ~TSLogger(){ stop_logging_ = true; if(consumer_.joinable()) consumer_.join(); #ifdef PRINT_LIB_ERRORS else fprintf(stderr, "Logger thread is not joinable\n"); #endif } /** \brief Clear log file of previous messages */ void deletePreviousMessagesInLogFile(){ std::ofstream out(logFile_, std::ios::out); out << "" << std::flush; } /** \brief Immediately kill logger \details Unwritten log messages will be lost */ void kill(){ kill_ = true; } /** \brief info messages @param msg The log message @param func_name Optional - name of function where message was logged from, passed to logger by using 'FUNC' macro...e.g. logger.info("message", FUNC); */ template <class MSG_T> void info(const MSG_T &msg, const std::string &func_name = ""){ form_and_push(msg, func_name, "INFO"); } /** \brief debug messages @param msg The log message @param func_name Optional - name of function where message was logged from, passed to logger by using 'FUNC' macro...e.g. logger.info("message", FUNC); */ template <class MSG_T> void debug(const MSG_T &msg, const std::string &func_name = ""){ form_and_push(msg, func_name, "DEBUG"); } /** \brief warning messages @param msg The log message @param func_name Optional - name of function where message was logged from, passed to logger by using 'FUNC' macro...e.g. logger.info("message", FUNC); */ template <class MSG_T> void warn(const MSG_T &msg, const std::string &func_name = ""){ form_and_push(msg, func_name, "WARNING"); } /** \brief error messages @param msg The log message @param func_name Optional - name of function where message was logged from, passed to logger by using 'FUNC' macro...e.g. logger.info("message", FUNC); */ template <class MSG_T> void error(const MSG_T &msg, const std::string &func_name = ""){ form_and_push(msg, func_name, "ERROR"); } /** \brief fatal messages @param msg The log message @param func_name Optional - name of function where message was logged from, passed to logger by using 'FUNC' macro...e.g. logger.info("message", FUNC); */ template <class MSG_T> void fatal(const MSG_T &msg, const std::string &func_name = ""){ form_and_push(msg, func_name, "FATAL"); } private: std::string logFile_; TSQueue<logmessage_t> msg_queue_; volatile bool stop_logging_{false}; volatile bool kill_{false}; std::thread consumer_; std::chrono::milliseconds timeout_{10}; std::string timeStamp(){ auto now = std::chrono::system_clock::now(); auto count = std::chrono::system_clock::to_time_t(now); auto secs = std::chrono::time_point_cast<std::chrono::seconds>(now); auto partial = now - secs; auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(partial); std::stringstream ss; ss << std::put_time(std::localtime(&count), "%Y-%m-%d %X"); ss << "." << ms.count(); return ss.str(); } void pop_and_write(){ // Main loop for the logger thread, will check queue for messages and write them while(true){ // Use try_and_pop instead of wait_and_pop so the thread can be immediately killed // if necessary; wait_and_pop will block on the thread while the queue is empty logmessage_t msg; bool did_receive_message{false}; did_receive_message = msg_queue_.try_and_pop(msg, timeout_); // Process the received message and write it to the log file if(did_receive_message){ std::string time_str = timeStamp(); std::string fnamestr = ""; if(msg.function_name_ != "") fnamestr = msg.function_name_; if(fnamestr != "") fnamestr += ": "; std::string type{msg.log_message_type_}; std::stringstream ss; ss << time_str << " " << type << ": " << fnamestr; ss << msg.message_to_be_logged_ << '\n'; std::ofstream out(logFile_, std::ios::out | std::ios::app); out << ss.str() << std::flush; } // stop_logging_ set to true in d'tor, keep pulling messages until queue is empty if(stop_logging_ && msg_queue_.empty()) break; // kill_ allows for immediate thread death regardless of messages already in queue if(kill_) break; } } template <class MSG_T> void form_and_push(const MSG_T &msg, const std::string &fname, const std::string &type){ if(stop_logging_ || kill_){ #ifdef PRINT_LIB_ERRORS fprintf(stderr, "Tried to log after destruction or kill order\n"); #endif return; } std::stringstream ss; if(!(ss << msg)){ #ifdef PRINT_LIB_ERRORS fprintf(stderr, "LOGGING ERROR - will attempt to log it\n"); return error("LOGGING ERROR: ", FUNC); #endif return; } msg_queue_.push({ss.str(), fname, type}); } }; <commit_msg>fixed typo in TSLogger.hpp<commit_after>// // TSLogger.hpp // cppcommon // // Created by Sean Grimes on 12/28/16. // Copyright © 2016 Sean Grimes. All rights reserved. // #pragma once /** \brief Use FUNC to pass function name \details FUNC is defined as __PRETTY_FUNCTION__ and will pass the function name to the logger when the logger is called. This is always an optional variable on logging fucntions */ #define FUNC __PRETTY_FUNCTION__ #include <string> #include <sstream> #include <fstream> #include <ctime> #include <chrono> #include <iomanip> #include <cstdlib> #include <thread> #include "TSQueue.hpp" /** \brief Log message type used by the logger \author Sean Grimes, spg63@cs.drexel.edu \date 12-27-16 */ struct logmessage_t{ logmessage_t() = default; logmessage_t(const std::string& message_to_be_logged, const std::string &function_name, const std::string &type) : message_to_be_logged_(message_to_be_logged) , function_name_(function_name) , log_message_type_(type) {} std::string message_to_be_logged_; std::string function_name_; std::string log_message_type_; }; /** \brief Thread safe async logger for c++ \details Uses a single background thread, pulling from an internal queue, to write messages to log file. It will automatically add timestamps to the messages. Writing to the log file is not buffered (outside of the queue), messages are written one at a time in an attempt to have complete logs if the event of an unhandled exception. Buffering may be implmented in the future. \n FUNC is a defined macro that can be (optionally) passed to all logging functions to display the calling function name in the log message. \author Sean Grimes, spg63@cs.drexel.edu \date 12-28-16 */ class TSLogger{ public: /** \brief default c'tor \details By default logs are written to "log.txt" in the CWD, and the backing queue using a timeout of 10 milliseconds */ TSLogger() : TSLogger("log.txt", std::chrono::milliseconds(10)) {} /** \brief custom log file c'tor \details Write to logfile of your choice, backing queue timeout is 10 milliseconds @param logFile The log file */ TSLogger(std::string logFile) : TSLogger(logFile, std::chrono::milliseconds(10)) {} /** \brief Your choice c'tor \details Set log file and backing queue timeout @param logFile The log file @param queue_cond_var_time Timeout for backing queue, std::chrono::milliseconds */ TSLogger(std::string logFile, std::chrono::milliseconds queue_cond_var_timeout) : logFile_(logFile) , timeout_(queue_cond_var_timeout) { consumer_ = std::thread(&TSLogger::pop_and_write, this); } TSLogger(const TSLogger &) = delete; TSLogger(const TSLogger &&) = delete; void operator=(const TSLogger &) = delete; void operator=(const TSLogger &&) = delete; ~TSLogger(){ stop_logging_ = true; if(consumer_.joinable()) consumer_.join(); #ifdef PRINT_LIB_ERRORS else fprintf(stderr, "Logger thread is not joinable\n"); #endif } /** \brief Clear log file of previous messages */ void deletePreviousMessagesInLogFile(){ std::ofstream out(logFile_, std::ios::out); out << "" << std::flush; } /** \brief Immediately kill logger \details Unwritten log messages will be lost */ void kill(){ kill_ = true; } /** \brief info messages @param msg The log message @param func_name Optional - name of function where message was logged from, passed to logger by using 'FUNC' macro...e.g. logger.info("message", FUNC); */ template <class MSG_T> void info(const MSG_T &msg, const std::string &func_name = ""){ form_and_push(msg, func_name, "INFO"); } /** \brief debug messages @param msg The log message @param func_name Optional - name of function where message was logged from, passed to logger by using 'FUNC' macro...e.g. logger.info("message", FUNC); */ template <class MSG_T> void debug(const MSG_T &msg, const std::string &func_name = ""){ form_and_push(msg, func_name, "DEBUG"); } /** \brief warning messages @param msg The log message @param func_name Optional - name of function where message was logged from, passed to logger by using 'FUNC' macro...e.g. logger.info("message", FUNC); */ template <class MSG_T> void warn(const MSG_T &msg, const std::string &func_name = ""){ form_and_push(msg, func_name, "WARNING"); } /** \brief error messages @param msg The log message @param func_name Optional - name of function where message was logged from, passed to logger by using 'FUNC' macro...e.g. logger.info("message", FUNC); */ template <class MSG_T> void error(const MSG_T &msg, const std::string &func_name = ""){ form_and_push(msg, func_name, "ERROR"); } /** \brief fatal messages @param msg The log message @param func_name Optional - name of function where message was logged from, passed to logger by using 'FUNC' macro...e.g. logger.info("message", FUNC); */ template <class MSG_T> void fatal(const MSG_T &msg, const std::string &func_name = ""){ form_and_push(msg, func_name, "FATAL"); } private: std::string logFile_; TSQueue<logmessage_t> msg_queue_; volatile bool stop_logging_{false}; volatile bool kill_{false}; std::thread consumer_; std::chrono::milliseconds timeout_{10}; std::string timeStamp(){ auto now = std::chrono::system_clock::now(); auto count = std::chrono::system_clock::to_time_t(now); auto secs = std::chrono::time_point_cast<std::chrono::seconds>(now); auto partial = now - secs; auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(partial); std::stringstream ss; ss << std::put_time(std::localtime(&count), "%Y-%m-%d %X"); ss << "." << ms.count(); return ss.str(); } void pop_and_write(){ // Main loop for the logger thread, will check queue for messages and write them while(true){ // Use try_and_pop instead of wait_and_pop so the thread can be immediately killed // if necessary; wait_and_pop will block on the thread while the queue is empty logmessage_t msg; bool did_receive_message{false}; did_receive_message = msg_queue_.try_and_pop(msg, timeout_); // Process the received message and write it to the log file if(did_receive_message){ std::string time_str = timeStamp(); std::string fnamestr = ""; if(msg.function_name_ != "") fnamestr = msg.function_name_; if(fnamestr != "") fnamestr += ": "; std::string type{msg.log_message_type_}; std::stringstream ss; ss << time_str << " " << type << ": " << fnamestr; ss << msg.message_to_be_logged_ << '\n'; std::ofstream out(logFile_, std::ios::out | std::ios::app); out << ss.str() << std::flush; } // stop_logging_ set to true in d'tor, keep pulling messages until queue is empty if(stop_logging_ && msg_queue_.empty()) break; // kill_ allows for immediate thread death regardless of messages already in queue if(kill_) break; } } template <class MSG_T> void form_and_push(const MSG_T &msg, const std::string &fname, const std::string &type){ if(stop_logging_ || kill_){ #ifdef PRINT_LIB_ERRORS fprintf(stderr, "Tried to log after destruction or kill order\n"); #endif return; } std::stringstream ss; if(!(ss << msg)){ #ifdef PRINT_LIB_ERRORS fprintf(stderr, "LOGGING ERROR - will attempt to log it\n"); return error("LOGGING ERROR: ", FUNC); #endif return; } msg_queue_.push({ss.str(), fname, type}); } }; <|endoftext|>
<commit_before>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "GlobalSignalNumbers.h" #include "signaldata/SignalDataPrint.hpp" #include "signaldata/TcKeyReq.hpp" #include "signaldata/TcKeyConf.hpp" #include "signaldata/TcKeyRef.hpp" #include "signaldata/LqhKey.hpp" #include "signaldata/TupKey.hpp" #include "signaldata/TupCommit.hpp" #include "signaldata/FsOpenReq.hpp" #include "signaldata/FsCloseReq.hpp" #include "signaldata/FsReadWriteReq.hpp" #include "signaldata/FsRef.hpp" #include "signaldata/FsConf.hpp" #include "signaldata/CloseComReqConf.hpp" #include "signaldata/PackedSignal.hpp" #include "signaldata/PrepFailReqRef.hpp" #include "signaldata/DictTabInfo.hpp" #include "signaldata/AlterTable.hpp" #include "signaldata/AlterTab.hpp" #include "signaldata/CreateTrig.hpp" #include "signaldata/AlterTrig.hpp" #include "signaldata/DropTrig.hpp" #include "signaldata/FireTrigOrd.hpp" #include "signaldata/TrigAttrInfo.hpp" #include "signaldata/CreateIndx.hpp" #include "signaldata/AlterIndx.hpp" #include "signaldata/DropIndx.hpp" #include "signaldata/TcIndx.hpp" #include "signaldata/IndxKeyInfo.hpp" #include "signaldata/IndxAttrInfo.hpp" #include <signaldata/FsAppendReq.hpp> #include <signaldata/BackupSignalData.hpp> #include <signaldata/BackupImpl.hpp> #include <signaldata/UtilSequence.hpp> #include <signaldata/UtilPrepare.hpp> #include <signaldata/UtilExecute.hpp> #include <signaldata/ScanTab.hpp> #include <signaldata/ScanFrag.hpp> #include <signaldata/LqhFrag.hpp> #include <signaldata/LqhTransConf.hpp> #include <signaldata/DropTab.hpp> #include <signaldata/PrepDropTab.hpp> #include <signaldata/LCP.hpp> #include <signaldata/MasterLCP.hpp> #include <signaldata/CopyGCIReq.hpp> #include <signaldata/SystemError.hpp> #include <signaldata/StartRec.hpp> #include <signaldata/NFCompleteRep.hpp> #include <signaldata/SignalDroppedRep.hpp> #include <signaldata/FailRep.hpp> #include <signaldata/DisconnectRep.hpp> #include <signaldata/SumaImpl.hpp> #include <signaldata/NdbSttor.hpp> #include <signaldata/CreateFragmentation.hpp> #include <signaldata/UtilLock.hpp> #include <signaldata/CntrStart.hpp> #include <signaldata/ReadNodesConf.hpp> #include <signaldata/TuxMaint.hpp> #include <signaldata/AccLock.hpp> /** * This is the register */ const NameFunctionPair SignalDataPrintFunctions[] = { { GSN_TCKEYREQ, printTCKEYREQ }, { GSN_TCKEYCONF, printTCKEYCONF }, { GSN_TCKEYREF, printTCKEYREF }, { GSN_LQHKEYREQ, printLQHKEYREQ }, { GSN_LQHKEYCONF, printLQHKEYCONF }, { GSN_LQHKEYREF, printLQHKEYREF }, { GSN_TUPKEYREQ, printTUPKEYREQ }, { GSN_TUPKEYCONF, printTUPKEYCONF }, { GSN_TUPKEYREF, printTUPKEYREF }, { GSN_TUP_COMMITREQ, printTUPCOMMITREQ }, { GSN_CONTINUEB, printCONTINUEB }, { GSN_FSOPENREQ, printFSOPENREQ }, { GSN_FSCLOSEREQ, printFSCLOSEREQ }, { GSN_FSREADREQ, printFSREADWRITEREQ }, { GSN_FSWRITEREQ, printFSREADWRITEREQ }, { GSN_FSCLOSEREF, printFSREF }, { GSN_FSOPENREF, printFSREF }, { GSN_FSWRITEREF, printFSREF }, { GSN_FSREADREF, printFSREF }, { GSN_FSSYNCREF, printFSREF }, { GSN_FSCLOSECONF, printFSCONF }, { GSN_FSOPENCONF, printFSCONF }, { GSN_FSWRITECONF, printFSCONF }, { GSN_FSREADCONF, printFSCONF }, { GSN_FSSYNCCONF, printFSCONF }, { GSN_CLOSE_COMREQ, printCLOSECOMREQCONF }, { GSN_CLOSE_COMCONF, printCLOSECOMREQCONF }, { GSN_PACKED_SIGNAL, printPACKED_SIGNAL }, { GSN_PREP_FAILREQ, printPREPFAILREQREF }, { GSN_PREP_FAILREF, printPREPFAILREQREF }, { GSN_ALTER_TABLE_REQ, printALTER_TABLE_REQ }, { GSN_ALTER_TABLE_CONF, printALTER_TABLE_CONF }, { GSN_ALTER_TABLE_REF, printALTER_TABLE_REF }, { GSN_ALTER_TAB_REQ, printALTER_TAB_REQ }, { GSN_ALTER_TAB_CONF, printALTER_TAB_CONF }, { GSN_ALTER_TAB_REF, printALTER_TAB_REF }, { GSN_CREATE_TRIG_REQ, printCREATE_TRIG_REQ }, { GSN_CREATE_TRIG_CONF, printCREATE_TRIG_CONF }, { GSN_CREATE_TRIG_REF, printCREATE_TRIG_REF }, { GSN_ALTER_TRIG_REQ, printALTER_TRIG_REQ }, { GSN_ALTER_TRIG_CONF, printALTER_TRIG_CONF }, { GSN_ALTER_TRIG_REF, printALTER_TRIG_REF }, { GSN_DROP_TRIG_REQ, printDROP_TRIG_REQ }, { GSN_DROP_TRIG_CONF, printDROP_TRIG_CONF }, { GSN_DROP_TRIG_REF, printDROP_TRIG_REF }, { GSN_FIRE_TRIG_ORD, printFIRE_TRIG_ORD }, { GSN_TRIG_ATTRINFO, printTRIG_ATTRINFO }, { GSN_CREATE_INDX_REQ, printCREATE_INDX_REQ }, { GSN_CREATE_INDX_CONF, printCREATE_INDX_CONF }, { GSN_CREATE_INDX_REF, printCREATE_INDX_REF }, { GSN_DROP_INDX_REQ, printDROP_INDX_REQ }, { GSN_DROP_INDX_CONF, printDROP_INDX_CONF }, { GSN_DROP_INDX_REF, printDROP_INDX_REF }, { GSN_ALTER_INDX_REQ, printALTER_INDX_REQ }, { GSN_ALTER_INDX_CONF, printALTER_INDX_CONF }, { GSN_ALTER_INDX_REF, printALTER_INDX_REF }, { GSN_TCINDXREQ, printTCINDXREQ }, { GSN_TCINDXCONF, printTCINDXCONF }, { GSN_TCINDXREF, printTCINDXREF }, { GSN_INDXKEYINFO, printINDXKEYINFO }, { GSN_INDXATTRINFO, printINDXATTRINFO }, //{ GSN_TCINDXNEXTREQ, printTCINDXNEXTREQ }, //{ GSN_TCINDEXNEXTCONF, printTCINDEXNEXTCONF }, //{ GSN_TCINDEXNEXREF, printTCINDEXNEXREF }, { GSN_FSAPPENDREQ, printFSAPPENDREQ }, { GSN_BACKUP_REQ, printBACKUP_REQ }, { GSN_BACKUP_DATA, printBACKUP_DATA }, { GSN_BACKUP_REF, printBACKUP_REF }, { GSN_BACKUP_CONF, printBACKUP_CONF }, { GSN_ABORT_BACKUP_ORD, printABORT_BACKUP_ORD }, { GSN_BACKUP_ABORT_REP, printBACKUP_ABORT_REP }, { GSN_BACKUP_COMPLETE_REP, printBACKUP_COMPLETE_REP }, { GSN_BACKUP_NF_COMPLETE_REP, printBACKUP_NF_COMPLETE_REP }, { GSN_DEFINE_BACKUP_REQ, printDEFINE_BACKUP_REQ }, { GSN_DEFINE_BACKUP_REF, printDEFINE_BACKUP_REF }, { GSN_DEFINE_BACKUP_CONF, printDEFINE_BACKUP_CONF }, { GSN_START_BACKUP_REQ, printSTART_BACKUP_REQ }, { GSN_START_BACKUP_REF, printSTART_BACKUP_REF }, { GSN_START_BACKUP_CONF, printSTART_BACKUP_CONF }, { GSN_BACKUP_FRAGMENT_REQ, printBACKUP_FRAGMENT_REQ }, { GSN_BACKUP_FRAGMENT_REF, printBACKUP_FRAGMENT_REF }, { GSN_BACKUP_FRAGMENT_CONF, printBACKUP_FRAGMENT_CONF }, { GSN_STOP_BACKUP_REQ, printSTOP_BACKUP_REQ }, { GSN_STOP_BACKUP_REF, printSTOP_BACKUP_REF }, { GSN_STOP_BACKUP_CONF, printSTOP_BACKUP_CONF }, { GSN_BACKUP_STATUS_REQ, printBACKUP_STATUS_REQ }, //{ GSN_BACKUP_STATUS_REF, printBACKUP_STATUS_REF }, { GSN_BACKUP_STATUS_CONF, printBACKUP_STATUS_CONF }, { GSN_UTIL_SEQUENCE_REQ, printUTIL_SEQUENCE_REQ }, { GSN_UTIL_SEQUENCE_REF, printUTIL_SEQUENCE_REF }, { GSN_UTIL_SEQUENCE_CONF, printUTIL_SEQUENCE_CONF }, { GSN_UTIL_PREPARE_REQ, printUTIL_PREPARE_REQ }, { GSN_UTIL_PREPARE_REF, printUTIL_PREPARE_REF }, { GSN_UTIL_PREPARE_CONF, printUTIL_PREPARE_CONF }, { GSN_UTIL_EXECUTE_REQ, printUTIL_EXECUTE_REQ }, { GSN_UTIL_EXECUTE_REF, printUTIL_EXECUTE_REF }, { GSN_UTIL_EXECUTE_CONF, printUTIL_EXECUTE_CONF }, { GSN_SCAN_TABREQ, printSCANTABREQ }, { GSN_SCAN_TABCONF, printSCANTABCONF }, { GSN_SCAN_TABREF, printSCANTABREF }, { GSN_SCAN_NEXTREQ, printSCANNEXTREQ }, { GSN_LQHFRAGREQ, printLQH_FRAG_REQ }, { GSN_LQHFRAGREF, printLQH_FRAG_REF }, { GSN_LQHFRAGCONF, printLQH_FRAG_CONF }, { GSN_PREP_DROP_TAB_REQ, printPREP_DROP_TAB_REQ }, { GSN_PREP_DROP_TAB_REF, printPREP_DROP_TAB_REF }, { GSN_PREP_DROP_TAB_CONF, printPREP_DROP_TAB_CONF }, { GSN_DROP_TAB_REQ, printDROP_TAB_REQ }, { GSN_DROP_TAB_REF, printDROP_TAB_REF }, { GSN_DROP_TAB_CONF, printDROP_TAB_CONF }, { GSN_LCP_FRAG_ORD, printLCP_FRAG_ORD }, { GSN_LCP_FRAG_REP, printLCP_FRAG_REP }, { GSN_LCP_COMPLETE_REP, printLCP_COMPLETE_REP }, { GSN_START_LCP_REQ, printSTART_LCP_REQ }, { GSN_START_LCP_CONF, printSTART_LCP_CONF }, { GSN_MASTER_LCPREQ, printMASTER_LCP_REQ }, { GSN_MASTER_LCPREF, printMASTER_LCP_REF }, { GSN_MASTER_LCPCONF, printMASTER_LCP_CONF }, { GSN_COPY_GCIREQ, printCOPY_GCI_REQ }, { GSN_SYSTEM_ERROR, printSYSTEM_ERROR }, { GSN_START_RECREQ, printSTART_REC_REQ }, { GSN_START_RECCONF, printSTART_REC_CONF }, { GSN_NF_COMPLETEREP, printNF_COMPLETE_REP }, { GSN_SIGNAL_DROPPED_REP, printSIGNAL_DROPPED_REP }, { GSN_FAIL_REP, printFAIL_REP }, { GSN_DISCONNECT_REP, printDISCONNECT_REP }, { GSN_SUB_CREATE_REQ, printSUB_CREATE_REQ }, //{ GSN_SUB_CREATE_REF, printSUB_CREATE_REF }, { GSN_SUB_CREATE_CONF, printSUB_CREATE_CONF }, { GSN_SUB_START_REQ, printSUB_START_REQ }, { GSN_SUB_START_REF, printSUB_START_REF }, { GSN_SUB_START_CONF, printSUB_START_CONF }, { GSN_SUB_SYNC_REQ, printSUB_SYNC_REQ }, { GSN_SUB_SYNC_REF, printSUB_SYNC_REF }, { GSN_SUB_SYNC_CONF, printSUB_SYNC_CONF }, { GSN_SUB_META_DATA, printSUB_META_DATA }, { GSN_SUB_TABLE_DATA, printSUB_TABLE_DATA }, { GSN_SUB_SYNC_CONTINUE_REQ, printSUB_SYNC_CONTINUE_REQ }, { GSN_SUB_SYNC_CONTINUE_REF, printSUB_SYNC_CONTINUE_REF }, { GSN_SUB_SYNC_CONTINUE_CONF, printSUB_SYNC_CONTINUE_CONF }, { GSN_SUB_GCP_COMPLETE_REP, printSUB_GCP_COMPLETE_REP } ,{ GSN_CREATE_FRAGMENTATION_REQ, printCREATE_FRAGMENTATION_REQ } ,{ GSN_CREATE_FRAGMENTATION_REF, printCREATE_FRAGMENTATION_REF } ,{ GSN_CREATE_FRAGMENTATION_CONF, printCREATE_FRAGMENTATION_CONF } ,{ GSN_UTIL_CREATE_LOCK_REQ, printUTIL_CREATE_LOCK_REQ } ,{ GSN_UTIL_CREATE_LOCK_REF, printUTIL_CREATE_LOCK_REF } ,{ GSN_UTIL_CREATE_LOCK_CONF, printUTIL_CREATE_LOCK_CONF } ,{ GSN_UTIL_DESTROY_LOCK_REQ, printUTIL_DESTROY_LOCK_REQ } ,{ GSN_UTIL_DESTROY_LOCK_REF, printUTIL_DESTROY_LOCK_REF } ,{ GSN_UTIL_DESTROY_LOCK_CONF, printUTIL_DESTROY_LOCK_CONF } ,{ GSN_UTIL_LOCK_REQ, printUTIL_LOCK_REQ } ,{ GSN_UTIL_LOCK_REF, printUTIL_LOCK_REF } ,{ GSN_UTIL_LOCK_CONF, printUTIL_LOCK_CONF } ,{ GSN_UTIL_UNLOCK_REQ, printUTIL_UNLOCK_REQ } ,{ GSN_UTIL_UNLOCK_REF, printUTIL_UNLOCK_REF } ,{ GSN_UTIL_UNLOCK_CONF, printUTIL_UNLOCK_CONF } ,{ GSN_CNTR_START_REQ, printCNTR_START_REQ } ,{ GSN_CNTR_START_REF, printCNTR_START_REF } ,{ GSN_CNTR_START_CONF, printCNTR_START_CONF } ,{ GSN_READ_NODESCONF, printREAD_NODES_CONF } ,{ GSN_TUX_MAINT_REQ, printTUX_MAINT_REQ } ,{ GSN_ACC_LOCKREQ, printACC_LOCKREQ } ,{ GSN_LQH_TRANSCONF, printLQH_TRANSCONF } ,{ GSN_SCAN_FRAGREQ, printSCAN_FRAGREQ } ,{ 0, 0 } }; template struct BitmaskPOD<1>; template struct BitmaskPOD<2>; template struct BitmaskPOD<4>; template class Bitmask<1>; template class Bitmask<2>; template class Bitmask<4>; <commit_msg>ndb: compile fix for hpita2-64 bit - remove a bunch of includes<commit_after>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <GlobalSignalNumbers.h> #include <signaldata/SignalData.hpp> #include <signaldata/SignalDataPrint.hpp> /** * This is the register */ const NameFunctionPair SignalDataPrintFunctions[] = { { GSN_TCKEYREQ, printTCKEYREQ }, { GSN_TCKEYCONF, printTCKEYCONF }, { GSN_TCKEYREF, printTCKEYREF }, { GSN_LQHKEYREQ, printLQHKEYREQ }, { GSN_LQHKEYCONF, printLQHKEYCONF }, { GSN_LQHKEYREF, printLQHKEYREF }, { GSN_TUPKEYREQ, printTUPKEYREQ }, { GSN_TUPKEYCONF, printTUPKEYCONF }, { GSN_TUPKEYREF, printTUPKEYREF }, { GSN_TUP_COMMITREQ, printTUPCOMMITREQ }, { GSN_CONTINUEB, printCONTINUEB }, { GSN_FSOPENREQ, printFSOPENREQ }, { GSN_FSCLOSEREQ, printFSCLOSEREQ }, { GSN_FSREADREQ, printFSREADWRITEREQ }, { GSN_FSWRITEREQ, printFSREADWRITEREQ }, { GSN_FSCLOSEREF, printFSREF }, { GSN_FSOPENREF, printFSREF }, { GSN_FSWRITEREF, printFSREF }, { GSN_FSREADREF, printFSREF }, { GSN_FSSYNCREF, printFSREF }, { GSN_FSCLOSECONF, printFSCONF }, { GSN_FSOPENCONF, printFSCONF }, { GSN_FSWRITECONF, printFSCONF }, { GSN_FSREADCONF, printFSCONF }, { GSN_FSSYNCCONF, printFSCONF }, { GSN_CLOSE_COMREQ, printCLOSECOMREQCONF }, { GSN_CLOSE_COMCONF, printCLOSECOMREQCONF }, { GSN_PACKED_SIGNAL, printPACKED_SIGNAL }, { GSN_PREP_FAILREQ, printPREPFAILREQREF }, { GSN_PREP_FAILREF, printPREPFAILREQREF }, { GSN_ALTER_TABLE_REQ, printALTER_TABLE_REQ }, { GSN_ALTER_TABLE_CONF, printALTER_TABLE_CONF }, { GSN_ALTER_TABLE_REF, printALTER_TABLE_REF }, { GSN_ALTER_TAB_REQ, printALTER_TAB_REQ }, { GSN_ALTER_TAB_CONF, printALTER_TAB_CONF }, { GSN_ALTER_TAB_REF, printALTER_TAB_REF }, { GSN_CREATE_TRIG_REQ, printCREATE_TRIG_REQ }, { GSN_CREATE_TRIG_CONF, printCREATE_TRIG_CONF }, { GSN_CREATE_TRIG_REF, printCREATE_TRIG_REF }, { GSN_ALTER_TRIG_REQ, printALTER_TRIG_REQ }, { GSN_ALTER_TRIG_CONF, printALTER_TRIG_CONF }, { GSN_ALTER_TRIG_REF, printALTER_TRIG_REF }, { GSN_DROP_TRIG_REQ, printDROP_TRIG_REQ }, { GSN_DROP_TRIG_CONF, printDROP_TRIG_CONF }, { GSN_DROP_TRIG_REF, printDROP_TRIG_REF }, { GSN_FIRE_TRIG_ORD, printFIRE_TRIG_ORD }, { GSN_TRIG_ATTRINFO, printTRIG_ATTRINFO }, { GSN_CREATE_INDX_REQ, printCREATE_INDX_REQ }, { GSN_CREATE_INDX_CONF, printCREATE_INDX_CONF }, { GSN_CREATE_INDX_REF, printCREATE_INDX_REF }, { GSN_DROP_INDX_REQ, printDROP_INDX_REQ }, { GSN_DROP_INDX_CONF, printDROP_INDX_CONF }, { GSN_DROP_INDX_REF, printDROP_INDX_REF }, { GSN_ALTER_INDX_REQ, printALTER_INDX_REQ }, { GSN_ALTER_INDX_CONF, printALTER_INDX_CONF }, { GSN_ALTER_INDX_REF, printALTER_INDX_REF }, { GSN_TCINDXREQ, printTCINDXREQ }, { GSN_TCINDXCONF, printTCINDXCONF }, { GSN_TCINDXREF, printTCINDXREF }, { GSN_INDXKEYINFO, printINDXKEYINFO }, { GSN_INDXATTRINFO, printINDXATTRINFO }, //{ GSN_TCINDXNEXTREQ, printTCINDXNEXTREQ }, //{ GSN_TCINDEXNEXTCONF, printTCINDEXNEXTCONF }, //{ GSN_TCINDEXNEXREF, printTCINDEXNEXREF }, { GSN_FSAPPENDREQ, printFSAPPENDREQ }, { GSN_BACKUP_REQ, printBACKUP_REQ }, { GSN_BACKUP_DATA, printBACKUP_DATA }, { GSN_BACKUP_REF, printBACKUP_REF }, { GSN_BACKUP_CONF, printBACKUP_CONF }, { GSN_ABORT_BACKUP_ORD, printABORT_BACKUP_ORD }, { GSN_BACKUP_ABORT_REP, printBACKUP_ABORT_REP }, { GSN_BACKUP_COMPLETE_REP, printBACKUP_COMPLETE_REP }, { GSN_BACKUP_NF_COMPLETE_REP, printBACKUP_NF_COMPLETE_REP }, { GSN_DEFINE_BACKUP_REQ, printDEFINE_BACKUP_REQ }, { GSN_DEFINE_BACKUP_REF, printDEFINE_BACKUP_REF }, { GSN_DEFINE_BACKUP_CONF, printDEFINE_BACKUP_CONF }, { GSN_START_BACKUP_REQ, printSTART_BACKUP_REQ }, { GSN_START_BACKUP_REF, printSTART_BACKUP_REF }, { GSN_START_BACKUP_CONF, printSTART_BACKUP_CONF }, { GSN_BACKUP_FRAGMENT_REQ, printBACKUP_FRAGMENT_REQ }, { GSN_BACKUP_FRAGMENT_REF, printBACKUP_FRAGMENT_REF }, { GSN_BACKUP_FRAGMENT_CONF, printBACKUP_FRAGMENT_CONF }, { GSN_STOP_BACKUP_REQ, printSTOP_BACKUP_REQ }, { GSN_STOP_BACKUP_REF, printSTOP_BACKUP_REF }, { GSN_STOP_BACKUP_CONF, printSTOP_BACKUP_CONF }, { GSN_BACKUP_STATUS_REQ, printBACKUP_STATUS_REQ }, //{ GSN_BACKUP_STATUS_REF, printBACKUP_STATUS_REF }, { GSN_BACKUP_STATUS_CONF, printBACKUP_STATUS_CONF }, { GSN_UTIL_SEQUENCE_REQ, printUTIL_SEQUENCE_REQ }, { GSN_UTIL_SEQUENCE_REF, printUTIL_SEQUENCE_REF }, { GSN_UTIL_SEQUENCE_CONF, printUTIL_SEQUENCE_CONF }, { GSN_UTIL_PREPARE_REQ, printUTIL_PREPARE_REQ }, { GSN_UTIL_PREPARE_REF, printUTIL_PREPARE_REF }, { GSN_UTIL_PREPARE_CONF, printUTIL_PREPARE_CONF }, { GSN_UTIL_EXECUTE_REQ, printUTIL_EXECUTE_REQ }, { GSN_UTIL_EXECUTE_REF, printUTIL_EXECUTE_REF }, { GSN_UTIL_EXECUTE_CONF, printUTIL_EXECUTE_CONF }, { GSN_SCAN_TABREQ, printSCANTABREQ }, { GSN_SCAN_TABCONF, printSCANTABCONF }, { GSN_SCAN_TABREF, printSCANTABREF }, { GSN_SCAN_NEXTREQ, printSCANNEXTREQ }, { GSN_LQHFRAGREQ, printLQH_FRAG_REQ }, { GSN_LQHFRAGREF, printLQH_FRAG_REF }, { GSN_LQHFRAGCONF, printLQH_FRAG_CONF }, { GSN_PREP_DROP_TAB_REQ, printPREP_DROP_TAB_REQ }, { GSN_PREP_DROP_TAB_REF, printPREP_DROP_TAB_REF }, { GSN_PREP_DROP_TAB_CONF, printPREP_DROP_TAB_CONF }, { GSN_DROP_TAB_REQ, printDROP_TAB_REQ }, { GSN_DROP_TAB_REF, printDROP_TAB_REF }, { GSN_DROP_TAB_CONF, printDROP_TAB_CONF }, { GSN_LCP_FRAG_ORD, printLCP_FRAG_ORD }, { GSN_LCP_FRAG_REP, printLCP_FRAG_REP }, { GSN_LCP_COMPLETE_REP, printLCP_COMPLETE_REP }, { GSN_START_LCP_REQ, printSTART_LCP_REQ }, { GSN_START_LCP_CONF, printSTART_LCP_CONF }, { GSN_MASTER_LCPREQ, printMASTER_LCP_REQ }, { GSN_MASTER_LCPREF, printMASTER_LCP_REF }, { GSN_MASTER_LCPCONF, printMASTER_LCP_CONF }, { GSN_COPY_GCIREQ, printCOPY_GCI_REQ }, { GSN_SYSTEM_ERROR, printSYSTEM_ERROR }, { GSN_START_RECREQ, printSTART_REC_REQ }, { GSN_START_RECCONF, printSTART_REC_CONF }, { GSN_NF_COMPLETEREP, printNF_COMPLETE_REP }, { GSN_SIGNAL_DROPPED_REP, printSIGNAL_DROPPED_REP }, { GSN_FAIL_REP, printFAIL_REP }, { GSN_DISCONNECT_REP, printDISCONNECT_REP }, { GSN_SUB_CREATE_REQ, printSUB_CREATE_REQ }, //{ GSN_SUB_CREATE_REF, printSUB_CREATE_REF }, { GSN_SUB_CREATE_CONF, printSUB_CREATE_CONF }, { GSN_SUB_START_REQ, printSUB_START_REQ }, { GSN_SUB_START_REF, printSUB_START_REF }, { GSN_SUB_START_CONF, printSUB_START_CONF }, { GSN_SUB_SYNC_REQ, printSUB_SYNC_REQ }, { GSN_SUB_SYNC_REF, printSUB_SYNC_REF }, { GSN_SUB_SYNC_CONF, printSUB_SYNC_CONF }, { GSN_SUB_META_DATA, printSUB_META_DATA }, { GSN_SUB_TABLE_DATA, printSUB_TABLE_DATA }, { GSN_SUB_SYNC_CONTINUE_REQ, printSUB_SYNC_CONTINUE_REQ }, { GSN_SUB_SYNC_CONTINUE_REF, printSUB_SYNC_CONTINUE_REF }, { GSN_SUB_SYNC_CONTINUE_CONF, printSUB_SYNC_CONTINUE_CONF }, { GSN_SUB_GCP_COMPLETE_REP, printSUB_GCP_COMPLETE_REP } ,{ GSN_CREATE_FRAGMENTATION_REQ, printCREATE_FRAGMENTATION_REQ } ,{ GSN_CREATE_FRAGMENTATION_REF, printCREATE_FRAGMENTATION_REF } ,{ GSN_CREATE_FRAGMENTATION_CONF, printCREATE_FRAGMENTATION_CONF } ,{ GSN_UTIL_CREATE_LOCK_REQ, printUTIL_CREATE_LOCK_REQ } ,{ GSN_UTIL_CREATE_LOCK_REF, printUTIL_CREATE_LOCK_REF } ,{ GSN_UTIL_CREATE_LOCK_CONF, printUTIL_CREATE_LOCK_CONF } ,{ GSN_UTIL_DESTROY_LOCK_REQ, printUTIL_DESTROY_LOCK_REQ } ,{ GSN_UTIL_DESTROY_LOCK_REF, printUTIL_DESTROY_LOCK_REF } ,{ GSN_UTIL_DESTROY_LOCK_CONF, printUTIL_DESTROY_LOCK_CONF } ,{ GSN_UTIL_LOCK_REQ, printUTIL_LOCK_REQ } ,{ GSN_UTIL_LOCK_REF, printUTIL_LOCK_REF } ,{ GSN_UTIL_LOCK_CONF, printUTIL_LOCK_CONF } ,{ GSN_UTIL_UNLOCK_REQ, printUTIL_UNLOCK_REQ } ,{ GSN_UTIL_UNLOCK_REF, printUTIL_UNLOCK_REF } ,{ GSN_UTIL_UNLOCK_CONF, printUTIL_UNLOCK_CONF } ,{ GSN_CNTR_START_REQ, printCNTR_START_REQ } ,{ GSN_CNTR_START_REF, printCNTR_START_REF } ,{ GSN_CNTR_START_CONF, printCNTR_START_CONF } ,{ GSN_READ_NODESCONF, printREAD_NODES_CONF } ,{ GSN_TUX_MAINT_REQ, printTUX_MAINT_REQ } ,{ GSN_ACC_LOCKREQ, printACC_LOCKREQ } ,{ GSN_LQH_TRANSCONF, printLQH_TRANSCONF } ,{ GSN_SCAN_FRAGREQ, printSCAN_FRAGREQ } ,{ 0, 0 } }; #include <Bitmask.hpp> template struct BitmaskPOD<1>; template struct BitmaskPOD<2>; template struct BitmaskPOD<4>; template class Bitmask<1>; template class Bitmask<2>; template class Bitmask<4>; <|endoftext|>
<commit_before>/** * A cache for decoded instructions in functional simulator * @author Denis Los */ // Google test library #include <gtest/gtest.h> // Modules #include "../LRUCache.h" #include <infra/types.h> #include <mips/mips_instr.h> class Dummy { const size_t value; public: explicit Dummy( uint32 val) : value( val) {}; bool is_same( const Dummy& rhs) const { return value == rhs.value; } bool operator==( const Dummy& rhs) const { return is_same(rhs); } friend std::ostream& operator<<( std::ostream& out, const Dummy& val) { return out << val.value; } }; TEST( update_and_find_int, Update_Find_And_Check_Using_Int) { LRUCache<Addr, Dummy, 8192> cache{}; const Addr PC = 0x401c04; const Dummy test_number( 0x103abf9); cache.update( PC, test_number); auto result = cache.find( PC); ASSERT_TRUE( result.first); ASSERT_EQ( result.second, test_number); } TEST( update_and_find, Update_Find_And_Check) { LRUCache<Addr, MIPSInstr, 8192> instr_cache{}; const uint32 instr_bytes = 0x3c010400; const Addr PC = 0x401c04; const MIPSInstr instr( instr_bytes, PC); instr_cache.update( PC, instr); ASSERT_TRUE( instr_cache.find( PC).first); } TEST( check_method_erase, Check_Method_Erase) { LRUCache<Addr, MIPSInstr, 8192> instr_cache{}; const uint32 instr_bytes = 0x3c010400; const Addr PC = 0x401c04; const MIPSInstr instr( instr_bytes, PC); instr_cache.update( PC, instr); instr_cache.erase( PC); ASSERT_FALSE( instr_cache.find( PC).first); } TEST( check_method_empty, Check_Method_Empty) { LRUCache<Addr, MIPSInstr, 8192> instr_cache{}; const uint32 instr_bytes = 0x2484ae10; const Addr PC = 0x400d05; const MIPSInstr instr( instr_bytes, PC); ASSERT_TRUE( instr_cache.empty()); instr_cache.update( PC, instr); ASSERT_FALSE( instr_cache.empty()); } TEST( check_method_size, Check_Method_Size) { LRUCache<Addr, MIPSInstr, 8192> instr_cache{}; uint32 instr_bytes = 0x2484ae10; Addr PC = 0x30ae17; const std::size_t SIZE = LRUCache<Addr, MIPSInstr, 8192>::get_capacity() / 12; for ( std::size_t i = 0; i < SIZE; ++i) { MIPSInstr instr( instr_bytes++, PC); instr_cache.update( PC++, instr); } ASSERT_EQ( SIZE, instr_cache.size()); instr_cache.erase( PC - 1); ASSERT_EQ( SIZE - 1, instr_cache.size()); } TEST( exceed_capacity_and_test_lru, Add_More_Elements_Than_Capacity_And_Check) { constexpr const auto CAPACITY = 8192; LRUCache<std::size_t, Dummy, CAPACITY> cache; for ( std::size_t i = 1; i <= CAPACITY; ++i) // note the <= cache.update( i, Dummy( i)); cache.update( 1, Dummy( 1)); cache.update( CAPACITY / 2, Dummy( CAPACITY / 2)); cache.update( CAPACITY + 1, Dummy( CAPACITY + 1)); ASSERT_EQ( cache.size(), CAPACITY); ASSERT_FALSE( cache.empty()); ASSERT_FALSE( cache.find( 2).first); } int main( int argc, char** argv) { ::testing::InitGoogleTest( &argc, argv); ::testing::FLAGS_gtest_death_test_style = "threadsafe"; return RUN_ALL_TESTS(); } <commit_msg>Fix sign of literal in unit test<commit_after>/** * A cache for decoded instructions in functional simulator * @author Denis Los */ // Google test library #include <gtest/gtest.h> // Modules #include "../LRUCache.h" #include <infra/types.h> #include <mips/mips_instr.h> class Dummy { const size_t value; public: explicit Dummy( uint32 val) : value( val) {}; bool is_same( const Dummy& rhs) const { return value == rhs.value; } bool operator==( const Dummy& rhs) const { return is_same(rhs); } friend std::ostream& operator<<( std::ostream& out, const Dummy& val) { return out << val.value; } }; TEST( update_and_find_int, Update_Find_And_Check_Using_Int) { LRUCache<Addr, Dummy, 8192> cache{}; const Addr PC = 0x401c04; const Dummy test_number( 0x103abf9); cache.update( PC, test_number); auto result = cache.find( PC); ASSERT_TRUE( result.first); ASSERT_EQ( result.second, test_number); } TEST( update_and_find, Update_Find_And_Check) { LRUCache<Addr, MIPSInstr, 8192> instr_cache{}; const uint32 instr_bytes = 0x3c010400; const Addr PC = 0x401c04; const MIPSInstr instr( instr_bytes, PC); instr_cache.update( PC, instr); ASSERT_TRUE( instr_cache.find( PC).first); } TEST( check_method_erase, Check_Method_Erase) { LRUCache<Addr, MIPSInstr, 8192> instr_cache{}; const uint32 instr_bytes = 0x3c010400; const Addr PC = 0x401c04; const MIPSInstr instr( instr_bytes, PC); instr_cache.update( PC, instr); instr_cache.erase( PC); ASSERT_FALSE( instr_cache.find( PC).first); } TEST( check_method_empty, Check_Method_Empty) { LRUCache<Addr, MIPSInstr, 8192> instr_cache{}; const uint32 instr_bytes = 0x2484ae10; const Addr PC = 0x400d05; const MIPSInstr instr( instr_bytes, PC); ASSERT_TRUE( instr_cache.empty()); instr_cache.update( PC, instr); ASSERT_FALSE( instr_cache.empty()); } TEST( check_method_size, Check_Method_Size) { LRUCache<Addr, MIPSInstr, 8192> instr_cache{}; uint32 instr_bytes = 0x2484ae10; Addr PC = 0x30ae17; const std::size_t SIZE = LRUCache<Addr, MIPSInstr, 8192>::get_capacity() / 12; for ( std::size_t i = 0; i < SIZE; ++i) { MIPSInstr instr( instr_bytes++, PC); instr_cache.update( PC++, instr); } ASSERT_EQ( SIZE, instr_cache.size()); instr_cache.erase( PC - 1); ASSERT_EQ( SIZE - 1, instr_cache.size()); } TEST( exceed_capacity_and_test_lru, Add_More_Elements_Than_Capacity_And_Check) { constexpr const auto CAPACITY = 8192u; LRUCache<std::size_t, Dummy, CAPACITY> cache; for ( std::size_t i = 1; i <= CAPACITY; ++i) // note the <= cache.update( i, Dummy( i)); cache.update( 1, Dummy( 1)); cache.update( CAPACITY / 2, Dummy( CAPACITY / 2)); cache.update( CAPACITY + 1, Dummy( CAPACITY + 1)); ASSERT_EQ( cache.size(), CAPACITY); ASSERT_FALSE( cache.empty()); ASSERT_FALSE( cache.find( 2).first); } int main( int argc, char** argv) { ::testing::InitGoogleTest( &argc, argv); ::testing::FLAGS_gtest_death_test_style = "threadsafe"; return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/** * medianSales.cpp * * Author: Patrick Rummage (patrickbrummage@gmail.com) * * Objective: * Use a two-dimensional array of sales data to identify the sales agent * with the highest median sales figure in a year. */ #include <cstdlib> #include <iostream> using std::cin; using std::cout; const int NUM_AGENTS = 3; const int NUM_MONTHS = 12; int sales[NUM_AGENTS][NUM_MONTHS] = { {1856, 498, 30924, 87478, 328, 2653, 387, 3754, 387587, 2873, 276, 32}, {5865, 5456, 3983, 6464, 9957, 4785, 3875, 3838, 4959, 1122, 7766, 2534}, {23, 55, 67, 99, 265, 376, 232, 223, 4546, 564, 4544, 3434} }; int compare(const void *p1, const void *p2) { int x = *(int *)p1, y = *(int *)p2; return x <= y ? (x < y ? -1 : 0) : 1; } double findMedian(int intArray[], int ARRAY_SIZE) { qsort(intArray, ARRAY_SIZE, sizeof(int), compare); int middle = ARRAY_SIZE / 2; //arrays all have even # of elements (12). average the two middle numbers return (intArray[middle - 1] + intArray[middle]) / 2; } int main(int argc, char *argv[]) { int bestAgent = 0; int highestMedian = findMedian(sales[0], 12); for (int agent = 1; agent < NUM_AGENTS; agent++) { int agentMedian = findMedian(sales[agent], 12); if (agentMedian > highestMedian) { highestMedian = agentMedian; bestAgent = agent; } } cout << "Agent " << bestAgent << " had best median sales: " << highestMedian << "\n"; return 0; } <commit_msg>findMedian rounds averages<commit_after>/** * medianSales.cpp * * Author: Patrick Rummage (patrickbrummage@gmail.com) * * Objective: * Use a two-dimensional array of sales data to identify the sales agent * with the highest median sales figure in a year. */ #include <cstdlib> #include <iostream> using std::cin; using std::cout; const int NUM_AGENTS = 3; const int NUM_MONTHS = 12; int sales[NUM_AGENTS][NUM_MONTHS] = { {1856, 498, 30924, 87478, 328, 2653, 387, 3754, 387587, 2873, 276, 32}, {5865, 5456, 3983, 6464, 9957, 4785, 3875, 3838, 4959, 1122, 7766, 2534}, {23, 55, 67, 99, 265, 376, 232, 223, 4546, 564, 4544, 3434} }; int compare(const void *p1, const void *p2) { int x = *(int *)p1, y = *(int *)p2; return x <= y ? (x < y ? -1 : 0) : 1; } double findMedian(int intArray[], int ARRAY_SIZE) { qsort(intArray, ARRAY_SIZE, sizeof(int), compare); int middle = ARRAY_SIZE / 2; //arrays all have even # of elements (12), so average the two middle numbers //add 0.5 to round return ((intArray[middle - 1] + intArray[middle]) / 2) + 0.5; } int main(int argc, char *argv[]) { int bestAgent = 0; int highestMedian = findMedian(sales[0], 12); for (int agent = 1; agent < NUM_AGENTS; agent++) { int agentMedian = findMedian(sales[agent], 12); if (agentMedian > highestMedian) { highestMedian = agentMedian; bestAgent = agent; } } cout << "Agent " << bestAgent << " had best median sales: " << highestMedian << "\n"; return 0; } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2016 ScyllaDB. */ #include "metrics.hh" #include "metrics_api.hh" #include <boost/range/algorithm.hpp> namespace seastar { namespace metrics { metric_groups::metric_groups() noexcept : _impl(impl::create_metric_groups()) { } void metric_groups::clear() { _impl = impl::create_metric_groups(); } metric_groups::metric_groups(std::initializer_list<metric_group_definition> mg) : _impl(impl::create_metric_groups()) { for (auto&& i : mg) { add_group(i.name, i.metrics); } } metric_groups& metric_groups::add_group(const group_name_type& name, const std::initializer_list<metric_definition>& l) { _impl->add_group(name, l); return *this; } metric_group::metric_group() noexcept = default; metric_group::~metric_group() = default; metric_group::metric_group(const group_name_type& name, std::initializer_list<metric_definition> l) { add_group(name, l); } metric_group_definition::metric_group_definition(const group_name_type& name, std::initializer_list<metric_definition> l) : name(name), metrics(l) { } metric_group_definition::~metric_group_definition() = default; metric_groups::~metric_groups() = default; metric_definition::metric_definition(metric_definition&& m) noexcept : _impl(std::move(m._impl)) { } metric_definition::~metric_definition() = default; metric_definition::metric_definition(impl::metric_definition_impl const& m) noexcept : _impl(std::make_unique<impl::metric_definition_impl>(m)) { } bool label_instance::operator<(const label_instance& id2) const { auto& id1 = *this; return std::tie(id1.key(), id1.value()) < std::tie(id2.key(), id2.value()); } bool label_instance::operator==(const label_instance& id2) const { auto& id1 = *this; return std::tie(id1.key(), id1.value()) == std::tie(id2.key(), id2.value()); } bool label_instance::operator!=(const label_instance& id2) const { auto& id1 = *this; return !(id1 == id2); } namespace impl { registered_metric::registered_metric(data_type type, metric_function f, description d, bool enabled) : _type(type), _d(d), _enabled(enabled), _f(f), _impl(get_local_impl()) { } metric_value metric_value::operator+(const metric_value& c) { metric_value res(*this); switch (_type) { case data_type::GAUGE: res.u._d += c.u._d; break; case data_type::DERIVE: res.u._i += c.u._i; break; default: res.u._ui += c.u._ui; break; } return res; } std::unique_ptr<metric_groups_def> create_metric_groups() { return std::make_unique<metric_groups_impl>(); } std::unique_ptr<metric_id> get_id(group_name_type group, instance_id_type instance, metric_name_type name, metric_type_def iht) { return std::make_unique<metric_id>(group, instance, name, iht); } metric_groups_impl::~metric_groups_impl() { for (auto i : _registration) { unregister_metric(i); } } metric_groups_impl& metric_groups_impl::add_metric(group_name_type name, const metric_definition& md) { metric_id id(name, md._impl->id, md._impl->name, md._impl->type.type_name, md._impl->labels); shared_ptr<registered_metric> rm = ::make_shared<registered_metric>(md._impl->type.base_type, md._impl->f, md._impl->d, md._impl->enabled); get_local_impl()->add_registration(id, rm); _registration.push_back(id); return *this; } metric_groups_impl& metric_groups_impl::add_group(group_name_type name, const std::vector<metric_definition>& l) { for (auto i = l.begin(); i != l.end(); ++i) { add_metric(name, *(i->_impl.get())); } return *this; } metric_groups_impl& metric_groups_impl::add_group(group_name_type name, const std::initializer_list<metric_definition>& l) { for (auto i = l.begin(); i != l.end(); ++i) { add_metric(name, *i); } return *this; } void metric_id::sort_labels() { boost::sort(_labels); } bool metric_id::operator<( const metric_id& id2) const { return as_tuple() < id2.as_tuple(); } bool metric_id::operator==( const metric_id & id2) const { return as_tuple() < id2.as_tuple(); } // Unfortunately, metrics_impl can not be shared because it // need to be available before the first users (reactor) will call it shared_ptr<impl> get_local_impl() { static thread_local auto the_impl = make_shared<impl>(); return the_impl; } void unregister_metric(const metric_id & id) { shared_ptr<impl> map = get_local_impl(); auto i = map->get_value_map().find(id); if (i != map->get_value_map().end()) { i->second = nullptr; } } const value_map& get_value_map() { return get_local_impl()->get_value_map(); } values_copy get_values() { values_copy res; for (auto i : get_local_impl()->get_value_map()) { if (i.second.get() && i.second->is_enabled()) { res[i.first] = (*(i.second))(); } } return std::move(res); } instance_id_type shard() { if (engine_is_ready()) { return to_sstring(engine().cpu_id()); } return sstring("0"); } void impl::add_registration(const metric_id& id, shared_ptr<registered_metric> rm) { _value_map[id] = rm; } } const bool metric_disabled = false; } } <commit_msg>metrics: equal operator should use ==<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2016 ScyllaDB. */ #include "metrics.hh" #include "metrics_api.hh" #include <boost/range/algorithm.hpp> namespace seastar { namespace metrics { metric_groups::metric_groups() noexcept : _impl(impl::create_metric_groups()) { } void metric_groups::clear() { _impl = impl::create_metric_groups(); } metric_groups::metric_groups(std::initializer_list<metric_group_definition> mg) : _impl(impl::create_metric_groups()) { for (auto&& i : mg) { add_group(i.name, i.metrics); } } metric_groups& metric_groups::add_group(const group_name_type& name, const std::initializer_list<metric_definition>& l) { _impl->add_group(name, l); return *this; } metric_group::metric_group() noexcept = default; metric_group::~metric_group() = default; metric_group::metric_group(const group_name_type& name, std::initializer_list<metric_definition> l) { add_group(name, l); } metric_group_definition::metric_group_definition(const group_name_type& name, std::initializer_list<metric_definition> l) : name(name), metrics(l) { } metric_group_definition::~metric_group_definition() = default; metric_groups::~metric_groups() = default; metric_definition::metric_definition(metric_definition&& m) noexcept : _impl(std::move(m._impl)) { } metric_definition::~metric_definition() = default; metric_definition::metric_definition(impl::metric_definition_impl const& m) noexcept : _impl(std::make_unique<impl::metric_definition_impl>(m)) { } bool label_instance::operator<(const label_instance& id2) const { auto& id1 = *this; return std::tie(id1.key(), id1.value()) < std::tie(id2.key(), id2.value()); } bool label_instance::operator==(const label_instance& id2) const { auto& id1 = *this; return std::tie(id1.key(), id1.value()) == std::tie(id2.key(), id2.value()); } bool label_instance::operator!=(const label_instance& id2) const { auto& id1 = *this; return !(id1 == id2); } namespace impl { registered_metric::registered_metric(data_type type, metric_function f, description d, bool enabled) : _type(type), _d(d), _enabled(enabled), _f(f), _impl(get_local_impl()) { } metric_value metric_value::operator+(const metric_value& c) { metric_value res(*this); switch (_type) { case data_type::GAUGE: res.u._d += c.u._d; break; case data_type::DERIVE: res.u._i += c.u._i; break; default: res.u._ui += c.u._ui; break; } return res; } std::unique_ptr<metric_groups_def> create_metric_groups() { return std::make_unique<metric_groups_impl>(); } std::unique_ptr<metric_id> get_id(group_name_type group, instance_id_type instance, metric_name_type name, metric_type_def iht) { return std::make_unique<metric_id>(group, instance, name, iht); } metric_groups_impl::~metric_groups_impl() { for (auto i : _registration) { unregister_metric(i); } } metric_groups_impl& metric_groups_impl::add_metric(group_name_type name, const metric_definition& md) { metric_id id(name, md._impl->id, md._impl->name, md._impl->type.type_name, md._impl->labels); shared_ptr<registered_metric> rm = ::make_shared<registered_metric>(md._impl->type.base_type, md._impl->f, md._impl->d, md._impl->enabled); get_local_impl()->add_registration(id, rm); _registration.push_back(id); return *this; } metric_groups_impl& metric_groups_impl::add_group(group_name_type name, const std::vector<metric_definition>& l) { for (auto i = l.begin(); i != l.end(); ++i) { add_metric(name, *(i->_impl.get())); } return *this; } metric_groups_impl& metric_groups_impl::add_group(group_name_type name, const std::initializer_list<metric_definition>& l) { for (auto i = l.begin(); i != l.end(); ++i) { add_metric(name, *i); } return *this; } void metric_id::sort_labels() { boost::sort(_labels); } bool metric_id::operator<( const metric_id& id2) const { return as_tuple() < id2.as_tuple(); } bool metric_id::operator==( const metric_id & id2) const { return as_tuple() == id2.as_tuple(); } // Unfortunately, metrics_impl can not be shared because it // need to be available before the first users (reactor) will call it shared_ptr<impl> get_local_impl() { static thread_local auto the_impl = make_shared<impl>(); return the_impl; } void unregister_metric(const metric_id & id) { shared_ptr<impl> map = get_local_impl(); auto i = map->get_value_map().find(id); if (i != map->get_value_map().end()) { i->second = nullptr; } } const value_map& get_value_map() { return get_local_impl()->get_value_map(); } values_copy get_values() { values_copy res; for (auto i : get_local_impl()->get_value_map()) { if (i.second.get() && i.second->is_enabled()) { res[i.first] = (*(i.second))(); } } return std::move(res); } instance_id_type shard() { if (engine_is_ready()) { return to_sstring(engine().cpu_id()); } return sstring("0"); } void impl::add_registration(const metric_id& id, shared_ptr<registered_metric> rm) { _value_map[id] = rm; } } const bool metric_disabled = false; } } <|endoftext|>
<commit_before>#pragma once // Parameters to control the behavior of an SDPSolver. See the manual // for a detailed description of each. // #include "types.hxx" #include <El.hpp> #include <iostream> class SDP_Solver_Parameters { public: int max_iterations; int max_runtime; int checkpoint_interval; bool no_final_checkpoint; bool find_primal_feasible; bool find_dual_feasible; bool detect_primal_feasible_jump; bool detect_dual_feasible_jump; int precision; Real duality_gap_threshold; Real primal_error_threshold; Real dual_error_threshold; Real initial_matrix_scale_primal; Real initial_matrix_scale_dual; Real feasible_centering_parameter; Real infeasible_centering_parameter; Real step_length_reduction; Real max_complementarity; El::BigFloat duality_gap_threshold_elemental; El::BigFloat primal_error_threshold_elemental; El::BigFloat dual_error_threshold_elemental; El::BigFloat initial_matrix_scale_primal_elemental; El::BigFloat initial_matrix_scale_dual_elemental; El::BigFloat feasible_centering_parameter_elemental; El::BigFloat infeasible_centering_parameter_elemental; El::BigFloat step_length_reduction_elemental; El::BigFloat max_complementarity_elemental; // Set the precision of all Real parameters to equal 'precision'. // This is necessary because 'precision' might be set (via the // command line or a file) after initializing other parameters. // void resetPrecision() { duality_gap_threshold.set_prec(precision); primal_error_threshold.set_prec(precision); dual_error_threshold.set_prec(precision); initial_matrix_scale_primal.set_prec(precision); initial_matrix_scale_dual.set_prec(precision); feasible_centering_parameter.set_prec(precision); infeasible_centering_parameter.set_prec(precision); step_length_reduction.set_prec(precision); max_complementarity.set_prec(precision); duality_gap_threshold_elemental.SetPrecision(precision); primal_error_threshold_elemental.SetPrecision(precision); dual_error_threshold_elemental.SetPrecision(precision); initial_matrix_scale_primal_elemental.SetPrecision(precision); initial_matrix_scale_dual_elemental.SetPrecision(precision); feasible_centering_parameter_elemental.SetPrecision(precision); infeasible_centering_parameter_elemental.SetPrecision(precision); step_length_reduction_elemental.SetPrecision(precision); max_complementarity_elemental.SetPrecision(precision); } friend std::ostream & operator<<(std::ostream &os, const SDP_Solver_Parameters &p); }; <commit_msg>Do not set precision of input parameters<commit_after>#pragma once // Parameters to control the behavior of an SDPSolver. See the manual // for a detailed description of each. // #include "types.hxx" #include <El.hpp> #include <iostream> class SDP_Solver_Parameters { public: int max_iterations; int max_runtime; int checkpoint_interval; bool no_final_checkpoint; bool find_primal_feasible; bool find_dual_feasible; bool detect_primal_feasible_jump; bool detect_dual_feasible_jump; int precision; Real duality_gap_threshold; Real primal_error_threshold; Real dual_error_threshold; Real initial_matrix_scale_primal; Real initial_matrix_scale_dual; Real feasible_centering_parameter; Real infeasible_centering_parameter; Real step_length_reduction; Real max_complementarity; El::BigFloat duality_gap_threshold_elemental; El::BigFloat primal_error_threshold_elemental; El::BigFloat dual_error_threshold_elemental; El::BigFloat initial_matrix_scale_primal_elemental; El::BigFloat initial_matrix_scale_dual_elemental; El::BigFloat feasible_centering_parameter_elemental; El::BigFloat infeasible_centering_parameter_elemental; El::BigFloat step_length_reduction_elemental; El::BigFloat max_complementarity_elemental; // Set the precision of all Real parameters to equal 'precision'. // This is necessary because 'precision' might be set (via the // command line or a file) after initializing other parameters. // void resetPrecision() { duality_gap_threshold.set_prec(precision); primal_error_threshold.set_prec(precision); dual_error_threshold.set_prec(precision); initial_matrix_scale_primal.set_prec(precision); initial_matrix_scale_dual.set_prec(precision); feasible_centering_parameter.set_prec(precision); infeasible_centering_parameter.set_prec(precision); step_length_reduction.set_prec(precision); max_complementarity.set_prec(precision); } friend std::ostream & operator<<(std::ostream &os, const SDP_Solver_Parameters &p); }; <|endoftext|>
<commit_before> #include <iostream> #include <memory> #include <vector> #include <algorithm> #include "Include\Application.h" #include "Include\TCPSocket.h" #include "Include\TCPServerSocket.h" #include "Include\SocketEvent.h" class EchoServer : public Application { TCPServerSocket server; std::vector<std::shared_ptr<TCPSocket>> clients; std::vector<std::shared_ptr<TCPSocket>>::iterator clientsIt; public: void run () { std::cout << "starting" << std::endl; server.on(SocketEvent::Connection, [=] (SocketEvent& ev) { clients.push_back(ev.socket); std::shared_ptr<std::string> message = std::make_shared<std::string>(); std::cout << "connection received, count: " << clients.size() << std::endl; ev.socket->on(SocketEvent::Data, [=] (SocketEvent& ev) { std::cout << "data received: " << ev.data << std::endl; std::string incoming(ev.data); message->reserve(message->size() + ev.dataLength); for (char& character : incoming) { if ((character >= 32) && (character <= 126)) { message->append(1, character); } else if (character == 13) { message->append(&character); ev.socket->send(message->c_str()); message->clear(); } else { // invalid char, void the buffer since this is likely a binary message, putty does this, its annoying message->clear(); } } message->shrink_to_fit(); }); ev.socket->on(SocketEvent::Error, [=] (SocketEvent& ev) { std::cout << "socket error: " << ev.error << std::endl; ev.socket->close(); }); ev.socket->on(SocketEvent::Close, [=] (SocketEvent& ev) { clientsIt = clients.erase(std::remove(clients.begin(), clients.end(), ev.socket), clients.end()); std::cout << "socket closed, count: " << clients.size() << std::endl; }); }); server.bind("0.0.0.0", 1337); server.listen(); while (true) { server.poll(); clientsIt = clients.begin(); while (clientsIt != clients.end()) { clientsIt->get()->poll(); if (clientsIt != clients.end()) clientsIt++; } } }; };<commit_msg>EchoServer example testing<commit_after> #include <iostream> #include <memory> #include <vector> #include <algorithm> #include <sstream> #include "Include\Application.h" #include "Include\TCPSocket.h" #include "Include\TCPServerSocket.h" #include "Include\SocketEvent.h" class EchoServer : public Application { TCPServerSocket server; std::vector<std::shared_ptr<TCPSocket>> clients; std::vector<std::shared_ptr<TCPSocket>>::iterator clientsIt; public: void run () { std::cout << "starting" << std::endl; server.on(SocketEvent::Connection, [=] (SocketEvent& ev) { clients.push_back(ev.socket); std::shared_ptr<std::string> message = std::make_shared<std::string>(); std::cout << "connection received, count: " << clients.size() << std::endl; ev.socket->on(SocketEvent::Data, [=] (SocketEvent& ev) { //std::cout << "data received: " << ev.socket->getRemoteAddress().first << ": " << ev.data << std::endl; std::string incoming(ev.data); message->reserve(message->size() + ev.dataLength); for (char& character : incoming) { if ((character >= 32) && (character <= 126)) { message->append(1, character); } else if (character == 13) { message->append("\r\n"); std::ostringstream ss; ss << ev.socket->getRemoteAddress().first << ": " << *message; ev.socket->send(ss.str()); message->clear(); } else { // invalid char, void the buffer since this is likely a binary message, putty does this, its annoying message->clear(); } } message->shrink_to_fit(); }); ev.socket->on(SocketEvent::Error, [=] (SocketEvent& ev) { std::cout << "socket error: " << ev.error << std::endl; ev.socket->close(); }); ev.socket->on(SocketEvent::Close, [=] (SocketEvent& ev) { clientsIt = clients.erase(std::remove(clients.begin(), clients.end(), ev.socket), clients.end()); std::cout << "socket closed, count: " << clients.size() << std::endl; }); }); server.bind("0.0.0.0", 1337); server.listen(); while (true) { server.poll(); clientsIt = clients.begin(); while (clientsIt != clients.end()) { clientsIt->get()->poll(); if (clientsIt != clients.end()) clientsIt++; } Sleep(0); } }; };<|endoftext|>
<commit_before>/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #include "MediaSet.hpp" #include "types/MediaPipeline.hpp" #include "types/MediaElement.hpp" #include "types/MediaSrc.hpp" #include "types/Mixer.hpp" #include "types/UriEndPoint.hpp" #include "types/HttpEndPoint.hpp" #include "types/SdpEndPoint.hpp" #include "types/Filter.hpp" #include "KmsMediaServer_constants.h" #include "KmsMediaErrorCodes_constants.h" #include "utils/utils.hpp" #define GST_CAT_DEFAULT kurento_media_set GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoMediaSet" using namespace kurento; struct _AutoReleaseData { guint timeoutId; MediaSet *mediaSet; KmsMediaObjectId objectId; bool forceRemoving; }; static gboolean auto_release (gpointer dataPointer) { AutoReleaseData *data = (AutoReleaseData *) dataPointer; GST_TRACE ("Auto release media object %" G_GINT64_FORMAT ", force: %d", data->objectId, data->forceRemoving); data->mediaSet->remove (data->objectId, data->forceRemoving); return TRUE; } namespace kurento { class ObjectReleasing { public: ~ObjectReleasing () { if (!object.unique() ) GST_WARNING ("Destroying object %" G_GINT64_FORMAT " that is not unique", object->id); else GST_DEBUG ("Destroying object %" G_GINT64_FORMAT, object->id); object.reset(); } std::shared_ptr <MediaObjectImpl> object; }; MediaSet::~MediaSet () { threadPool.shutdown (true); } bool MediaSet::canBeAutoreleased (const KmsMediaObjectRef &mediaObject) { try { getMediaObject<MediaPad> (mediaObject); return false; } catch (const KmsMediaServerException &e) { return true; } } void MediaSet::keepAlive (const KmsMediaObjectRef &mediaObject) throw (KmsMediaServerException) { std::shared_ptr<MediaObjectImpl> mo; std::shared_ptr<AutoReleaseData> data; std::map<KmsMediaObjectId, std::shared_ptr<AutoReleaseData>>::iterator it; if (!canBeAutoreleased (mediaObject) ) { GST_DEBUG ("MediaObject %" G_GINT64_FORMAT " is not auto releasable", mediaObject.id); return; } /* Check that object exists and it is not exluded from GC */ mo = getMediaObject<MediaObjectImpl> (mediaObject); if (mo->getExcludeFromGC () ) { GST_DEBUG ("MediaObject %" G_GINT64_FORMAT " is excluded from GC", mediaObject.id); return; } mutex.lock(); it = mediaObjectsAlive.find (mediaObject.id); if (it != mediaObjectsAlive.end() ) { data = it->second; if (data->timeoutId != 0) g_source_remove (data->timeoutId); } data->timeoutId = g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, mo->getGarbageCollectorPeriod() * 2, auto_release, (gpointer) data.get (), NULL); mutex.unlock(); } static bool isForceRemoving (std::shared_ptr<MediaObjectImpl> mediaObject) { return ! std::dynamic_pointer_cast<MediaPipeline> (mediaObject); } void MediaSet::put (std::shared_ptr<MediaObjectImpl> mediaObject) { std::shared_ptr<AutoReleaseData> data; std::map<KmsMediaObjectId, std::shared_ptr<std::set<KmsMediaObjectId>> >::iterator it; std::shared_ptr<std::set<KmsMediaObjectId>> children; mutex.lock(); auto findIt = mediaObjectsMap.find (mediaObject->id); if (findIt != mediaObjectsMap.end() && findIt->second != NULL) { // The object is already in the mediaset mutex.unlock(); return; } if (!mediaObject->getExcludeFromGC () ) { data = std::shared_ptr<AutoReleaseData> (new AutoReleaseData() ); data->mediaSet = this; data->objectId = mediaObject->id; data->forceRemoving = isForceRemoving (mediaObject); } if (mediaObject->parent != NULL) { it = childrenMap.find (mediaObject->parent->id); if (it != childrenMap.end() ) { children = it->second; } else { children = std::shared_ptr<std::set<KmsMediaObjectId>> (new std::set<KmsMediaObjectId>() ); childrenMap[mediaObject->parent->id] = children; } children->insert (mediaObject->id); } mediaObjectsMap[mediaObject->id] = mediaObject; if (!mediaObject->getExcludeFromGC () ) { mediaObjectsAlive[mediaObject->id] = data; keepAlive (*mediaObject); } mutex.unlock(); } void MediaSet::removeAutoRelease (const KmsMediaObjectId &id) { std::shared_ptr<AutoReleaseData> data; std::map<KmsMediaObjectId, std::shared_ptr<AutoReleaseData>>::iterator it; mutex.lock(); it = mediaObjectsAlive.find (id); if (it != mediaObjectsAlive.end() ) { data = it->second; if (data->timeoutId != 0) g_source_remove (data->timeoutId); } mediaObjectsAlive.erase (id); mutex.unlock(); } void MediaSet::remove (const KmsMediaObjectRef &mediaObject, bool force) { remove (mediaObject.id, force); } void MediaSet::remove (const KmsMediaObjectId &id, bool force) { std::map<KmsMediaObjectId, std::shared_ptr<MediaObjectImpl> >::iterator mediaObjectsMapIt; std::shared_ptr<MediaObjectImpl> mo = NULL; std::map<KmsMediaObjectId, std::shared_ptr<std::set<KmsMediaObjectId>> >::iterator childrenMapIt; std::shared_ptr<std::set<KmsMediaObjectId>> children; std::set<KmsMediaObjectId>::iterator childrenIt; mutex.lock(); childrenMapIt = childrenMap.find (id); if (childrenMapIt != childrenMap.end() ) { children = std::shared_ptr<std::set<KmsMediaObjectId>> (new std::set<KmsMediaObjectId> (* (childrenMapIt->second) ) ); if (!force && !children->empty () ) { GST_DEBUG ("Media Object %" G_GINT64_FORMAT " has children and not is forcing, so it will not be removed.", id); mutex.unlock(); return; } for (childrenIt = children->begin(); childrenIt != children->end(); childrenIt++) { remove (*childrenIt, force); } childrenMap.erase (id); } mediaObjectsMapIt = mediaObjectsMap.find (id); if (mediaObjectsMapIt != mediaObjectsMap.end() ) mo = mediaObjectsMapIt->second; if (mo != NULL) { if (mo->parent != NULL) { childrenMapIt = childrenMap.find (mo->parent->id); if (childrenMapIt != childrenMap.end() ) { children = childrenMapIt->second; children->erase (mo->id); } } } mediaObjectsMap.erase (id); removeAutoRelease (id); mutex.unlock(); if (mo) { ObjectReleasing *obj = new ObjectReleasing(); obj->object = mo; mo.reset(); threadPool.push ([obj] () { delete obj; } ); } } int MediaSet::size () { int size; mutex.lock(); size = mediaObjectsMap.size(); mutex.unlock(); return size; } template std::shared_ptr<MediaObjectImpl> MediaSet::getMediaObject<MediaObjectImpl> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<MediaPipeline> MediaSet::getMediaObject<MediaPipeline> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<MediaElement> MediaSet::getMediaObject<MediaElement> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<MediaPad> MediaSet::getMediaObject<MediaPad> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<MediaSrc> MediaSet::getMediaObject<MediaSrc> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<MediaSink> MediaSet::getMediaObject<MediaSink> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<Mixer> MediaSet::getMediaObject<Mixer> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<UriEndPoint> MediaSet::getMediaObject<UriEndPoint> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<HttpEndPoint> MediaSet::getMediaObject<HttpEndPoint> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<SdpEndPoint> MediaSet::getMediaObject<SdpEndPoint> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<Filter> MediaSet::getMediaObject<Filter> (const KmsMediaObjectRef &mediaObject); template <class T> std::shared_ptr<T> MediaSet::getMediaObject (const KmsMediaObjectRef &mediaObject) throw (KmsMediaServerException) { std::map<KmsMediaObjectId, std::shared_ptr<MediaObjectImpl> >::iterator it; std::shared_ptr<KmsMediaObjectRef> mo = NULL; std::shared_ptr<T> typedMo; mutex.lock(); it = mediaObjectsMap.find (mediaObject.id); if (it != mediaObjectsMap.end() ) mo = it->second; mutex.unlock(); if (mo == NULL) { KmsMediaServerException except; createKmsMediaServerException (except, g_KmsMediaErrorCodes_constants.MEDIA_OBJECT_NOT_FOUND, "Media object not found"); throw except; } typedMo = std::dynamic_pointer_cast<T> (mo); if (typedMo == NULL) { KmsMediaServerException except; createKmsMediaServerException (except, g_KmsMediaErrorCodes_constants.MEDIA_OBJECT_CAST_ERROR, "Media Object found is not of requested type"); throw except; } return typedMo; } MediaSet::StaticConstructor MediaSet::staticConstructor; MediaSet::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } // kurento <commit_msg>Add timeout to warn about not released objects<commit_after>/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #include "MediaSet.hpp" #include "types/MediaPipeline.hpp" #include "types/MediaElement.hpp" #include "types/MediaSrc.hpp" #include "types/Mixer.hpp" #include "types/UriEndPoint.hpp" #include "types/HttpEndPoint.hpp" #include "types/SdpEndPoint.hpp" #include "types/Filter.hpp" #include "KmsMediaServer_constants.h" #include "KmsMediaErrorCodes_constants.h" #include "utils/utils.hpp" #define GST_CAT_DEFAULT kurento_media_set GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoMediaSet" #define RELEASE_TIMEOUT 10 using namespace kurento; struct _AutoReleaseData { guint timeoutId; MediaSet *mediaSet; KmsMediaObjectId objectId; bool forceRemoving; }; static gboolean auto_release (gpointer dataPointer) { AutoReleaseData *data = (AutoReleaseData *) dataPointer; GST_TRACE ("Auto release media object %" G_GINT64_FORMAT ", force: %d", data->objectId, data->forceRemoving); data->mediaSet->remove (data->objectId, data->forceRemoving); return TRUE; } namespace kurento { class ObjectReleasing { public: ~ObjectReleasing () { Glib::RefPtr<Glib::TimeoutSource> timeout; timeout = Glib::TimeoutSource::create (RELEASE_TIMEOUT * 1000); timeout->connect (sigc::mem_fun<bool, ObjectReleasing> (this, &ObjectReleasing::timeout) ); timeout->attach (); if (!object.unique() ) GST_WARNING ("Destroying object %" G_GINT64_FORMAT " that is not unique", object->id); else GST_DEBUG ("Destroying object %" G_GINT64_FORMAT, object->id); object.reset(); timeout->destroy (); } std::shared_ptr <MediaObjectImpl> object; private: bool timeout () { GST_WARNING ("Timeout releasing object %" G_GINT64_FORMAT, this->object->id); return false; } }; MediaSet::~MediaSet () { threadPool.shutdown (true); } bool MediaSet::canBeAutoreleased (const KmsMediaObjectRef &mediaObject) { try { getMediaObject<MediaPad> (mediaObject); return false; } catch (const KmsMediaServerException &e) { return true; } } void MediaSet::keepAlive (const KmsMediaObjectRef &mediaObject) throw (KmsMediaServerException) { std::shared_ptr<MediaObjectImpl> mo; std::shared_ptr<AutoReleaseData> data; std::map<KmsMediaObjectId, std::shared_ptr<AutoReleaseData>>::iterator it; if (!canBeAutoreleased (mediaObject) ) { GST_DEBUG ("MediaObject %" G_GINT64_FORMAT " is not auto releasable", mediaObject.id); return; } /* Check that object exists and it is not exluded from GC */ mo = getMediaObject<MediaObjectImpl> (mediaObject); if (mo->getExcludeFromGC () ) { GST_DEBUG ("MediaObject %" G_GINT64_FORMAT " is excluded from GC", mediaObject.id); return; } mutex.lock(); it = mediaObjectsAlive.find (mediaObject.id); if (it != mediaObjectsAlive.end() ) { data = it->second; if (data->timeoutId != 0) g_source_remove (data->timeoutId); } data->timeoutId = g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, mo->getGarbageCollectorPeriod() * 2, auto_release, (gpointer) data.get (), NULL); mutex.unlock(); } static bool isForceRemoving (std::shared_ptr<MediaObjectImpl> mediaObject) { return ! std::dynamic_pointer_cast<MediaPipeline> (mediaObject); } void MediaSet::put (std::shared_ptr<MediaObjectImpl> mediaObject) { std::shared_ptr<AutoReleaseData> data; std::map<KmsMediaObjectId, std::shared_ptr<std::set<KmsMediaObjectId>> >::iterator it; std::shared_ptr<std::set<KmsMediaObjectId>> children; mutex.lock(); auto findIt = mediaObjectsMap.find (mediaObject->id); if (findIt != mediaObjectsMap.end() && findIt->second != NULL) { // The object is already in the mediaset mutex.unlock(); return; } if (!mediaObject->getExcludeFromGC () ) { data = std::shared_ptr<AutoReleaseData> (new AutoReleaseData() ); data->mediaSet = this; data->objectId = mediaObject->id; data->forceRemoving = isForceRemoving (mediaObject); } if (mediaObject->parent != NULL) { it = childrenMap.find (mediaObject->parent->id); if (it != childrenMap.end() ) { children = it->second; } else { children = std::shared_ptr<std::set<KmsMediaObjectId>> (new std::set<KmsMediaObjectId>() ); childrenMap[mediaObject->parent->id] = children; } children->insert (mediaObject->id); } mediaObjectsMap[mediaObject->id] = mediaObject; if (!mediaObject->getExcludeFromGC () ) { mediaObjectsAlive[mediaObject->id] = data; keepAlive (*mediaObject); } mutex.unlock(); } void MediaSet::removeAutoRelease (const KmsMediaObjectId &id) { std::shared_ptr<AutoReleaseData> data; std::map<KmsMediaObjectId, std::shared_ptr<AutoReleaseData>>::iterator it; mutex.lock(); it = mediaObjectsAlive.find (id); if (it != mediaObjectsAlive.end() ) { data = it->second; if (data->timeoutId != 0) g_source_remove (data->timeoutId); } mediaObjectsAlive.erase (id); mutex.unlock(); } void MediaSet::remove (const KmsMediaObjectRef &mediaObject, bool force) { remove (mediaObject.id, force); } void MediaSet::remove (const KmsMediaObjectId &id, bool force) { std::map<KmsMediaObjectId, std::shared_ptr<MediaObjectImpl> >::iterator mediaObjectsMapIt; std::shared_ptr<MediaObjectImpl> mo = NULL; std::map<KmsMediaObjectId, std::shared_ptr<std::set<KmsMediaObjectId>> >::iterator childrenMapIt; std::shared_ptr<std::set<KmsMediaObjectId>> children; std::set<KmsMediaObjectId>::iterator childrenIt; mutex.lock(); childrenMapIt = childrenMap.find (id); if (childrenMapIt != childrenMap.end() ) { children = std::shared_ptr<std::set<KmsMediaObjectId>> (new std::set<KmsMediaObjectId> (* (childrenMapIt->second) ) ); if (!force && !children->empty () ) { GST_DEBUG ("Media Object %" G_GINT64_FORMAT " has children and not is forcing, so it will not be removed.", id); mutex.unlock(); return; } for (childrenIt = children->begin(); childrenIt != children->end(); childrenIt++) { remove (*childrenIt, force); } childrenMap.erase (id); } mediaObjectsMapIt = mediaObjectsMap.find (id); if (mediaObjectsMapIt != mediaObjectsMap.end() ) mo = mediaObjectsMapIt->second; if (mo != NULL) { if (mo->parent != NULL) { childrenMapIt = childrenMap.find (mo->parent->id); if (childrenMapIt != childrenMap.end() ) { children = childrenMapIt->second; children->erase (mo->id); } } } mediaObjectsMap.erase (id); removeAutoRelease (id); mutex.unlock(); if (mo) { ObjectReleasing *obj = new ObjectReleasing(); obj->object = mo; mo.reset(); threadPool.push ([obj] () { delete obj; } ); } } int MediaSet::size () { int size; mutex.lock(); size = mediaObjectsMap.size(); mutex.unlock(); return size; } template std::shared_ptr<MediaObjectImpl> MediaSet::getMediaObject<MediaObjectImpl> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<MediaPipeline> MediaSet::getMediaObject<MediaPipeline> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<MediaElement> MediaSet::getMediaObject<MediaElement> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<MediaPad> MediaSet::getMediaObject<MediaPad> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<MediaSrc> MediaSet::getMediaObject<MediaSrc> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<MediaSink> MediaSet::getMediaObject<MediaSink> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<Mixer> MediaSet::getMediaObject<Mixer> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<UriEndPoint> MediaSet::getMediaObject<UriEndPoint> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<HttpEndPoint> MediaSet::getMediaObject<HttpEndPoint> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<SdpEndPoint> MediaSet::getMediaObject<SdpEndPoint> (const KmsMediaObjectRef &mediaObject); template std::shared_ptr<Filter> MediaSet::getMediaObject<Filter> (const KmsMediaObjectRef &mediaObject); template <class T> std::shared_ptr<T> MediaSet::getMediaObject (const KmsMediaObjectRef &mediaObject) throw (KmsMediaServerException) { std::map<KmsMediaObjectId, std::shared_ptr<MediaObjectImpl> >::iterator it; std::shared_ptr<KmsMediaObjectRef> mo = NULL; std::shared_ptr<T> typedMo; mutex.lock(); it = mediaObjectsMap.find (mediaObject.id); if (it != mediaObjectsMap.end() ) mo = it->second; mutex.unlock(); if (mo == NULL) { KmsMediaServerException except; createKmsMediaServerException (except, g_KmsMediaErrorCodes_constants.MEDIA_OBJECT_NOT_FOUND, "Media object not found"); throw except; } typedMo = std::dynamic_pointer_cast<T> (mo); if (typedMo == NULL) { KmsMediaServerException except; createKmsMediaServerException (except, g_KmsMediaErrorCodes_constants.MEDIA_OBJECT_CAST_ERROR, "Media Object found is not of requested type"); throw except; } return typedMo; } MediaSet::StaticConstructor MediaSet::staticConstructor; MediaSet::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } // kurento <|endoftext|>
<commit_before> #include <Python.h> #include <memory> #include <vector> #include <iostream> #include <boost/intrusive_ptr.hpp> template<class T> using ptr = boost::intrusive_ptr<T>; #define AS_GC(o) ((PyGC_Head *)(o)-1) static long& gc_refs(PyObject* self) { PyGC_Head *gc = AS_GC(self); return gc->gc.gc_refs; } struct py_base { std::size_t rc = 0; PyObject* self = nullptr; py_base(PyObject* self) : self(self) { // c++ object keeps python object alive Py_XINCREF(self); std::clog << "py_base() " << this << " - " << self << std::endl; } ~py_base() { std::clog << "~py_base() " << this << " - " << self << std::endl; if(self) { // python ref should have been cleared *before* destruction happens // (during gc clear), or we may still have python ref pointing to the c++ // object throw std::logic_error("attempting to destruct a c++ object with non-zero python ref"); } } template<class Derived> friend void intrusive_ptr_add_ref(Derived* self) { ++self->rc; } template<class Derived> friend void intrusive_ptr_release(Derived* self) { std::clog << "decref: " << self << " " << self->rc << std::endl; if(--self->rc == 0) { delete self; return; } } }; // a c++ class extensible from python struct spam : py_base { public: using py_base::py_base; std::string bacon() { PyObject* obj = PyObject_CallMethod(self, (char*)"bacon", NULL); // TODO check obj is actually a string std::string res = PyString_AsString(obj); Py_XDECREF(obj); return res; } }; static struct test { test() { std::clog << "test" << std::endl; } ~test() { std::clog << "~test" << std::endl; } std::vector< ptr<spam> > spams; } instance; // module methods static PyObject* some(PyObject* self, PyObject* args); static PyObject* clear(PyObject* self, PyObject* args); struct py_spam { PyObject_HEAD; ptr<spam> obj; static void dealloc(py_spam* self); static int traverse(py_spam *self, visitproc visit, void *arg); static int tp_clear(py_spam *self); static PyObject* bacon(py_spam* self, PyObject* args, PyObject** kwargs) { return PyString_FromString("standard bacon"); } static PyObject* tp_new(PyTypeObject* cls, PyObject* args, PyObject* kwargs) { std::clog << "tp_new" << std::endl; PyObject* self = PyType_GenericAlloc(cls, 1); py_spam* py = reinterpret_cast<py_spam*>(self); // allocate c++ object here py->obj = new spam(self); instance.spams.emplace_back(py->obj); return self; } }; static PyMethodDef module_methods[] = { {"some", some, METH_VARARGS, "produce a limited quantity of spam"}, {"clear", clear, METH_VARARGS, "clear all known spam instances"}, {NULL} }; static PyMethodDef spam_methods[] = { {"bacon", (PyCFunction)py_spam::bacon, METH_KEYWORDS, "gimme some bacon" }, {NULL} /* Sentinel */ }; static PyTypeObject spam_type = { PyVarObject_HEAD_INIT(NULL, 0) "spam.spam", /* tp_name */ sizeof(py_spam), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ "spam bacon and spam", /* tp_doc */ }; // implementation of module methods static PyObject* some(PyObject*, PyObject* args) { if(!PyArg_ParseTuple(args, "")) return NULL; PyObject* self = PyType_GenericNew(&spam_type, args, NULL); py_spam* py = reinterpret_cast<py_spam*>(self); // gc cycle here py->obj = new spam(self); return self; } static PyObject* clear(PyObject*, PyObject* args) { if(!PyArg_ParseTuple(args, "")) return NULL; instance.spams.clear(); std::clog << "spam instances cleared" << std::endl; Py_RETURN_NONE; } int py_spam::traverse(py_spam *self, visitproc visit, void *arg) { std::clog << "tp_traverse: " << self << std::endl; // if( self->obj->rc == 1 ) Py_VISIT(self); else std::clog << "existing c++ refs outside python object, don't clear python object" << std::endl; return 0; } int py_spam::tp_clear(py_spam *self) { std::clog << "tp_clear: " << self << std::endl; // object is in a cycle: il will get collected. we notify c++ about it, and // prevent it from decref'ing during destruction, if any std::clog << " c++ rc: " << self->obj->rc << std::endl; self->obj->self = nullptr; self->obj.reset(); return 0; } PyMODINIT_FUNC initspam(void) { // spam_type.tp_dealloc = (destructor) py_spam::dealloc; spam_type.tp_traverse = (traverseproc) py_spam::traverse; spam_type.tp_clear = (inquiry) py_spam::tp_clear; spam_type.tp_methods = spam_methods; spam_type.tp_new = py_spam::tp_new; // noddy_NoddyType.tp_new = PyType_GenericNew; if (PyType_Ready(&spam_type) < 0) return; PyObject* module = Py_InitModule3("spam", module_methods, "Example module that creates an extension type."); Py_INCREF(&spam_type); PyModule_AddObject(module, "spam", (PyObject *)&spam_type); } <commit_msg>not sure wat<commit_after> #include <Python.h> #include <memory> #include <vector> #include <iostream> template<class T> using ptr = std::shared_ptr<T>; // a base class for a c++ object that has a python counterpart: the two objects // will live exactly for the same duration, with python detecting and collecting // garbage. struct base { PyObject* self = nullptr; base(PyObject* self) : self(self) { // the c++ object keeps the python object alive, which in turn keeps the c++ // object alive. only the python gc can detect/break the cycle (see // tp_traverse/tp_clear). Py_XINCREF(self); // precondition: self is a 'freshly' instantiated python object std::clog << "base()" << std::endl; } virtual ~base() { // the c++ object is expected to live as long as the python object, with // python controlling the release. the only legal way this object can be // destroyed is after tp_clear is called on the python object, which clears // 'self' for this object. henceforth, 'self' must be null. assert( !self && "python object outliving its c++ counterpart"); std::clog << "~base()" << std::endl; } // python object struct object { PyObject_HEAD; ptr<base> obj; }; // python methods static int tp_traverse(PyObject *self, visitproc visit, void *arg) { // std::clog << "tp_traverse" << std::endl; // Py_VISIT notifies python gc about the c++/python/c++ cycle: to python, // this object acts like a container containing itself. when python detects // this object is unreachable, tp_clear will be called and the python object // will be collected. // note: we only allow python gc to collect this object when it becomes // unreachable from the c++ side too object* cast = reinterpret_cast<object*>(self); if(cast->obj.unique()) { Py_VISIT(self); } return 0; } static int tp_clear(PyObject *self) { // std::clog << "tp_clear" << std::endl; object* cast = reinterpret_cast<object*>(self); // the python object became unreachable: it will be collected. we notify the // c++ object accordingly. cast->obj->self = nullptr; // c++ object must be released after this point, otherwise it will outlive // its python counterpart. assert( cast->obj.unique() && "c++ object outliving its python counterpart"); cast->obj.reset(); return 0; } // python type object static PyTypeObject pto; // convenience template<class Derived> static Derived* as(PyObject* self) { // TODO check python types object* cast = reinterpret_cast<object*>(self); return static_cast<Derived*>(cast->obj.get()); } }; PyTypeObject base::pto = { PyVarObject_HEAD_INIT(NULL, 0) "base", /* tp_name */ sizeof(object), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ "base class for collectable objects", /* tp_doc */ tp_traverse, tp_clear, }; // a user class struct spam : base { using base::base; std::string bacon() const { PyObject* obj = PyObject_CallMethod(self, (char*) "bacon", NULL); std::string res = PyString_AsString(obj); Py_XDECREF(obj); return res; } static PyObject* tp_new(PyTypeObject* cls, PyObject* args, PyObject* kwargs) { std::clog << "tp_new" << std::endl; PyObject* self = PyType_GenericAlloc(cls, 1); // allocate c++ object base::object* cast = reinterpret_cast<base::object*>(self); cast->obj = std::make_shared<spam>(self); // keep a handle on c++ objects static std::vector<ptr<base> > instances; return self; } static PyObject* py_bacon(PyObject* self, PyObject* args, PyObject* kwargs) { return PyString_FromString("default bacon"); } static PyMethodDef tp_methods[]; }; PyMethodDef spam::tp_methods[] = { {"bacon", (PyCFunction)py_bacon, METH_KEYWORDS, "give the user some bacon"}, {NULL} }; static const struct sentinel { sentinel() { std::clog << "sentinel" << std::endl; } ~sentinel() { std::clog << "~sentinel" << std::endl; } } instance; static PyMethodDef module_methods[] = { {NULL} }; static PyTypeObject spam_type = { PyVarObject_HEAD_INIT(NULL, 0) "spam", /* tp_name */ sizeof(base::object), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "spam bacon and spam", /* tp_doc */ }; #define AS_GC(o) ((PyGC_Head *)(o)-1) static long& gc_refs(PyObject* self) { PyGC_Head *gc = AS_GC(self); return gc->gc.gc_refs; } // static std::size_t force_gc(PyObject* self) { // PyGC_Head *gc = AS_GC(self); // _PyGCHead_SET_REFS(gc, _PyGC_REFS_TENTATIVELY_UNREACHABLE); // } PyMODINIT_FUNC initspam(void) { if (PyType_Ready(&base::pto) < 0) return; Py_INCREF(&base::pto); // spam_type.tp_traverse = (traverseproc) py_spam::tp_traverse; // spam_type.tp_clear = (inquiry) py_spam::tp_clear; spam_type.tp_new = spam::tp_new; spam_type.tp_methods = spam::tp_methods; spam_type.tp_base = &base::pto; // noddy_NoddyType.tp_new = PyType_GenericNew; if (PyType_Ready(&spam_type) < 0) return; PyObject* module = Py_InitModule3("spam", module_methods, "Example module that creates an extension type."); Py_INCREF(&spam_type); PyModule_AddObject(module, "spam", (PyObject *)&spam_type); } <|endoftext|>