text
stringlengths
54
60.6k
<commit_before>/************************************************************************************ This source file is part of the Theora Video Playback Library For latest info, see http://libtheoraplayer.sourceforge.net/ ************************************************************************************* Copyright (c) 2008-2013 Kresimir Spes ([email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php *************************************************************************************/ #include "TheoraVideoManager.h" #include "TheoraWorkerThread.h" #include "TheoraVideoClip.h" #include "TheoraFrameQueue.h" #include "TheoraAudioInterface.h" #include "TheoraUtil.h" #include "TheoraDataSource.h" #include "TheoraException.h" #ifdef __THEORA #include <theora/codec.h> #include <vorbis/codec.h> #include "TheoraVideoClip_Theora.h" #endif #ifdef __AVFOUNDATION #include "TheoraVideoClip_AVFoundation.h" #endif #ifdef __FFMPEG #include "TheoraVideoClip_FFmpeg.h" #endif // declaring function prototype here so I don't have to put it in a header file // it only needs to be used by this plugin and called once extern "C" { void initYUVConversionModule(); } // -------------------------- //#define _SCHEDULING_DEBUG #ifdef _SCHEDULING_DEBUG float gThreadDiagnosticTimer = 0; #endif // -------------------------- struct TheoraWorkCandidate { TheoraVideoClip* clip; float priority, queuedTime, workTime, entitledTime; }; TheoraVideoManager* g_ManagerSingleton = NULL; void theora_writelog(std::string output) { printf("%s\n", output.c_str()); } void (*g_LogFuction)(std::string)=theora_writelog; void TheoraVideoManager::setLogFunction(void (*fn)(std::string)) { g_LogFuction=fn; } TheoraVideoManager* TheoraVideoManager::getSingletonPtr() { return g_ManagerSingleton; } TheoraVideoManager& TheoraVideoManager::getSingleton() { return *g_ManagerSingleton; } TheoraVideoManager::TheoraVideoManager(int num_worker_threads) : mDefaultNumPrecachedFrames(8) { if (num_worker_threads < 1) throw TheoraGenericException("Unable to create TheoraVideoManager, at least one worker thread is reqired"); g_ManagerSingleton = this; logMessage("Initializing Theora Playback Library (" + getVersionString() + ")\n" + #ifdef __THEORA " - libtheora version: " + th_version_string() + "\n" + " - libvorbis version: " + vorbis_version_string() + "\n" + #endif #ifdef __AVFOUNDATION " - using Apple AVFoundation classes.\n" #endif #ifdef __FFMPEG " - using FFmpeg library.\n" #endif "------------------------------------"); mAudioFactory = NULL; mWorkMutex = new TheoraMutex(); // for CPU based yuv2rgb decoding initYUVConversionModule(); createWorkerThreads(num_worker_threads); } TheoraVideoManager::~TheoraVideoManager() { destroyWorkerThreads(); ClipList::iterator ci; for (ci = mClips.begin(); ci != mClips.end(); ci++) delete (*ci); mClips.clear(); delete mWorkMutex; } void TheoraVideoManager::logMessage(std::string msg) { g_LogFuction(msg); } TheoraVideoClip* TheoraVideoManager::getVideoClipByName(std::string name) { foreach(TheoraVideoClip*,mClips) if ((*it)->getName() == name) return *it; return 0; } void TheoraVideoManager::setAudioInterfaceFactory(TheoraAudioInterfaceFactory* factory) { mAudioFactory = factory; } TheoraAudioInterfaceFactory* TheoraVideoManager::getAudioInterfaceFactory() { return mAudioFactory; } TheoraVideoClip* TheoraVideoManager::createVideoClip(std::string filename, TheoraOutputMode output_mode, int numPrecachedOverride, bool usePower2Stride) { TheoraDataSource* src=new TheoraFileDataSource(filename); return createVideoClip(src,output_mode,numPrecachedOverride,usePower2Stride); } TheoraVideoClip* TheoraVideoManager::createVideoClip(TheoraDataSource* data_source, TheoraOutputMode output_mode, int numPrecachedOverride, bool usePower2Stride) { mWorkMutex->lock(); TheoraVideoClip* clip = NULL; int nPrecached = numPrecachedOverride ? numPrecachedOverride : mDefaultNumPrecachedFrames; logMessage("Creating video from data source: "+data_source->repr()); #ifdef __AVFOUNDATION TheoraFileDataSource* fileDataSource = dynamic_cast<TheoraFileDataSource*>(data_source); std::string filename; if (fileDataSource == NULL) { TheoraMemoryFileDataSource* memoryDataSource = dynamic_cast<TheoraMemoryFileDataSource*>(data_source); if (memoryDataSource != NULL) filename = memoryDataSource->getFilename(); // if the user has his own data source, it's going to be a problem for AVAssetReader since it only supports reading from files... } else filename = fileDataSource->getFilename(); if (filename.size() > 4 && filename.substr(filename.size() - 4, filename.size()) == ".mp4") { clip = new TheoraVideoClip_AVFoundation(data_source, output_mode, nPrecached, usePower2Stride); } #endif #if defined(__AVFOUNDATION) && defined(__THEORA) else #endif #ifdef __THEORA clip = new TheoraVideoClip_Theora(data_source, output_mode, nPrecached, usePower2Stride); #endif #ifdef __FFMPEG clip = new TheoraVideoClip_FFmpeg(data_source, output_mode, nPrecached, usePower2Stride); #endif clip->load(data_source); mClips.push_back(clip); mWorkMutex->unlock(); return clip; } void TheoraVideoManager::destroyVideoClip(TheoraVideoClip* clip) { if (clip) { th_writelog("Destroying video clip: " + clip->getName()); mWorkMutex->lock(); bool reported = 0; while (clip->mAssignedWorkerThread) { if (!reported) { th_writelog("Waiting for WorkerThread to finish decoding in order to destroy"); reported = 1; } _psleep(1); } if (reported) th_writelog("WorkerThread done, destroying.."); // erase the clip from the clip list foreach (TheoraVideoClip*, mClips) { if ((*it) == clip) { mClips.erase(it); break; } } // remove all it's references from the work log mWorkLog.remove(clip); // delete the actual clip delete clip; th_writelog("Destroyed video."); mWorkMutex->unlock(); } } TheoraVideoClip* TheoraVideoManager::requestWork(TheoraWorkerThread* caller) { if (!mWorkMutex) return NULL; mWorkMutex->lock(); TheoraVideoClip* selectedClip = NULL; float maxQueuedTime = 0, totalAccessCount = 0, prioritySum = 0, diff, maxDiff = -1; int nReadyFrames; std::vector<TheoraWorkCandidate> candidates; TheoraVideoClip* clip; TheoraWorkCandidate candidate; // first pass is for playing videos, but if no such videos are available for decoding // paused videos are selected in the second pass. Paused videos that are waiting for cache // are considered as playing in the scheduling context for (int i = 0; i < 2 && candidates.size() == 0; i++) { foreach (TheoraVideoClip*, mClips) { clip = *it; if (clip->isBusy() || (i == 0 && clip->isPaused() && !clip->mWaitingForCache)) continue; nReadyFrames = clip->getNumReadyFrames(); if (nReadyFrames == clip->getFrameQueue()->getSize()) continue; candidate.clip = clip; candidate.priority = clip->getPriority(); candidate.queuedTime = (float) nReadyFrames / (clip->getFPS() * clip->getPlaybackSpeed()); candidate.workTime = (float) clip->mThreadAccessCount; totalAccessCount += candidate.workTime; if (maxQueuedTime < candidate.queuedTime) maxQueuedTime = candidate.queuedTime; candidates.push_back(candidate); } } // prevent division by zero if (totalAccessCount == 0) totalAccessCount = 1; if (maxQueuedTime == 0) maxQueuedTime = 1; // normalize candidate values foreach (TheoraWorkCandidate, candidates) { it->workTime /= totalAccessCount; // adjust user priorities to favor clips that have fewer frames queued it->priority *= 1.0f - (it->queuedTime / maxQueuedTime) * 0.5f; prioritySum += it->priority; } foreach (TheoraWorkCandidate, candidates) { it->entitledTime = it->priority / prioritySum; } // now, based on how much access time has been given to each clip in the work log // and how much time should be given to each clip based on calculated priorities, // we choose a best suited clip for this worker thread to decode next foreach (TheoraWorkCandidate, candidates) { diff = it->entitledTime - it->workTime; if (maxDiff < diff) { maxDiff = diff; selectedClip = it->clip; } } if (selectedClip) { selectedClip->mAssignedWorkerThread = caller; int nClips = mClips.size(); unsigned int maxWorkLogSize = (nClips - 1) * 50; if (nClips > 1) { mWorkLog.push_front(selectedClip); selectedClip->mThreadAccessCount++; } TheoraVideoClip* c; while (mWorkLog.size() > maxWorkLogSize) { c = mWorkLog.back(); mWorkLog.pop_back(); c->mThreadAccessCount--; } #ifdef _SCHEDULING_DEBUG if (mClips.size() > 1) { int accessCount = mWorkLog.size(); if (gThreadDiagnosticTimer > 2.0f) { gThreadDiagnosticTimer = 0; std::string logstr = "-----\nTheora Playback Library debug CPU time analysis (" + str(accessCount) + "):\n"; int percent; foreach (TheoraVideoClip*, mClips) { percent = ((float) (*it)->mThreadAccessCount / mWorkLog.size()) * 100.0f; logstr += (*it)->getName() + " (" + str((*it)->getPriority()) + "): " + str((*it)->mThreadAccessCount) + ", " + str(percent) + "%\n"; } logstr += "-----"; th_writelog(logstr); } } #endif } mWorkMutex->unlock(); return selectedClip; } void TheoraVideoManager::update(float time_increase) { foreach (TheoraVideoClip*, mClips) { (*it)->update(time_increase); (*it)->decodedAudioCheck(); } #ifdef _SCHEDULING_DEBUG gThreadDiagnosticTimer += time_increase; #endif } int TheoraVideoManager::getNumWorkerThreads() { return mWorkerThreads.size(); } void TheoraVideoManager::createWorkerThreads(int n) { TheoraWorkerThread* t; for (int i=0;i<n;i++) { t=new TheoraWorkerThread(); t->start(); mWorkerThreads.push_back(t); } } void TheoraVideoManager::destroyWorkerThreads() { foreach(TheoraWorkerThread*,mWorkerThreads) { (*it)->join(); delete (*it); } mWorkerThreads.clear(); } void TheoraVideoManager::setNumWorkerThreads(int n) { if (n == getNumWorkerThreads()) return; if (n < 1) throw TheoraGenericException("Unable to change the number of worker threads in TheoraVideoManager, at least one worker thread is reqired"); th_writelog("changing number of worker threats to: "+str(n)); destroyWorkerThreads(); createWorkerThreads(n); } std::string TheoraVideoManager::getVersionString() { int a, b, c; getVersion(&a, &b, &c); std::string out = str(a) + "." + str(b); if (c != 0) { if (c < 0) out += " RC" + str(-c); else out += "." + str(c); } return out; } void TheoraVideoManager::getVersion(int* a, int* b, int* c) // TODO, return a struct instead of the current solution. { *a = 1; *b = 0; *c = 0; } std::vector<std::string> TheoraVideoManager::getSupportedDecoders() { std::vector<std::string> lst; #ifdef __THEORA lst.push_back("Theora"); #endif #ifdef __AVFOUNDATION lst.push_back("AVFoundation"); #endif #ifdef __FFMPEG lst.push_back("FFmpeg"); #endif return lst; } <commit_msg>added more informative logging when creating a video clip<commit_after>/************************************************************************************ This source file is part of the Theora Video Playback Library For latest info, see http://libtheoraplayer.sourceforge.net/ ************************************************************************************* Copyright (c) 2008-2013 Kresimir Spes ([email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php *************************************************************************************/ #include "TheoraVideoManager.h" #include "TheoraWorkerThread.h" #include "TheoraVideoClip.h" #include "TheoraFrameQueue.h" #include "TheoraAudioInterface.h" #include "TheoraUtil.h" #include "TheoraDataSource.h" #include "TheoraException.h" #ifdef __THEORA #include <theora/codec.h> #include <vorbis/codec.h> #include "TheoraVideoClip_Theora.h" #endif #ifdef __AVFOUNDATION #include "TheoraVideoClip_AVFoundation.h" #endif #ifdef __FFMPEG #include "TheoraVideoClip_FFmpeg.h" #endif // declaring function prototype here so I don't have to put it in a header file // it only needs to be used by this plugin and called once extern "C" { void initYUVConversionModule(); } // -------------------------- //#define _SCHEDULING_DEBUG #ifdef _SCHEDULING_DEBUG float gThreadDiagnosticTimer = 0; #endif // -------------------------- struct TheoraWorkCandidate { TheoraVideoClip* clip; float priority, queuedTime, workTime, entitledTime; }; TheoraVideoManager* g_ManagerSingleton = NULL; void theora_writelog(std::string output) { printf("%s\n", output.c_str()); } void (*g_LogFuction)(std::string)=theora_writelog; void TheoraVideoManager::setLogFunction(void (*fn)(std::string)) { g_LogFuction=fn; } TheoraVideoManager* TheoraVideoManager::getSingletonPtr() { return g_ManagerSingleton; } TheoraVideoManager& TheoraVideoManager::getSingleton() { return *g_ManagerSingleton; } TheoraVideoManager::TheoraVideoManager(int num_worker_threads) : mDefaultNumPrecachedFrames(8) { if (num_worker_threads < 1) throw TheoraGenericException("Unable to create TheoraVideoManager, at least one worker thread is reqired"); g_ManagerSingleton = this; logMessage("Initializing Theora Playback Library (" + getVersionString() + ")\n" + #ifdef __THEORA " - libtheora version: " + th_version_string() + "\n" + " - libvorbis version: " + vorbis_version_string() + "\n" + #endif #ifdef __AVFOUNDATION " - using Apple AVFoundation classes.\n" #endif #ifdef __FFMPEG " - using FFmpeg library.\n" #endif "------------------------------------"); mAudioFactory = NULL; mWorkMutex = new TheoraMutex(); // for CPU based yuv2rgb decoding initYUVConversionModule(); createWorkerThreads(num_worker_threads); } TheoraVideoManager::~TheoraVideoManager() { destroyWorkerThreads(); ClipList::iterator ci; for (ci = mClips.begin(); ci != mClips.end(); ci++) delete (*ci); mClips.clear(); delete mWorkMutex; } void TheoraVideoManager::logMessage(std::string msg) { g_LogFuction(msg); } TheoraVideoClip* TheoraVideoManager::getVideoClipByName(std::string name) { foreach(TheoraVideoClip*,mClips) if ((*it)->getName() == name) return *it; return 0; } void TheoraVideoManager::setAudioInterfaceFactory(TheoraAudioInterfaceFactory* factory) { mAudioFactory = factory; } TheoraAudioInterfaceFactory* TheoraVideoManager::getAudioInterfaceFactory() { return mAudioFactory; } TheoraVideoClip* TheoraVideoManager::createVideoClip(std::string filename, TheoraOutputMode output_mode, int numPrecachedOverride, bool usePower2Stride) { TheoraDataSource* src=new TheoraFileDataSource(filename); return createVideoClip(src,output_mode,numPrecachedOverride,usePower2Stride); } TheoraVideoClip* TheoraVideoManager::createVideoClip(TheoraDataSource* data_source, TheoraOutputMode output_mode, int numPrecachedOverride, bool usePower2Stride) { mWorkMutex->lock(); TheoraVideoClip* clip = NULL; int nPrecached = numPrecachedOverride ? numPrecachedOverride : mDefaultNumPrecachedFrames; logMessage("Creating video from data source: " + data_source->repr() + " [" + str(nPrecached) + " precached frames]."); #ifdef __AVFOUNDATION TheoraFileDataSource* fileDataSource = dynamic_cast<TheoraFileDataSource*>(data_source); std::string filename; if (fileDataSource == NULL) { TheoraMemoryFileDataSource* memoryDataSource = dynamic_cast<TheoraMemoryFileDataSource*>(data_source); if (memoryDataSource != NULL) filename = memoryDataSource->getFilename(); // if the user has his own data source, it's going to be a problem for AVAssetReader since it only supports reading from files... } else filename = fileDataSource->getFilename(); if (filename.size() > 4 && filename.substr(filename.size() - 4, filename.size()) == ".mp4") { clip = new TheoraVideoClip_AVFoundation(data_source, output_mode, nPrecached, usePower2Stride); } #endif #if defined(__AVFOUNDATION) && defined(__THEORA) else #endif #ifdef __THEORA clip = new TheoraVideoClip_Theora(data_source, output_mode, nPrecached, usePower2Stride); #endif #ifdef __FFMPEG clip = new TheoraVideoClip_FFmpeg(data_source, output_mode, nPrecached, usePower2Stride); #endif clip->load(data_source); mClips.push_back(clip); mWorkMutex->unlock(); return clip; } void TheoraVideoManager::destroyVideoClip(TheoraVideoClip* clip) { if (clip) { th_writelog("Destroying video clip: " + clip->getName()); mWorkMutex->lock(); bool reported = 0; while (clip->mAssignedWorkerThread) { if (!reported) { th_writelog("Waiting for WorkerThread to finish decoding in order to destroy"); reported = 1; } _psleep(1); } if (reported) th_writelog("WorkerThread done, destroying.."); // erase the clip from the clip list foreach (TheoraVideoClip*, mClips) { if ((*it) == clip) { mClips.erase(it); break; } } // remove all it's references from the work log mWorkLog.remove(clip); // delete the actual clip delete clip; th_writelog("Destroyed video."); mWorkMutex->unlock(); } } TheoraVideoClip* TheoraVideoManager::requestWork(TheoraWorkerThread* caller) { if (!mWorkMutex) return NULL; mWorkMutex->lock(); TheoraVideoClip* selectedClip = NULL; float maxQueuedTime = 0, totalAccessCount = 0, prioritySum = 0, diff, maxDiff = -1; int nReadyFrames; std::vector<TheoraWorkCandidate> candidates; TheoraVideoClip* clip; TheoraWorkCandidate candidate; // first pass is for playing videos, but if no such videos are available for decoding // paused videos are selected in the second pass. Paused videos that are waiting for cache // are considered as playing in the scheduling context for (int i = 0; i < 2 && candidates.size() == 0; i++) { foreach (TheoraVideoClip*, mClips) { clip = *it; if (clip->isBusy() || (i == 0 && clip->isPaused() && !clip->mWaitingForCache)) continue; nReadyFrames = clip->getNumReadyFrames(); if (nReadyFrames == clip->getFrameQueue()->getSize()) continue; candidate.clip = clip; candidate.priority = clip->getPriority(); candidate.queuedTime = (float) nReadyFrames / (clip->getFPS() * clip->getPlaybackSpeed()); candidate.workTime = (float) clip->mThreadAccessCount; totalAccessCount += candidate.workTime; if (maxQueuedTime < candidate.queuedTime) maxQueuedTime = candidate.queuedTime; candidates.push_back(candidate); } } // prevent division by zero if (totalAccessCount == 0) totalAccessCount = 1; if (maxQueuedTime == 0) maxQueuedTime = 1; // normalize candidate values foreach (TheoraWorkCandidate, candidates) { it->workTime /= totalAccessCount; // adjust user priorities to favor clips that have fewer frames queued it->priority *= 1.0f - (it->queuedTime / maxQueuedTime) * 0.5f; prioritySum += it->priority; } foreach (TheoraWorkCandidate, candidates) { it->entitledTime = it->priority / prioritySum; } // now, based on how much access time has been given to each clip in the work log // and how much time should be given to each clip based on calculated priorities, // we choose a best suited clip for this worker thread to decode next foreach (TheoraWorkCandidate, candidates) { diff = it->entitledTime - it->workTime; if (maxDiff < diff) { maxDiff = diff; selectedClip = it->clip; } } if (selectedClip) { selectedClip->mAssignedWorkerThread = caller; int nClips = mClips.size(); unsigned int maxWorkLogSize = (nClips - 1) * 50; if (nClips > 1) { mWorkLog.push_front(selectedClip); selectedClip->mThreadAccessCount++; } TheoraVideoClip* c; while (mWorkLog.size() > maxWorkLogSize) { c = mWorkLog.back(); mWorkLog.pop_back(); c->mThreadAccessCount--; } #ifdef _SCHEDULING_DEBUG if (mClips.size() > 1) { int accessCount = mWorkLog.size(); if (gThreadDiagnosticTimer > 2.0f) { gThreadDiagnosticTimer = 0; std::string logstr = "-----\nTheora Playback Library debug CPU time analysis (" + str(accessCount) + "):\n"; int percent; foreach (TheoraVideoClip*, mClips) { percent = ((float) (*it)->mThreadAccessCount / mWorkLog.size()) * 100.0f; logstr += (*it)->getName() + " (" + str((*it)->getPriority()) + "): " + str((*it)->mThreadAccessCount) + ", " + str(percent) + "%\n"; } logstr += "-----"; th_writelog(logstr); } } #endif } mWorkMutex->unlock(); return selectedClip; } void TheoraVideoManager::update(float time_increase) { foreach (TheoraVideoClip*, mClips) { (*it)->update(time_increase); (*it)->decodedAudioCheck(); } #ifdef _SCHEDULING_DEBUG gThreadDiagnosticTimer += time_increase; #endif } int TheoraVideoManager::getNumWorkerThreads() { return mWorkerThreads.size(); } void TheoraVideoManager::createWorkerThreads(int n) { TheoraWorkerThread* t; for (int i=0;i<n;i++) { t=new TheoraWorkerThread(); t->start(); mWorkerThreads.push_back(t); } } void TheoraVideoManager::destroyWorkerThreads() { foreach(TheoraWorkerThread*,mWorkerThreads) { (*it)->join(); delete (*it); } mWorkerThreads.clear(); } void TheoraVideoManager::setNumWorkerThreads(int n) { if (n == getNumWorkerThreads()) return; if (n < 1) throw TheoraGenericException("Unable to change the number of worker threads in TheoraVideoManager, at least one worker thread is reqired"); th_writelog("changing number of worker threats to: "+str(n)); destroyWorkerThreads(); createWorkerThreads(n); } std::string TheoraVideoManager::getVersionString() { int a, b, c; getVersion(&a, &b, &c); std::string out = str(a) + "." + str(b); if (c != 0) { if (c < 0) out += " RC" + str(-c); else out += "." + str(c); } return out; } void TheoraVideoManager::getVersion(int* a, int* b, int* c) // TODO, return a struct instead of the current solution. { *a = 1; *b = 0; *c = 0; } std::vector<std::string> TheoraVideoManager::getSupportedDecoders() { std::vector<std::string> lst; #ifdef __THEORA lst.push_back("Theora"); #endif #ifdef __AVFOUNDATION lst.push_back("AVFoundation"); #endif #ifdef __FFMPEG lst.push_back("FFmpeg"); #endif return lst; } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_EVALUATION_PRODUCT_L2DERIV_HH #define DUNE_GDT_EVALUATION_PRODUCT_L2DERIV_HH #include <type_traits> #include <dune/common/dynmatrix.hh> #include <dune/common/fvector.hh> #include <dune/common/typetraits.hh> #include <dune/stuff/functions/interfaces.hh> #include "interface.hh" namespace Dune { namespace GDT { namespace LocalEvaluation { //forward template< class LocalizableFunctionImp > class L2grad; template< class LocalizableFunctionImp > class L2curl; namespace internal { /** * \brief Traits for the L2grad product. */ template< class LocalizableFunctionImp > class L2gradTraits { static_assert(Stuff::is_localizable_function< LocalizableFunctionImp >::value, "LocalizableFunctionImp has to be a localizable function."); public: typedef LocalizableFunctionImp LocalizableFunctionType; typedef L2grad< LocalizableFunctionType > derived_type; typedef typename LocalizableFunctionType::EntityType EntityType; typedef typename LocalizableFunctionType::DomainFieldType DomainFieldType; typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType; typedef std::tuple< std::shared_ptr< LocalfunctionType > > LocalfunctionTupleType; static const size_t dimDomain = LocalizableFunctionType::dimDomain; }; // class L2gradTraits /** * \brief Traits for the L2curl product. */ template< class LocalizableFunctionImp > class L2curlTraits { static_assert(Stuff::is_localizable_function< LocalizableFunctionImp >::value, "LocalizableFunctionImp has to be a localizable function."); public: typedef LocalizableFunctionImp LocalizableFunctionType; typedef L2curl< LocalizableFunctionType > derived_type; typedef typename LocalizableFunctionType::EntityType EntityType; typedef typename LocalizableFunctionType::DomainFieldType DomainFieldType; typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType; typedef std::tuple< std::shared_ptr< LocalfunctionType > > LocalfunctionTupleType; static const size_t dimDomain = LocalizableFunctionType::dimDomain; }; // class L2curlTraits } //namespace internal /** * \brief Computes a product evaluation between a vector valued local l2 function and the gradients of a test space. */ template< class LocalizableFunctionImp > class L2grad : public LocalEvaluation::Codim0Interface< internal::L2gradTraits< LocalizableFunctionImp >, 1 > { public: typedef internal::L2gradTraits< LocalizableFunctionImp > Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType; typedef typename Traits::EntityType EntityType; typedef typename Traits::DomainFieldType DomainFieldType; static const size_t dimDomain = Traits::dimDomain; L2grad(const LocalizableFunctionType& inducingFunction) : inducingFunction_(inducingFunction) {} /// \name Required by all variants of LocalEvaluation::Codim0Interface /// \{ LocalfunctionTupleType localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /// \} /// \name Required by LocalEvaluation::Codim0Interface< ..., 1 > /// \{ /** * \brief extracts the local function and calls the correct order() method */ template< class R, size_t rT, size_t rCT > size_t order(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const { return order(*std::get< 0 >(localFuncs), testBase); } /** * \brief extracts the local function and calls the correct evaluate() method */ template< class R, size_t rT, size_t rCT > void evaluate(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { evaluate(*std::get< 0 >(localFuncs), testBase, localPoint, ret); } /// \} /// \name Actual implementation of order /// \{ /** * \note for `LocalEvaluation::Codim0Interface< ..., 1 >` * \return localFunction.order() + testBase.order()-1 */ template< class R, size_t rL, size_t rCL, size_t rT, size_t rCT > size_t order(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, rL, rCL >& localFunction, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const { return localFunction.order() + testBase.order()-1; } /// \} /// \name Actual implementation of evaluate /// \{ /** * \brief computes a product between a local (l2) function and the gradients of a scalar test base */ template< class R, size_t r > void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, r, 1 >& localFunction, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { assert(r == dimDomain && "This cannot be computed!"); typedef typename Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, 1, 1 >::JacobianRangeType JacobianRangeType; // evaluate local function const auto functionValue = localFunction.evaluate(localPoint); // evaluate test base const size_t size = testBase.size(); std::vector< JacobianRangeType > testgradients(size, JacobianRangeType(0)); testBase.jacobian(localPoint, testgradients); // compute product assert(ret.size() >= size); for (size_t ii = 0; ii < size; ++ii) { ret[ii] = functionValue * testgradients[ii][0]; } } // ... evaluate(...) /// \} private: const LocalizableFunctionType& inducingFunction_; }; // class L2grad /** * \brief Computes a product evaluation between a vector valued local l2 function and the curls of a test space. */ template< class LocalizableFunctionImp > class L2curl : public LocalEvaluation::Codim0Interface< internal::L2curlTraits< LocalizableFunctionImp >, 1 > { public: typedef internal::L2curlTraits< LocalizableFunctionImp > Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType; typedef typename Traits::EntityType EntityType; typedef typename Traits::DomainFieldType DomainFieldType; static const size_t dimDomain = Traits::dimDomain; L2curl(const LocalizableFunctionType& inducingFunction) : inducingFunction_(inducingFunction) {} /// \name Required by all variants of LocalEvaluation::Codim0Interface /// \{ LocalfunctionTupleType localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /// \} /// \name Required by LocalEvaluation::Codim0Interface< ..., 1 > /// \{ /** * \brief extracts the local function and calls the correct order() method */ template< class R, size_t rT, size_t rCT > size_t order(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const { return order(*std::get< 0 >(localFuncs), testBase); } /** * \brief extracts the local function and calls the correct evaluate() method */ template< class R, size_t rT, size_t rCT > void evaluate(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { evaluate(*std::get< 0 >(localFuncs), testBase, localPoint, ret); } /// \} /// \name Actual implementation of order /// \{ /** * \note for `LocalEvaluation::Codim0Interface< ..., 1 >` * \return localFunction.order() + testBase.order()-1 */ template< class R, size_t rL, size_t rCL, size_t rT, size_t rCT > size_t order(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, rL, rCL >& localFunction, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const { return localFunction.order() + testBase.order()-1; } /// \} /// \name Actual implementation of evaluate /// \{ /** * \brief computes a product between a local (l2) function and the curls of a vectorial test base */ template< class R, size_t r > void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, r, 1 >& localFunction, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, 1 >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { assert(r == dimDomain && dimDomain == 3 && "curl only defined form r^3 to r^3!"); typedef typename Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, r, 1 >::JacobianRangeType JacobianRangeType; // evaluate local function const auto functionValue = localFunction.evaluate(localPoint); // evaluate test base const size_t size = testBase.size(); std::vector< JacobianRangeType > testgradients(size, JacobianRangeType(0)); testBase.jacobian(localPoint, testgradients); // compute product assert(ret.size() >= size); for (size_t ii = 0; ii < size; ++ii) { ret[ii] = functionValue[0] * (testgradients[ii][2][1]-testgradients[ii][1][2]) + functionValue[1] * (testgradients[ii][0][2]-testgradients[ii][2][0]) + functionValue[2] * (testgradients[ii][1][0]-testgradients[ii][0][1]); } } // ... evaluate(...) /// \} private: const LocalizableFunctionType& inducingFunction_; }; // class L2grad } //namespace LocalEvaluation } //namespace GDT } //namespace Dune #endif // DUNE_GDT_EVALUATION_PRODUCT_L2DERIV_HH <commit_msg>add evaluations for rhs of cell problems in HMM<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_EVALUATION_PRODUCT_L2DERIV_HH #define DUNE_GDT_EVALUATION_PRODUCT_L2DERIV_HH #include <type_traits> #include <dune/common/dynmatrix.hh> #include <dune/common/fvector.hh> #include <dune/common/typetraits.hh> #include <dune/stuff/functions/interfaces.hh> #include "interface.hh" namespace Dune { namespace GDT { namespace LocalEvaluation { //forward template< class LocalizableFunctionImp > class L2grad; template< class LocalizableFunctionImp > class L2curl; namespace internal { /** * \brief Traits for the L2grad product. */ template< class LocalizableFunctionImp > class L2gradTraits { static_assert(Stuff::is_localizable_function< LocalizableFunctionImp >::value, "LocalizableFunctionImp has to be a localizable function."); public: typedef LocalizableFunctionImp LocalizableFunctionType; typedef L2grad< LocalizableFunctionType > derived_type; typedef typename LocalizableFunctionType::EntityType EntityType; typedef typename LocalizableFunctionType::DomainFieldType DomainFieldType; typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType; typedef std::tuple< std::shared_ptr< LocalfunctionType > > LocalfunctionTupleType; static const size_t dimDomain = LocalizableFunctionType::dimDomain; }; // class L2gradTraits /** * \brief Traits for the L2curl product. */ template< class LocalizableFunctionImp > class L2curlTraits { static_assert(Stuff::is_localizable_function< LocalizableFunctionImp >::value, "LocalizableFunctionImp has to be a localizable function."); public: typedef LocalizableFunctionImp LocalizableFunctionType; typedef L2curl< LocalizableFunctionType > derived_type; typedef typename LocalizableFunctionType::EntityType EntityType; typedef typename LocalizableFunctionType::DomainFieldType DomainFieldType; typedef typename LocalizableFunctionType::LocalfunctionType LocalfunctionType; typedef std::tuple< std::shared_ptr< LocalfunctionType > > LocalfunctionTupleType; static const size_t dimDomain = LocalizableFunctionType::dimDomain; }; // class L2curlTraits } //namespace internal /** * \brief Computes a product evaluation between a vector valued local l2 function and the gradients of a test space. */ template< class LocalizableFunctionImp > class L2grad : public LocalEvaluation::Codim0Interface< internal::L2gradTraits< LocalizableFunctionImp >, 1 > { public: typedef internal::L2gradTraits< LocalizableFunctionImp > Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType; typedef typename Traits::EntityType EntityType; typedef typename Traits::DomainFieldType DomainFieldType; static const size_t dimDomain = Traits::dimDomain; L2grad(const LocalizableFunctionType& inducingFunction) : inducingFunction_(inducingFunction) {} /// \name Required by all variants of LocalEvaluation::Codim0Interface /// \{ LocalfunctionTupleType localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /// \} /// \name Required by LocalEvaluation::Codim0Interface< ..., 1 > /// \{ /** * \brief extracts the local function and calls the correct order() method */ template< class R, size_t rT, size_t rCT > size_t order(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const { return order(*std::get< 0 >(localFuncs), testBase); } /** * \brief extracts the local function and calls the correct evaluate() method */ template< class R, size_t rT, size_t rCT > void evaluate(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { evaluate(*std::get< 0 >(localFuncs), testBase, localPoint, ret); } /// \} /// \name Actual implementation of order /// \{ /** * \note for `LocalEvaluation::Codim0Interface< ..., 1 >` * \return localFunction.order() + testBase.order()-1 */ template< class R, size_t rL, size_t rCL, size_t rT, size_t rCT > size_t order(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, rL, rCL >& localFunction, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const { return localFunction.order() + testBase.order()-1; } /// \} /// \name Actual implementation of evaluate /// \{ /** * \brief computes a product between a local (l2) function and the gradients of a scalar test base */ template< class R, size_t r > void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, r, 1 >& localFunction, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { assert(r == dimDomain && "This cannot be computed!"); typedef typename Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, 1, 1 >::JacobianRangeType JacobianRangeType; // evaluate local function const auto functionValue = localFunction.evaluate(localPoint); // evaluate test base const size_t size = testBase.size(); std::vector< JacobianRangeType > testgradients(size, JacobianRangeType(0)); testBase.jacobian(localPoint, testgradients); // compute product assert(ret.size() >= size); for (size_t ii = 0; ii < size; ++ii) { ret[ii] = functionValue * testgradients[ii][0]; } } // ... evaluate(...) /// \} private: const LocalizableFunctionType& inducingFunction_; }; // class L2grad /** * \brief Computes a product evaluation between a scalar valued local l2 function, a constant vector of vectors and the gradients of a test space. */ template< class LocalizableFunctionImp, class VectorofVectors > class VectorL2grad : public LocalEvaluation::Codim0Interface< internal::L2gradTraits< LocalizableFunctionImp >, 1 > { public: typedef internal::L2gradTraits< LocalizableFunctionImp > Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType; typedef typename Traits::EntityType EntityType; typedef typename Traits::DomainFieldType DomainFieldType; static const size_t dimDomain = Traits::dimDomain; VectorL2grad(const LocalizableFunctionType& inducingFunction, const VectorofVectors& vectors, const size_t num_vector) : inducingFunction_(inducingFunction) , vectors_(vectors) , num_vector_(num_vector) {} /// \name Required by all variants of LocalEvaluation::Codim0Interface /// \{ LocalfunctionTupleType localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /// \} /// \name Required by LocalEvaluation::Codim0Interface< ..., 1 > /// \{ /** * \brief extracts the local function and calls the correct order() method */ template< class R, size_t rT, size_t rCT > size_t order(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const { return order(*std::get< 0 >(localFuncs), testBase); } /** * \brief extracts the local function and calls the correct evaluate() method */ template< class R, size_t rT, size_t rCT > void evaluate(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { evaluate(*std::get< 0 >(localFuncs), testBase, localPoint, ret); } /// \} /// \name Actual implementation of order /// \{ /** * \note for `LocalEvaluation::Codim0Interface< ..., 1 >` * \return localFunction.order() + testBase.order()-1 */ template< class R, size_t rL, size_t rCL, size_t rT, size_t rCT > size_t order(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, rL, rCL >& localFunction, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const { return localFunction.order() + testBase.order()-1; } /// \} /// \name Actual implementation of evaluate /// \{ /** * \brief computes a product between a local (l2) function and the gradients of a scalar test base */ template< class R> void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& localFunction, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { typedef typename Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, 1, 1 >::JacobianRangeType JacobianRangeType; // evaluate local function const auto functionValue = localFunction.evaluate(localPoint); const auto vector = vectors_[num_vector_]; // evaluate test base const size_t size = testBase.size(); std::vector< JacobianRangeType > testgradients(size, JacobianRangeType(0)); testBase.jacobian(localPoint, testgradients); // compute product assert(ret.size() >= size); for (size_t ii = 0; ii < size; ++ii) { ret[ii] = -1 * functionValue * (vector * testgradients[ii][0]); } } // ... evaluate(...) /// \} private: const LocalizableFunctionType& inducingFunction_; const VectorofVectors& vectors_; const size_t num_vector_; }; // class VectorL2grad /** * \brief Computes a product evaluation between a vector valued local l2 function and the curls of a test space. */ template< class LocalizableFunctionImp > class L2curl : public LocalEvaluation::Codim0Interface< internal::L2curlTraits< LocalizableFunctionImp >, 1 > { public: typedef internal::L2curlTraits< LocalizableFunctionImp > Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType; typedef typename Traits::EntityType EntityType; typedef typename Traits::DomainFieldType DomainFieldType; static const size_t dimDomain = Traits::dimDomain; L2curl(const LocalizableFunctionType& inducingFunction) : inducingFunction_(inducingFunction) {} /// \name Required by all variants of LocalEvaluation::Codim0Interface /// \{ LocalfunctionTupleType localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /// \} /// \name Required by LocalEvaluation::Codim0Interface< ..., 1 > /// \{ /** * \brief extracts the local function and calls the correct order() method */ template< class R, size_t rT, size_t rCT > size_t order(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const { return order(*std::get< 0 >(localFuncs), testBase); } /** * \brief extracts the local function and calls the correct evaluate() method */ template< class R, size_t rT, size_t rCT > void evaluate(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { evaluate(*std::get< 0 >(localFuncs), testBase, localPoint, ret); } /// \} /// \name Actual implementation of order /// \{ /** * \note for `LocalEvaluation::Codim0Interface< ..., 1 >` * \return localFunction.order() + testBase.order()-1 */ template< class R, size_t rL, size_t rCL, size_t rT, size_t rCT > size_t order(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, rL, rCL >& localFunction, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const { return localFunction.order() + testBase.order()-1; } /// \} /// \name Actual implementation of evaluate /// \{ /** * \brief computes a product between a local (l2) function and the curls of a vectorial test base */ template< class R, size_t r > void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, r, 1 >& localFunction, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, 1 >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { assert(r == dimDomain && dimDomain == 3 && "curl only defined form r^3 to r^3!"); typedef typename Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, r, 1 >::JacobianRangeType JacobianRangeType; // evaluate local function const auto functionValue = localFunction.evaluate(localPoint); // evaluate test base const size_t size = testBase.size(); std::vector< JacobianRangeType > testgradients(size, JacobianRangeType(0)); testBase.jacobian(localPoint, testgradients); // compute product assert(ret.size() >= size); for (size_t ii = 0; ii < size; ++ii) { ret[ii] = functionValue[0] * (testgradients[ii][2][1]-testgradients[ii][1][2]) + functionValue[1] * (testgradients[ii][0][2]-testgradients[ii][2][0]) + functionValue[2] * (testgradients[ii][1][0]-testgradients[ii][0][1]); } } // ... evaluate(...) /// \} private: const LocalizableFunctionType& inducingFunction_; }; // class L2curl /** * \brief Computes a product evaluation between a scalar valued local l2 function, a constnat vector and the curls of a test space. */ template< class LocalizableFunctionImp, class VectorofVectors > class VectorL2curl : public LocalEvaluation::Codim0Interface< internal::L2curlTraits< LocalizableFunctionImp >, 1 > { public: typedef internal::L2curlTraits< LocalizableFunctionImp > Traits; typedef typename Traits::LocalizableFunctionType LocalizableFunctionType; typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType; typedef typename Traits::EntityType EntityType; typedef typename Traits::DomainFieldType DomainFieldType; static const size_t dimDomain = Traits::dimDomain; VectorL2curl(const LocalizableFunctionType& inducingFunction, const VectorofVectors& vectors, const size_t num_vector) : inducingFunction_(inducingFunction) , vectors_(vectors) , num_vector_(num_vector) {} /// \name Required by all variants of LocalEvaluation::Codim0Interface /// \{ LocalfunctionTupleType localFunctions(const EntityType& entity) const { return std::make_tuple(inducingFunction_.local_function(entity)); } /// \} /// \name Required by LocalEvaluation::Codim0Interface< ..., 1 > /// \{ /** * \brief extracts the local function and calls the correct order() method */ template< class R, size_t rT, size_t rCT > size_t order(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const { return order(*std::get< 0 >(localFuncs), testBase); } /** * \brief extracts the local function and calls the correct evaluate() method */ template< class R, size_t rT, size_t rCT > void evaluate(const LocalfunctionTupleType& localFuncs, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { evaluate(*std::get< 0 >(localFuncs), testBase, localPoint, ret); } /// \} /// \name Actual implementation of order /// \{ /** * \note for `LocalEvaluation::Codim0Interface< ..., 1 >` * \return localFunction.order() + testBase.order()-1 */ template< class R, size_t rL, size_t rCL, size_t rT, size_t rCT > size_t order(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, rL, rCL >& localFunction, const Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase) const { return localFunction.order() + testBase.order()-1; } /// \} /// \name Actual implementation of evaluate /// \{ /** * \brief computes a product between a local (l2) function and the curls of a vectorial test base */ template< class R, size_t r > void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& localFunction, const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, 1 >& testBase, const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint, Dune::DynamicVector< R >& ret) const { assert(r == dimDomain && dimDomain == 3 && "curl only defined form r^3 to r^3!"); typedef typename Stuff::LocalfunctionSetInterface < EntityType, DomainFieldType, dimDomain, R, r, 1 >::JacobianRangeType JacobianRangeType; // evaluate local function const auto functionValue = localFunction.evaluate(localPoint); const auto vector = vectors_[num_vector_]; // evaluate test base const size_t size = testBase.size(); std::vector< JacobianRangeType > testgradients(size, JacobianRangeType(0)); testBase.jacobian(localPoint, testgradients); // compute product assert(ret.size() >= size); for (size_t ii = 0; ii < size; ++ii) { ret[ii] = -1 * functionValue * (vector[0] * (testgradients[ii][2][1]-testgradients[ii][1][2]) + vector[1] * (testgradients[ii][0][2]-testgradients[ii][2][0]) + vector[2] * (testgradients[ii][1][0]-testgradients[ii][0][1])); } } // ... evaluate(...) /// \} private: const LocalizableFunctionType& inducingFunction_; const VectorofVectors& vectors_; const size_t num_vector_; }; // class VectorL2curl } //namespace LocalEvaluation } //namespace GDT } //namespace Dune #endif // DUNE_GDT_EVALUATION_PRODUCT_L2DERIV_HH <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/notification_options_menu_model.h" #include "app/l10n_util.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/notifications/desktop_notification_service.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/notifications/notifications_prefs_cache.h" #include "chrome/browser/profile.h" #include "chrome/common/content_settings_types.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/url_constants.h" #include "grit/generated_resources.h" // Menu commands const int kTogglePermissionCommand = 0; const int kToggleExtensionCommand = 1; const int kOpenContentSettingsCommand = 2; NotificationOptionsMenuModel::NotificationOptionsMenuModel(Balloon* balloon) : ALLOW_THIS_IN_INITIALIZER_LIST(menus::SimpleMenuModel(this)), balloon_(balloon) { const Notification& notification = balloon->notification(); const GURL& origin = notification.origin_url(); if (origin.SchemeIs(chrome::kExtensionScheme)) { const string16 disable_label = l10n_util::GetStringUTF16( IDS_EXTENSIONS_DISABLE); AddItem(kToggleExtensionCommand, disable_label); } else { const string16 disable_label = l10n_util::GetStringFUTF16( IDS_NOTIFICATION_BALLOON_REVOKE_MESSAGE, notification.display_source()); AddItem(kTogglePermissionCommand, disable_label); } const string16 settings_label = l10n_util::GetStringUTF16( IDS_NOTIFICATIONS_SETTINGS_BUTTON); AddItem(kOpenContentSettingsCommand, settings_label); } NotificationOptionsMenuModel::~NotificationOptionsMenuModel() { } bool NotificationOptionsMenuModel::IsLabelForCommandIdDynamic(int command_id) const { return command_id == kTogglePermissionCommand || command_id == kToggleExtensionCommand; } string16 NotificationOptionsMenuModel::GetLabelForCommandId(int command_id) const { // TODO(tfarina,johnnyg): Removed this code if we decide to close // notifications after permissions are revoked. if (command_id == kTogglePermissionCommand || command_id == kToggleExtensionCommand) { const Notification& notification = balloon_->notification(); const GURL& origin = notification.origin_url(); DesktopNotificationService* service = balloon_->profile()->GetDesktopNotificationService(); if (origin.SchemeIs(chrome::kExtensionScheme)) { ExtensionsService* ext_service = balloon_->profile()->GetExtensionsService(); const Extension* extension = ext_service->GetExtensionByURL(origin); if (extension) { ExtensionPrefs* extension_prefs = ext_service->extension_prefs(); const std::string& id = extension->id(); if (extension_prefs->GetExtensionState(id) == Extension::ENABLED) return l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE); else return l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE); } } else { if (service->GetContentSetting(origin) == CONTENT_SETTING_ALLOW) { return l10n_util::GetStringFUTF16( IDS_NOTIFICATION_BALLOON_REVOKE_MESSAGE, notification.display_source()); } else { return l10n_util::GetStringFUTF16( IDS_NOTIFICATION_BALLOON_ENABLE_MESSAGE, notification.display_source()); } } } else if (command_id == kOpenContentSettingsCommand) { return l10n_util::GetStringUTF16(IDS_NOTIFICATIONS_SETTINGS_BUTTON); } return string16(); } bool NotificationOptionsMenuModel::IsCommandIdChecked(int /* command_id */) const { // Nothing in the menu is checked. return false; } bool NotificationOptionsMenuModel::IsCommandIdEnabled(int /* command_id */) const { // All the menu options are always enabled. return true; } bool NotificationOptionsMenuModel::GetAcceleratorForCommandId( int /* command_id */, menus::Accelerator* /* accelerator */) { // Currently no accelerators. return false; } void NotificationOptionsMenuModel::ExecuteCommand(int command_id) { DesktopNotificationService* service = balloon_->profile()->GetDesktopNotificationService(); ExtensionsService* ext_service = balloon_->profile()->GetExtensionsService(); const GURL& origin = balloon_->notification().origin_url(); switch (command_id) { case kTogglePermissionCommand: if (service->GetContentSetting(origin) == CONTENT_SETTING_ALLOW) service->DenyPermission(origin); else service->GrantPermission(origin); break; case kToggleExtensionCommand: { const Extension* extension = ext_service->GetExtensionByURL(origin); if (extension) { ExtensionPrefs* extension_prefs = ext_service->extension_prefs(); const std::string& id = extension->id(); if (extension_prefs->GetExtensionState(id) == Extension::ENABLED) ext_service->DisableExtension(id); else ext_service->EnableExtension(id); } break; } case kOpenContentSettingsCommand: { Browser* browser = BrowserList::GetLastActive(); if (browser) static_cast<TabContentsDelegate*>(browser)->ShowContentSettingsWindow( CONTENT_SETTINGS_TYPE_NOTIFICATIONS); break; } default: NOTREACHED(); break; } } <commit_msg>Ensure that the contents settings dialog is displayed for notifications displayed in chrome frame pages.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/notification_options_menu_model.h" #include "app/l10n_util.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/notifications/desktop_notification_service.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/notifications/notifications_prefs_cache.h" #include "chrome/browser/profile.h" #include "chrome/common/content_settings_types.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/url_constants.h" #include "grit/generated_resources.h" #if defined(OS_WIN) #include "chrome/browser/ui/views/browser_dialogs.h" #include "chrome/installer/util/install_util.h" #endif // OS_WIN // Menu commands const int kTogglePermissionCommand = 0; const int kToggleExtensionCommand = 1; const int kOpenContentSettingsCommand = 2; NotificationOptionsMenuModel::NotificationOptionsMenuModel(Balloon* balloon) : ALLOW_THIS_IN_INITIALIZER_LIST(menus::SimpleMenuModel(this)), balloon_(balloon) { const Notification& notification = balloon->notification(); const GURL& origin = notification.origin_url(); if (origin.SchemeIs(chrome::kExtensionScheme)) { const string16 disable_label = l10n_util::GetStringUTF16( IDS_EXTENSIONS_DISABLE); AddItem(kToggleExtensionCommand, disable_label); } else { const string16 disable_label = l10n_util::GetStringFUTF16( IDS_NOTIFICATION_BALLOON_REVOKE_MESSAGE, notification.display_source()); AddItem(kTogglePermissionCommand, disable_label); } const string16 settings_label = l10n_util::GetStringUTF16( IDS_NOTIFICATIONS_SETTINGS_BUTTON); AddItem(kOpenContentSettingsCommand, settings_label); } NotificationOptionsMenuModel::~NotificationOptionsMenuModel() { } bool NotificationOptionsMenuModel::IsLabelForCommandIdDynamic(int command_id) const { return command_id == kTogglePermissionCommand || command_id == kToggleExtensionCommand; } string16 NotificationOptionsMenuModel::GetLabelForCommandId(int command_id) const { // TODO(tfarina,johnnyg): Removed this code if we decide to close // notifications after permissions are revoked. if (command_id == kTogglePermissionCommand || command_id == kToggleExtensionCommand) { const Notification& notification = balloon_->notification(); const GURL& origin = notification.origin_url(); DesktopNotificationService* service = balloon_->profile()->GetDesktopNotificationService(); if (origin.SchemeIs(chrome::kExtensionScheme)) { ExtensionsService* ext_service = balloon_->profile()->GetExtensionsService(); const Extension* extension = ext_service->GetExtensionByURL(origin); if (extension) { ExtensionPrefs* extension_prefs = ext_service->extension_prefs(); const std::string& id = extension->id(); if (extension_prefs->GetExtensionState(id) == Extension::ENABLED) return l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE); else return l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE); } } else { if (service->GetContentSetting(origin) == CONTENT_SETTING_ALLOW) { return l10n_util::GetStringFUTF16( IDS_NOTIFICATION_BALLOON_REVOKE_MESSAGE, notification.display_source()); } else { return l10n_util::GetStringFUTF16( IDS_NOTIFICATION_BALLOON_ENABLE_MESSAGE, notification.display_source()); } } } else if (command_id == kOpenContentSettingsCommand) { return l10n_util::GetStringUTF16(IDS_NOTIFICATIONS_SETTINGS_BUTTON); } return string16(); } bool NotificationOptionsMenuModel::IsCommandIdChecked(int /* command_id */) const { // Nothing in the menu is checked. return false; } bool NotificationOptionsMenuModel::IsCommandIdEnabled(int /* command_id */) const { // All the menu options are always enabled. return true; } bool NotificationOptionsMenuModel::GetAcceleratorForCommandId( int /* command_id */, menus::Accelerator* /* accelerator */) { // Currently no accelerators. return false; } void NotificationOptionsMenuModel::ExecuteCommand(int command_id) { DesktopNotificationService* service = balloon_->profile()->GetDesktopNotificationService(); ExtensionsService* ext_service = balloon_->profile()->GetExtensionsService(); const GURL& origin = balloon_->notification().origin_url(); switch (command_id) { case kTogglePermissionCommand: if (service->GetContentSetting(origin) == CONTENT_SETTING_ALLOW) service->DenyPermission(origin); else service->GrantPermission(origin); break; case kToggleExtensionCommand: { const Extension* extension = ext_service->GetExtensionByURL(origin); if (extension) { ExtensionPrefs* extension_prefs = ext_service->extension_prefs(); const std::string& id = extension->id(); if (extension_prefs->GetExtensionState(id) == Extension::ENABLED) ext_service->DisableExtension(id); else ext_service->EnableExtension(id); } break; } case kOpenContentSettingsCommand: { Browser* browser = BrowserList::GetLastActive(); if (browser) { static_cast<TabContentsDelegate*>(browser)->ShowContentSettingsWindow( CONTENT_SETTINGS_TYPE_NOTIFICATIONS); } else { #if defined(OS_WIN) if (InstallUtil::IsChromeFrameProcess()) { // We may not have a browser if this is a chrome frame process. browser::ShowContentSettingsWindow(NULL, CONTENT_SETTINGS_TYPE_DEFAULT, balloon_->profile()); } #endif // OS_WIN } break; } default: NOTREACHED(); break; } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011-2014. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <string> #include <iostream> #include <vector> #include <atomic> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include "Options.hpp" #include "cxxopts.hpp" using namespace eddic; namespace po = boost::program_options; namespace { std::pair<std::string, std::string> numeric_parser(const std::string& s){ if (s.find("-32") == 0) { return make_pair("32", std::string("true")); } else if (s.find("-64") == 0) { return make_pair("64", std::string("true")); } else { return make_pair(std::string(), std::string()); } } std::atomic<bool> description_flag; po::options_description visible("Usage : eddic [options] source.eddi"); po::options_description all("Usage : eddic [options] source.eddi"); std::unordered_map<std::string, std::vector<std::string>> triggers; cxxopts::Options options("eddic", " source.eddi"); void add_trigger(const std::string& option, const std::vector<std::string>& childs){ triggers[option] = childs; } void init_descriptions(){ po::options_description general("General options"); general.add_options() ("help,h", "Generate this help message") ("assembly,S", "Generate only the assembly") ("keep,k", "Keep the assembly file") ("version", "Print the version of eddic") ("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable") ("debug,g", "Add debugging symbols") ("template-depth", po::value<std::string>()->default_value("100"), "Define the maximum template depth") ("32", "Force the compilation for 32 bits platform") ("64", "Force the compilation for 64 bits platform") ("warning-all", "Enable all the warning messages") ("warning-unused", "Warn about unused variables, parameters and functions") ("warning-cast", "Warn about useless casts") ("warning-effects", "Warn about statements without effect") ("warning-includes", "Warn about useless includes") ; po::options_description display("Display options"); display.add_options() ("ast", "Print the Abstract Syntax Tree representation of the source") ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ") ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)") ("mtac", "Print the medium-level Three Address Code representation of the source") ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed") ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)") ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers") ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization") ("ltac", "Print the final low-level Three Address Code representation of the source") ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)") ; po::options_description optimization("Optimization options"); optimization.add_options() ("Opt,O", po::value<std::string>()->implicit_value("0")->default_value("2"), "Define the optimization level") ("O0", "Disable all optimizations") ("O1", "Enable low-level optimizations") ("O2", "Enable all optimizations improving the speed but do imply a space tradeoff.") ("O3", "Enable all optimizations improving the speed but can increase the size of the program.") ("fglobal-optimization", "Enable optimizer engine") ("fparameter-allocation", "Enable parameter allocation in register") ("fpeephole-optimization", "Enable peephole optimizer") ("fomit-frame-pointer", "Omit frame pointer from functions") ("finline-functions", "Enable inlining") ("fno-inline-functions", "Disable inlining") ("funroll-loops", "Enable Loop Unrolling") ("fcomplete-peel-loops", "Enable Complete Loop Peeling") ; po::options_description backend("Backend options"); backend.add_options() ("log", po::value<std::string>()->default_value("0"), "Define the logging") ("quiet,q", "Do not print anything") ("verbose,v", "Make the compiler verbose") ("single-threaded", "Disable the multi-threaded optimization") ("time", "Activate the timing system") ("stats", "Activate the statistics system") ("input", po::value<std::string>(), "Input file") ; all.add(general).add(display).add(optimization).add(backend); visible.add(general).add(display).add(optimization); try { options.add_options("General") ("h,help", "Generate this help message") ("S,assembly", "Generate only the assembly") ("k,keep", "Keep the assembly file") ("version", "Print the version of eddic") ("o,output", "Set the name of the executable", cxxopts::value<std::string>()->default_value("a.out")) ("g,debug", "Add debugging symbols") ("template-depth", "Define the maximum template depth", cxxopts::value<std::string>()->default_value("100")) ("32", "Force the compilation for 32 bits platform") ("64", "Force the compilation for 64 bits platform") ("warning-all", "Enable all the warning messages") ("warning-unused", "Warn about unused variables, parameters and functions") ("warning-cast", "Warn about useless casts") ("warning-effects", "Warn about statements without effect") ("warning-includes", "Warn about useless includes") ; options.add_options("Display") ("ast", "Print the Abstract Syntax Tree representation of the source") ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ") ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)") ("mtac", "Print the medium-level Three Address Code representation of the source") ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed") ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)") ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers") ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization") ("ltac", "Print the final low-level Three Address Code representation of the source") ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)") ; options.add_options("Optimization") ("O,Opt", "Define the optimization level", cxxopts::value<std::string>()->implicit_value("0")->default_value("2")) ("O0", "Disable all optimizations") ("O1", "Enable low-level optimizations") ("O2", "Enable all optimizations improving the speed but do imply a space tradeoff.") ("O3", "Enable all optimizations improving the speed but can increase the size of the program.") ("fglobal-optimization", "Enable optimizer engine") ("fparameter-allocation", "Enable parameter allocation in register") ("fpeephole-optimization", "Enable peephole optimizer") ("fomit-frame-pointer", "Omit frame pointer from functions") ("finline-functions", "Enable inlining") ("fno-inline-functions", "Disable inlining") ("funroll-loops", "Enable Loop Unrolling") ("fcomplete-peel-loops", "Enable Complete Loop Peeling") ; options.add_options("Backend") ("log", "Define the logging", cxxopts::value<std::string>()->default_value("0")) ("q,quiet", "Do not print anything") ("v,verbose", "Make the compiler verbose") ("single-threaded", "Disable the multi-threaded optimization") ("time", "Activate the timing system") ("stats", "Activate the statistics system") ("input", "Input file", cxxopts::value<std::string>()) ; } catch (const cxxopts::OptionException& e) { std::cout << "error parsing options: " << e.what() << std::endl; exit(1); } add_trigger("warning-all", {"warning-unused", "warning-cast", "warning-effects", "warning-includes"}); //Special triggers for optimization levels add_trigger("__1", {"fpeephole-optimization"}); add_trigger("__2", {"fglobal-optimization", "fomit-frame-pointer", "fparameter-allocation", "finline-functions"}); add_trigger("__3", {"funroll-loops", "fcomplete-peel-loops", "funswitch-loops"}); } inline void trigger_childs(std::shared_ptr<Configuration> configuration, const std::vector<std::string>& childs){ for(auto& child : childs){ configuration->values[child].defined = true; configuration->values[child].value = std::string("true"); } } } //end of anonymous namespace std::shared_ptr<Configuration> eddic::parseOptions(int argc, const char* argv[]) { //Create a new configuration auto configuration = std::make_shared<Configuration>(); try { //Only if the description has not been already defined if(!description_flag.load()){ bool old_value = description_flag.load(); if(description_flag.compare_exchange_strong(old_value, true)){ init_descriptions(); } } //Add the option of the input file po::positional_options_description p; p.add("input", -1); //Create a new set of options po::variables_map options; //Parse the command line options po::store(po::command_line_parser(argc, argv).options(all).extra_parser(numeric_parser).positional(p).run(), options); po::notify(options); //Transfer the options in the eddic configuration for(auto& option : all.options()){ ConfigValue value; if(options.count(option->long_name())){ value.defined = true; value.value = options[option->long_name()].as<std::string>(); } else { value.defined = false; value.value = std::string("false"); } configuration->values[option->long_name()] = value; } if(options.count("O0") + options.count("O1") + options.count("O2") > 1){ std::cout << "Invalid command line options : only one optimization level should be set" << std::endl; return nullptr; } if(options.count("64") && options.count("32")){ std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl; return nullptr; } //Update optimization level based on special switches if(options.count("O0")){ configuration->values["Opt"].value = "0"; } else if(options.count("O1")){ configuration->values["Opt"].value = "1"; } else if(options.count("O2")){ configuration->values["Opt"].value = "2"; } else if(options.count("O3")){ configuration->values["Opt"].value = "3"; } //Triggers dependent options for(auto& trigger : triggers){ if(configuration->option_defined(trigger.first)){ trigger_childs(configuration, trigger.second); } } if(configuration->option_int_value("Opt") >= 1){ trigger_childs(configuration, triggers["__1"]); } if(configuration->option_int_value("Opt") >= 2){ trigger_childs(configuration, triggers["__2"]); } if(configuration->option_int_value("Opt") >= 3){ trigger_childs(configuration, triggers["__3"]); } } catch (const po::ambiguous_option& e) { std::cout << "Invalid command line options: " << e.what() << std::endl; return nullptr; } catch (const po::unknown_option& e) { std::cout << "Invalid command line options: " << e.what() << std::endl; return nullptr; } catch (const po::multiple_occurrences& e) { std::cout << "Invalid command line options: Multiple occurrences of " << e.get_option_name() << std::endl; return nullptr; } return configuration; } bool Configuration::option_defined(const std::string& option_name){ return values[option_name].defined; } std::string Configuration::option_value(const std::string& option_name){ return values[option_name].value; } int Configuration::option_int_value(const std::string& option_name){ return boost::lexical_cast<int>(values[option_name].value); } void eddic::print_help(){ std::cout << visible << std::endl; std::cout << options.help({"General", "Display", "Optimization"}) << std::endl; } void eddic::print_version(){ std::cout << "eddic version 1.2.3" << std::endl; } <commit_msg>Cleanup<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011-2014. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <string> #include <iostream> #include <vector> #include <atomic> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include "Options.hpp" #include "cxxopts.hpp" using namespace eddic; namespace po = boost::program_options; namespace { std::pair<std::string, std::string> numeric_parser(const std::string& s){ if (s.find("-32") == 0) { return make_pair("32", std::string("true")); } else if (s.find("-64") == 0) { return make_pair("64", std::string("true")); } else { return make_pair(std::string(), std::string()); } } std::atomic<bool> description_flag; po::options_description visible("Usage : eddic [options] source.eddi"); po::options_description all("Usage : eddic [options] source.eddi"); std::unordered_map<std::string, std::vector<std::string>> triggers; cxxopts::Options options("eddic", " source.eddi"); void add_trigger(const std::string& option, const std::vector<std::string>& childs){ triggers[option] = childs; } void init_descriptions(){ po::options_description general("General options"); general.add_options() ("help,h", "Generate this help message") ("assembly,S", "Generate only the assembly") ("keep,k", "Keep the assembly file") ("version", "Print the version of eddic") ("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable") ("debug,g", "Add debugging symbols") ("template-depth", po::value<std::string>()->default_value("100"), "Define the maximum template depth") ("32", "Force the compilation for 32 bits platform") ("64", "Force the compilation for 64 bits platform") ("warning-all", "Enable all the warning messages") ("warning-unused", "Warn about unused variables, parameters and functions") ("warning-cast", "Warn about useless casts") ("warning-effects", "Warn about statements without effect") ("warning-includes", "Warn about useless includes") ; po::options_description display("Display options"); display.add_options() ("ast", "Print the Abstract Syntax Tree representation of the source") ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ") ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)") ("mtac", "Print the medium-level Three Address Code representation of the source") ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed") ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)") ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers") ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization") ("ltac", "Print the final low-level Three Address Code representation of the source") ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)") ; po::options_description optimization("Optimization options"); optimization.add_options() ("Opt,O", po::value<std::string>()->implicit_value("0")->default_value("2"), "Define the optimization level") ("O0", "Disable all optimizations") ("O1", "Enable low-level optimizations") ("O2", "Enable all optimizations improving the speed but do imply a space tradeoff.") ("O3", "Enable all optimizations improving the speed but can increase the size of the program.") ("fglobal-optimization", "Enable optimizer engine") ("fparameter-allocation", "Enable parameter allocation in register") ("fpeephole-optimization", "Enable peephole optimizer") ("fomit-frame-pointer", "Omit frame pointer from functions") ("finline-functions", "Enable inlining") ("fno-inline-functions", "Disable inlining") ("funroll-loops", "Enable Loop Unrolling") ("fcomplete-peel-loops", "Enable Complete Loop Peeling") ; po::options_description backend("Backend options"); backend.add_options() ("log", po::value<std::string>()->default_value("0"), "Define the logging") ("quiet,q", "Do not print anything") ("verbose,v", "Make the compiler verbose") ("single-threaded", "Disable the multi-threaded optimization") ("time", "Activate the timing system") ("stats", "Activate the statistics system") ("input", po::value<std::string>(), "Input file") ; all.add(general).add(display).add(optimization).add(backend); visible.add(general).add(display).add(optimization); options.add_options("General") ("h,help", "Generate this help message") ("S,assembly", "Generate only the assembly") ("k,keep", "Keep the assembly file") ("version", "Print the version of eddic") ("o,output", "Set the name of the executable", cxxopts::value<std::string>()->default_value("a.out")) ("g,debug", "Add debugging symbols") ("template-depth", "Define the maximum template depth", cxxopts::value<std::string>()->default_value("100")) ("32", "Force the compilation for 32 bits platform") ("64", "Force the compilation for 64 bits platform") ("warning-all", "Enable all the warning messages") ("warning-unused", "Warn about unused variables, parameters and functions") ("warning-cast", "Warn about useless casts") ("warning-effects", "Warn about statements without effect") ("warning-includes", "Warn about useless includes") ; options.add_options("Display") ("ast", "Print the Abstract Syntax Tree representation of the source") ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ") ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)") ("mtac", "Print the medium-level Three Address Code representation of the source") ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed") ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)") ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers") ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization") ("ltac", "Print the final low-level Three Address Code representation of the source") ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)") ; options.add_options("Optimization") ("O,Opt", "Define the optimization level", cxxopts::value<std::string>()->implicit_value("0")->default_value("2")) ("O0", "Disable all optimizations") ("O1", "Enable low-level optimizations") ("O2", "Enable all optimizations improving the speed but do imply a space tradeoff.") ("O3", "Enable all optimizations improving the speed but can increase the size of the program.") ("fglobal-optimization", "Enable optimizer engine") ("fparameter-allocation", "Enable parameter allocation in register") ("fpeephole-optimization", "Enable peephole optimizer") ("fomit-frame-pointer", "Omit frame pointer from functions") ("finline-functions", "Enable inlining") ("fno-inline-functions", "Disable inlining") ("funroll-loops", "Enable Loop Unrolling") ("fcomplete-peel-loops", "Enable Complete Loop Peeling") ; options.add_options("Backend") ("log", "Define the logging", cxxopts::value<std::string>()->default_value("0")) ("q,quiet", "Do not print anything") ("v,verbose", "Make the compiler verbose") ("single-threaded", "Disable the multi-threaded optimization") ("time", "Activate the timing system") ("stats", "Activate the statistics system") ("input", "Input file", cxxopts::value<std::string>()) ; add_trigger("warning-all", {"warning-unused", "warning-cast", "warning-effects", "warning-includes"}); //Special triggers for optimization levels add_trigger("__1", {"fpeephole-optimization"}); add_trigger("__2", {"fglobal-optimization", "fomit-frame-pointer", "fparameter-allocation", "finline-functions"}); add_trigger("__3", {"funroll-loops", "fcomplete-peel-loops", "funswitch-loops"}); } inline void trigger_childs(std::shared_ptr<Configuration> configuration, const std::vector<std::string>& childs){ for(auto& child : childs){ configuration->values[child].defined = true; configuration->values[child].value = std::string("true"); } } } //end of anonymous namespace std::shared_ptr<Configuration> eddic::parseOptions(int argc, const char* argv[]) { //Create a new configuration auto configuration = std::make_shared<Configuration>(); try { //Only if the description has not been already defined if(!description_flag.load()){ bool old_value = description_flag.load(); if(description_flag.compare_exchange_strong(old_value, true)){ init_descriptions(); } } //Add the option of the input file po::positional_options_description p; p.add("input", -1); //Create a new set of options po::variables_map options; //Parse the command line options po::store(po::command_line_parser(argc, argv).options(all).extra_parser(numeric_parser).positional(p).run(), options); po::notify(options); //Transfer the options in the eddic configuration for(auto& option : all.options()){ ConfigValue value; if(options.count(option->long_name())){ value.defined = true; value.value = options[option->long_name()].as<std::string>(); } else { value.defined = false; value.value = std::string("false"); } configuration->values[option->long_name()] = value; } if(options.count("O0") + options.count("O1") + options.count("O2") > 1){ std::cout << "Invalid command line options : only one optimization level should be set" << std::endl; return nullptr; } if(options.count("64") && options.count("32")){ std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl; return nullptr; } //Update optimization level based on special switches if(options.count("O0")){ configuration->values["Opt"].value = "0"; } else if(options.count("O1")){ configuration->values["Opt"].value = "1"; } else if(options.count("O2")){ configuration->values["Opt"].value = "2"; } else if(options.count("O3")){ configuration->values["Opt"].value = "3"; } //Triggers dependent options for(auto& trigger : triggers){ if(configuration->option_defined(trigger.first)){ trigger_childs(configuration, trigger.second); } } if(configuration->option_int_value("Opt") >= 1){ trigger_childs(configuration, triggers["__1"]); } if(configuration->option_int_value("Opt") >= 2){ trigger_childs(configuration, triggers["__2"]); } if(configuration->option_int_value("Opt") >= 3){ trigger_childs(configuration, triggers["__3"]); } } catch (const po::ambiguous_option& e) { std::cout << "Invalid command line options: " << e.what() << std::endl; return nullptr; } catch (const po::unknown_option& e) { std::cout << "Invalid command line options: " << e.what() << std::endl; return nullptr; } catch (const po::multiple_occurrences& e) { std::cout << "Invalid command line options: Multiple occurrences of " << e.get_option_name() << std::endl; return nullptr; } return configuration; } bool Configuration::option_defined(const std::string& option_name){ return values[option_name].defined; } std::string Configuration::option_value(const std::string& option_name){ return values[option_name].value; } int Configuration::option_int_value(const std::string& option_name){ return boost::lexical_cast<int>(values[option_name].value); } void eddic::print_help(){ std::cout << visible << std::endl; std::cout << options.help({"General", "Display", "Optimization"}) << std::endl; } void eddic::print_version(){ std::cout << "eddic version 1.2.3" << std::endl; } <|endoftext|>
<commit_before>// RSHELL.CPP // Main source code for rshell // enable debug messages //#define RSHELL_DEBUG // prepend "[RSHELL]" to prompt, helps to differ from bash #define RSHELL_PREPEND #define COL_DEFAULT "\033[39m" #define COL_PREPEND "\033[32m" #include "unistd.h" #include "sys/wait.h" #include "stdio.h" #include "errno.h" #include <iostream> #include <string> #include <vector> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/regex.hpp> #include <boost/regex.hpp> #include "rshell.h" const char* CONN_AMP = "&&"; const char* CONN_PIPE = "||"; const char* CONN_SEMIC = ";"; const char* TOKN_COMMENT = "#"; const char* REDIR_SYM_PIPE = "|"; const char* REDIR_SYM_INPUT = "<"; const char* REDIR_SYM_OUTPUT = ">"; enum REDIR_TYPE { REDIR_TYPE_CMD = 0x001, REDIR_TYPE_PIPE = 0x002, REDIR_TYPE_INPUT = 0x004, REDIR_TYPE_OUTPUT = 0x008, REDIR_TYPE_OUTPUT_APP = 0x010 }; struct redir { redir(int t) : type(t) {} redir(int r, int l, int t) : type(t) { pids[0] = r; pids[1] = l; } int type; int pipefd[2] = { 0, 1 }; int pids[2]; const char* redir_file; }; /* Initialize environment */ void init() {} /* Main loop - controls command line, parsing, and execution logic */ int run() { std::vector<std::string> tokens_spc; std::vector<std::string> tokens_redir; std::vector<std::string> tokens_word; std::string usr_input; int prev_exit_code = 0; while(true) { bool skip_cmd = false; std::string prev_spc = ""; usr_input = prompt(); // regex '||', '&&', ';', or '#' tokens_spc = tokenize(usr_input, "(\\|\\||\\&\\&|;|#)"); for(unsigned int i = 0; i < tokens_spc.size(); i++) { std::string spc = tokens_spc.at(i); boost::trim(spc); #ifdef RSHELL_DEBUG std::cout << "<" << spc << ">" << std::endl; #endif if(spc == "") continue; // assumption: a connector token has no whitespace if( spc == std::string(CONN_AMP)) { if(i == 0 || prev_spc != "") { std::cout << "syntax error: bad token \"" << CONN_AMP << "\"\n"; break; } else if(prev_exit_code != 0 && i != 0) { skip_cmd = true; continue; } prev_spc = spc; continue; } else if( spc == std::string(CONN_PIPE)) { if(i == 0 || prev_spc != "") { std::cout << "syntax error: bad token \"" << CONN_PIPE << "\"\n"; break; } else if(prev_exit_code == 0 && i != 0) { skip_cmd = true; continue; } prev_spc = spc; continue; } else if( spc == std::string(CONN_SEMIC)) { if(i == 0) { std::cout << "syntax error: bad token \"" << CONN_SEMIC << "\"\n"; break; } else { prev_exit_code = 0; skip_cmd = false; prev_spc = spc; continue; } } else if( spc == std::string(TOKN_COMMENT)) { break; } prev_spc = ""; if(skip_cmd) continue; tokens_redir = tokenize(spc, "\\||<|>"); // regex '|', '<', or '>' int syntax_err = 0; std::vector<std::string> cmd_set; std::vector<struct redir> redir_set; // redirection syntax pass for(unsigned int redir_i = 0; redir_i < tokens_redir.size(); redir_i++) { std::string cmd = tokens_redir.at(redir_i); boost::trim(cmd); std::cout << "<" << cmd << ">\n"; if(cmd == "") { // tokens_redir.erase(tokens_redir.begin() + redir_i); std::cout << "syntax error: unexpected null command\n"; syntax_err = 2; break; } if(cmd == REDIR_SYM_PIPE) { // '|' piping operator if(redir_i == 0) { syntax_err = 1; std::cout << "syntax error: token \"|\" at start of command\n"; break; } else if(redir_set.back().type != REDIR_TYPE_CMD) { syntax_err = 1; std::cout << "syntax error: bad token near \"|\"\n"; break; } redir_set.push_back(redir(REDIR_TYPE_PIPE)); continue; // default action } else if(cmd == REDIR_SYM_INPUT) { // '<' input redirection operator if(redir_i == tokens_redir.size() - 1) { syntax_err = 1; std::cout << "syntax error: expected file for input \"<\"\n"; break; } redir_set.push_back(redir(REDIR_TYPE_INPUT)); continue; // default action } else if(cmd == REDIR_SYM_OUTPUT) { // '>' output redirection operator if(redir_i == tokens_redir.size() - 1) { syntax_err = 1; std::cout << "syntax error: expected file for output \">\"\n"; break; } if(redir_i > 0 && tokens_redir.at(redir_i-1) == REDIR_SYM_OUTPUT) { // '>>' operator redir_set.pop_back(); // erase old TYPE_OUTPUT redir_set.push_back(REDIR_TYPE_OUTPUT_APP); continue; } redir_set.push_back(REDIR_TYPE_OUTPUT); continue; // default action } else { redir_set.push_back(redir(REDIR_TYPE_CMD)); cmd_set.push_back(cmd); } } if(syntax_err != 0) break; // command running pass for(unsigned int cmd_i = 0; cmd_i < cmd_set.size(); cmd_i++) { auto cmd = cmd_set.at(cmd_i); tokens_word = toksplit(cmd, " "); for(unsigned int j = 0; j < tokens_word.size(); j++) { std::string word = tokens_word.at(j); // using boost for convenience - this can be implemented manually boost::trim(word); // kill empty words if(word == "") tokens_word.erase(tokens_word.begin() + j); } std::vector<char*> cmd_argv(tokens_word.size() + 1); for(unsigned int k = 0; k < tokens_word.size(); k++) { cmd_argv[k] = &tokens_word[k][0]; #ifdef RSHELL_DEBUG std::cout << "\t" << "<" << tokens_word.at(k) << ">" << std::endl; #endif } // exit only if first word is "exit", after formatting if(tokens_word.at(0) == "exit") return 0; prev_exit_code = execute(cmd_argv[0], cmd_argv.data()); // if execvp returned and had error, stop the process // if(err_num == 1) return 1; } } } return 0; } /* Prints prompt text and takes in raw command line input */ std::string prompt() { char hostname[HOST_NAME_MAX]; if(gethostname(hostname, HOST_NAME_MAX) == -1) perror("gethostname"); #ifdef RSHELL_PREPEND std::cout << COL_PREPEND << "[RSHELL] "; #endif std::cout << COL_DEFAULT; std::cout << getlogin() << "@" << hostname; std::cout << "$ " << std::flush; std::string input_raw; std::getline(std::cin, input_raw); return input_raw; } /* fork and exec a program, complete error checking */ int execute(const char* path, char* const argv[]) { #ifdef RSHELL_DEBUG std::cout << "executing " << path << std::endl; #endif int pid = fork(); #ifdef RSHELL_DEBUG std::cout << "created process with id " << pid << std::endl; #endif if(pid == -1) { perror("fork"); return -1; } else if(pid == 0) { execvp(path, argv); perror(path); exit(1); } else { int exit_code; // pass exit code along if(waitpid(pid, &exit_code, 0) == -1) perror("waitpid"); return exit_code; } return 0; } /* Overload to tokenize by whitespace */ std::vector<std::string> tokenize(std::string s) { return tokenize(s, "\\s"); } /* Tokenize a string using boost regex */ std::vector<std::string> tokenize(std::string s, std::string r) { std::vector<std::string> token_vec; // boost::algorithm::split_regex(token_vec, s, boost::regex(r)); std::string::const_iterator s_start, s_end; s_start = s.begin(); s_end = s.end(); boost::match_results<std::string::const_iterator> results; boost::match_flag_type flags = boost::match_default; while(boost::regex_search(s_start, s_end, results, boost::regex(r), flags)) { token_vec.push_back(std::string(s_start, results[0].first)); token_vec.push_back(results[0]); s_start = results[0].second; flags |= boost::match_prev_avail; flags |= boost::match_not_bob; } token_vec.push_back(std::string(s_start, s_end)); // scrub vector of empty fields for(unsigned int i = 0; i < token_vec.size(); i++) { #ifdef RSHELL_DEBUG // std::cout << "[" << token_vec.at(i) << "]" << std::endl; #endif if(token_vec.at(i) == "") token_vec.erase(token_vec.begin() + i); } return token_vec; } /* Tokenize a string using boost split */ std::vector<std::string> toksplit(std::string s, std::string toks) { std::vector<std::string> token_vec; boost::split(token_vec, s, boost::is_any_of(toks), boost::token_compress_on); return token_vec; } <commit_msg>improved debug print<commit_after>// RSHELL.CPP // Main source code for rshell // enable debug messages and macros #define RSHELL_DEBUG // prepend "[RSHELL]" to prompt, helps to differ from bash #define RSHELL_PREPEND #define COL_DEFAULT "\033[39m" #define COL_PREPEND "\033[32m" #define COL_DEBUG "\033[33m" // debug print macro #ifdef RSHELL_DEBUG #define _PRINT(stream) std::cout << COL_DEBUG << "[DEBUG] " \ << COL_DEFAULT << stream \ << std::endl << std::flush; #else #define _PRINT(stream) #endif #include "unistd.h" #include "sys/wait.h" #include "stdio.h" #include "errno.h" #include <iostream> #include <string> #include <vector> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/regex.hpp> #include <boost/regex.hpp> #include "rshell.h" const char* CONN_AMP = "&&"; const char* CONN_PIPE = "||"; const char* CONN_SEMIC = ";"; const char* TOKN_COMMENT = "#"; const char* REDIR_SYM_PIPE = "|"; const char* REDIR_SYM_INPUT = "<"; const char* REDIR_SYM_OUTPUT = ">"; enum REDIR_TYPE { REDIR_TYPE_CMD = 0x001, REDIR_TYPE_PIPE = 0x002, REDIR_TYPE_INPUT = 0x004, REDIR_TYPE_OUTPUT = 0x008, REDIR_TYPE_OUTPUT_APP = 0x010 }; struct redir { redir(int t) : type(t) {} redir(int r, int l, int t) : type(t) { pids[0] = r; pids[1] = l; } int type; int pipefd[2] = { 0, 1 }; int pids[2]; const char* redir_file; }; /* Initialize environment */ void init() {} /* Main loop - controls command line, parsing, and execution logic */ int run() { std::vector<std::string> tokens_spc; std::vector<std::string> tokens_redir; std::vector<std::string> tokens_word; std::string usr_input; int prev_exit_code = 0; _PRINT("starting in debug mode"); while(true) { bool skip_cmd = false; std::string prev_spc = ""; usr_input = prompt(); // regex '||', '&&', ';', or '#' tokens_spc = tokenize(usr_input, "(\\|\\||\\&\\&|;|#)"); for(unsigned int i = 0; i < tokens_spc.size(); i++) { std::string spc = tokens_spc.at(i); boost::trim(spc); _PRINT("initial parser: <" << spc << ">") if(spc == "") continue; // assumption: a connector token has no whitespace if( spc == std::string(CONN_AMP)) { if(i == 0 || prev_spc != "") { std::cout << "syntax error: bad token \"" << CONN_AMP << "\"\n"; break; } else if(prev_exit_code != 0 && i != 0) { skip_cmd = true; continue; } prev_spc = spc; continue; } else if( spc == std::string(CONN_PIPE)) { if(i == 0 || prev_spc != "") { std::cout << "syntax error: bad token \"" << CONN_PIPE << "\"\n"; break; } else if(prev_exit_code == 0 && i != 0) { skip_cmd = true; continue; } prev_spc = spc; continue; } else if( spc == std::string(CONN_SEMIC)) { if(i == 0) { std::cout << "syntax error: bad token \"" << CONN_SEMIC << "\"\n"; break; } else { prev_exit_code = 0; skip_cmd = false; prev_spc = spc; continue; } } else if( spc == std::string(TOKN_COMMENT)) { break; } prev_spc = ""; if(skip_cmd) continue; tokens_redir = tokenize(spc, "\\||<|>"); // regex '|', '<', or '>' int syntax_err = 0; std::vector<std::string> cmd_set; std::vector<struct redir> redir_set; // redirection syntax pass for(unsigned int redir_i = 0; redir_i < tokens_redir.size(); redir_i++) { std::string cmd = tokens_redir.at(redir_i); boost::trim(cmd); if(cmd == "") { // tokens_redir.erase(tokens_redir.begin() + redir_i); std::cout << "syntax error: unexpected null command\n"; syntax_err = 2; break; } cmd_set.push_back(cmd); if(cmd == REDIR_SYM_PIPE) { // '|' piping operator if(redir_i == 0) { syntax_err = 1; std::cout << "syntax error: token \"|\" at start of command\n"; break; } else if(redir_set.back().type != REDIR_TYPE_CMD) { syntax_err = 1; std::cout << "syntax error: bad token near \"|\"\n"; break; } redir_set.push_back(redir(REDIR_TYPE_PIPE)); continue; // default action } else if(cmd == REDIR_SYM_INPUT) { // '<' input redirection operator if(redir_i == tokens_redir.size() - 1) { syntax_err = 1; std::cout << "syntax error: expected file for input \"<\"\n"; break; } redir_set.push_back(redir(REDIR_TYPE_INPUT)); continue; // default action } else if(cmd == REDIR_SYM_OUTPUT) { // '>' output redirection operator if(redir_i == tokens_redir.size() - 1) { syntax_err = 1; std::cout << "syntax error: expected file for output \">\"\n"; break; } if(redir_i > 0 && tokens_redir.at(redir_i-1) == REDIR_SYM_OUTPUT) { // '>>' operator redir_set.pop_back(); // erase old TYPE_OUTPUT cmd_set.pop_back(); redir_set.push_back(REDIR_TYPE_OUTPUT_APP); continue; } redir_set.push_back(REDIR_TYPE_OUTPUT); continue; // default action } else { redir_set.push_back(redir(REDIR_TYPE_CMD)); } } if(syntax_err != 0) break; for(unsigned int test_i = 0; test_i < cmd_set.size(); test_i++) { _PRINT("redir parser: \"" << cmd_set.at(test_i) << "\" : " << redir_set.at(test_i).type) } // command running pass for(unsigned int cmd_i = 0; cmd_i < cmd_set.size(); cmd_i++) { auto cmd = cmd_set.at(cmd_i); tokens_word = toksplit(cmd, " "); for(unsigned int j = 0; j < tokens_word.size(); j++) { std::string word = tokens_word.at(j); // using boost for convenience - this can be implemented manually boost::trim(word); // kill empty words if(word == "") tokens_word.erase(tokens_word.begin() + j); } std::vector<char*> cmd_argv(tokens_word.size() + 1); for(unsigned int k = 0; k < tokens_word.size(); k++) { cmd_argv[k] = &tokens_word[k][0]; _PRINT("\t" << "<" << tokens_word.at(k) << ">"); } // exit only if first word is "exit", after formatting if(tokens_word.at(0) == "exit") return 0; prev_exit_code = execute(cmd_argv[0], cmd_argv.data()); // if execvp returned and had error, stop the process // if(err_num == 1) return 1; } } } return 0; } /* Prints prompt text and takes in raw command line input */ std::string prompt() { char hostname[HOST_NAME_MAX]; if(gethostname(hostname, HOST_NAME_MAX) == -1) perror("gethostname"); #ifdef RSHELL_PREPEND std::cout << COL_PREPEND << "[RSHELL] "; #endif std::cout << COL_DEFAULT; std::cout << getlogin() << "@" << hostname; std::cout << "$ " << std::flush; std::string input_raw; std::getline(std::cin, input_raw); return input_raw; } /* fork and exec a program, complete error checking */ int execute(const char* path, char* const argv[]) { _PRINT("executing " << path); int pid = fork(); _PRINT("created process with id " << pid) if(pid == -1) { perror("fork"); return -1; } else if(pid == 0) { execvp(path, argv); perror(path); exit(1); } else { int exit_code; // pass exit code along if(waitpid(pid, &exit_code, 0) == -1) perror("waitpid"); return exit_code; } return 0; } /* Overload to tokenize by whitespace */ std::vector<std::string> tokenize(std::string s) { return tokenize(s, "\\s"); } /* Tokenize a string using boost regex */ std::vector<std::string> tokenize(std::string s, std::string r) { std::vector<std::string> token_vec; // boost::algorithm::split_regex(token_vec, s, boost::regex(r)); std::string::const_iterator s_start, s_end; s_start = s.begin(); s_end = s.end(); boost::match_results<std::string::const_iterator> results; boost::match_flag_type flags = boost::match_default; while(boost::regex_search(s_start, s_end, results, boost::regex(r), flags)) { token_vec.push_back(std::string(s_start, results[0].first)); token_vec.push_back(results[0]); s_start = results[0].second; flags |= boost::match_prev_avail; flags |= boost::match_not_bob; } token_vec.push_back(std::string(s_start, s_end)); // scrub vector of empty fields for(unsigned int i = 0; i < token_vec.size(); i++) { if(token_vec.at(i) == "") token_vec.erase(token_vec.begin() + i); } return token_vec; } /* Tokenize a string using boost split */ std::vector<std::string> toksplit(std::string s, std::string toks) { std::vector<std::string> token_vec; boost::split(token_vec, s, boost::is_any_of(toks), boost::token_compress_on); return token_vec; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <boost/tokenizer.hpp> //Boost tokenizer #include <unistd.h> // Fork() #include <sys/types.h> // Wait() #include <sys/wait.h> // Wait() #include <vector> #include <stdio.h> //Perror() #include <errno.h> // Perror() #include <algorithm> using namespace std; using namespace boost; int main() { while(true) //Shell runs until the exit command { cout << "$"; // Prints command prompt string commandLine; char* arguments[]; getline(cin, commandLine); // Accounts for comments by removing parts that are comments // TODO: Account for escape character + comment (\#) if(commandLine.find(" #") != -1) { commandLine = commandLine.substr(commandLine.find(" #")); } // Finds locations of connectors; a && b, && has a location of 3 vector<int> connectorLocs; unsigned int marker = 0; // Marks location to start find() from while((int loc = commandLine.find("&&", marker)) != -1) { connectorLocs.push_back(loc); marker = loc + 2; // Starts searching after "&&" } marker = 0; while((int loc = commandLine.find("||", marker)) != -1) { connectorLocs.push_back(loc); marker = loc + 2; // Starts searching after "||" } marker = 0; while((int loc = commandLine.find(";", marker)) != -1) { connectorLocs.push_back(loc); marker = loc + 1; // Starts searching after ";" } connectorLocs.push_back(0); // Will be sorted and put in beginning sort(connectorLocs.begin(), connectorLocs.end()); // Sorted to find each subcommand substring connectorLocs.push_back(commandLine.size()); // One past end index will act like connector // Runs through subcommands and runs each one // Works for connectors with nothing between them (tokenizer will have "" => syntax error, which is expected) for(int i = 0; i < connectorLocs.size() - 1; ++i) // # of subcommands == # of connectors - 1 (including 0, one-past-end) { string command; vector<char*> args; char_seperator<char> delim(" "); tokenizer<char_seperator<char>> tok(commandLine, delim); auto iter = tok.begin(); command = *iter; ++iter; for(; iter != tok.end(); ++iter) { args.push_back(iter->c_str()); } } } return 0; } <commit_msg>Fixed compile errors on rshell<commit_after>#include <iostream> #include <string> #include <boost/tokenizer.hpp> //Boost tokenizer #include <unistd.h> // Fork() #include <sys/types.h> // Wait() #include <sys/wait.h> // Wait() #include <vector> #include <stdio.h> //Perror() #include <errno.h> // Perror() #include <algorithm> using namespace std; using namespace boost; int main() { while(true) //Shell runs until the exit command { cout << "$"; // Prints command prompt string commandLine; getline(cin, commandLine); // Accounts for comments by removing parts that are comments // TODO: Account for escape character + comment (\#) if(commandLine.find(" #") != string::npos) { commandLine = commandLine.substr(commandLine.find(" #")); } // Finds locations of connectors; a && b, && has a location of 3 vector<unsigned int> connectorLocs; unsigned int marker = 0; // Marks location to start find() from unsigned int loc = commandLine.find("&&", marker); while(loc != string::npos) { connectorLocs.push_back(loc); marker = loc + 2; // Starts searching after "&&" loc = commandLine.find("&&", marker); } marker = 0; loc = commandLine.find("||", marker); while(loc != string::npos) { connectorLocs.push_back(loc); marker = loc + 2; // Starts searching after "||" loc = commandLine.find("||", marker); } marker = 0; loc = commandLine.find(";", marker); while(loc != string::npos) { connectorLocs.push_back(loc); marker = loc + 1; // Starts searching after ";" loc = commandLine.find(";", marker); } connectorLocs.push_back(0); // Will be sorted and put in beginning sort(connectorLocs.begin(), connectorLocs.end()); // Sorted to find each subcommand substring connectorLocs.push_back(commandLine.size()); // One past end index will act like connector // Runs through subcommands and runs each one // Works for connectors with nothing between them (tokenizer will have "" => syntax error, which is expected) for(unsigned int i = 0; i < connectorLocs.size() - 1; ++i) // # of subcommands == # of connectors - 1 (including 0, one-past-end) { string command; vector<char*> args; char_separator<char> delim(" "); tokenizer<char_separator<char>> tok(commandLine, delim); auto iter = tok.begin(); command = *iter; ++iter; for(; iter != tok.end(); ++iter) { char* c = const_cast<char*> (iter->c_str()); args.push_back(c); } } } return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2015, Hobu Inc. ([email protected]) * * 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 Hobu, Inc. or Flaxen Geo Consulting 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 <pdal/Options.hpp> #include <pdal/PDALUtils.hpp> #include <iostream> #include <sstream> #include <iostream> namespace pdal { Option::Option(const boost::property_tree::ptree& tree) { using namespace boost::property_tree; m_name = tree.get<std::string>("Name"); m_value = tree.get<std::string>("Value"); m_description = tree.count("Description") ? tree.get<std::string>("Description") : ""; } #if !defined(PDAL_COMPILER_MSVC) // explicit specialization: // if insert a bool, we don't want it to be "0" or "1" (which is // what lexical_cast would do) template<> void Option::setValue(const bool& value) { m_value = value ? "true" : "false"; } // explicit specialization: // if we want to insert a string, we don't need lexical_cast template<> void Option::setValue(const std::string& value) { m_value = value; } #endif void Option::toMetadata(MetadataNode& parent) const { MetadataNode child = parent.add(getName()); child.add("value", getValue<std::string>()); child.add("description", getDescription()); } //--------------------------------------------------------------------------- Options::Options(const Options& rhs) : m_options(rhs.m_options) {} Options::Options(const Option& opt) { add(opt); } bool Option::nameValid(const std::string& name, bool reportError) { bool valid = (parse(name, 0) == name.size()); if (reportError) { std::ostringstream oss; oss << "Invalid option name '" << name << "'. Options must " "consist of only lowercase letters, numbers and '_'."; Utils::printError(oss.str()); } return valid; } Options::Options(const boost::property_tree::ptree& tree) { for (auto iter = tree.begin(); iter != tree.end(); ++iter) { assert(iter->first == "Option"); Option opt(iter->second); add(opt); } } void Options::add(const Option& option) { assert(Option::nameValid(option.getName(), true)); m_options.insert(std::pair<std::string, Option>(option.getName(), option)); } void Options::remove(const Option& option) { m_options.erase(option.getName()); } Option& Options::getOptionByRef(const std::string& name) { auto iter = m_options.find(name); if (iter == m_options.end()) { std::ostringstream oss; oss << "Options::getOptionByRef: Required option '" << name << "' was not found on this stage"; throw Option::not_found(oss.str()); } return iter->second; } const Option& Options::getOption(const std::string& name) const { assert(Option::nameValid(name, true)); auto iter = m_options.find(name); if (iter == m_options.end()) { std::ostringstream oss; oss << "Options::getOption: Required option '" << name << "' was not found on this stage"; throw Option::not_found(oss.str()); } return iter->second; } std::vector<Option> Options::getOptions(std::string const& name) const { std::vector<Option> output; // If we have an empty name, return them all if (name.empty()) { for (auto it = m_options.begin(); it != m_options.end(); ++it) { output.push_back(it->second); } } else { auto ret = m_options.equal_range(name); for (auto it = ret.first; it != ret.second; ++it) { output.push_back(it->second); } } return output; } bool Options::hasOption(std::string const& name) const { try { (void)getOption(name); return true; } catch (Option::not_found) {} return false; } void Options::dump() const { std::cout << *this; } std::ostream& operator<<(std::ostream& ostr, const Options& options) { const boost::property_tree::ptree tree = pdal::Utils::toPTree(options); boost::property_tree::write_json(ostr, tree); return ostr; } } // namespace pdal <commit_msg>Fix reporting check for nameValid().<commit_after>/****************************************************************************** * Copyright (c) 2015, Hobu Inc. ([email protected]) * * 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 Hobu, Inc. or Flaxen Geo Consulting 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 <pdal/Options.hpp> #include <pdal/PDALUtils.hpp> #include <iostream> #include <sstream> #include <iostream> namespace pdal { Option::Option(const boost::property_tree::ptree& tree) { using namespace boost::property_tree; m_name = tree.get<std::string>("Name"); m_value = tree.get<std::string>("Value"); m_description = tree.count("Description") ? tree.get<std::string>("Description") : ""; } #if !defined(PDAL_COMPILER_MSVC) // explicit specialization: // if insert a bool, we don't want it to be "0" or "1" (which is // what lexical_cast would do) template<> void Option::setValue(const bool& value) { m_value = value ? "true" : "false"; } // explicit specialization: // if we want to insert a string, we don't need lexical_cast template<> void Option::setValue(const std::string& value) { m_value = value; } #endif void Option::toMetadata(MetadataNode& parent) const { MetadataNode child = parent.add(getName()); child.add("value", getValue<std::string>()); child.add("description", getDescription()); } //--------------------------------------------------------------------------- Options::Options(const Options& rhs) : m_options(rhs.m_options) {} Options::Options(const Option& opt) { add(opt); } bool Option::nameValid(const std::string& name, bool reportError) { bool valid = (parse(name, 0) == name.size()); if (!valid && reportError) { std::ostringstream oss; oss << "Invalid option name '" << name << "'. Options must " "consist of only lowercase letters, numbers and '_'."; Utils::printError(oss.str()); } return valid; } Options::Options(const boost::property_tree::ptree& tree) { for (auto iter = tree.begin(); iter != tree.end(); ++iter) { assert(iter->first == "Option"); Option opt(iter->second); add(opt); } } void Options::add(const Option& option) { assert(Option::nameValid(option.getName(), true)); m_options.insert(std::pair<std::string, Option>(option.getName(), option)); } void Options::remove(const Option& option) { m_options.erase(option.getName()); } Option& Options::getOptionByRef(const std::string& name) { auto iter = m_options.find(name); if (iter == m_options.end()) { std::ostringstream oss; oss << "Options::getOptionByRef: Required option '" << name << "' was not found on this stage"; throw Option::not_found(oss.str()); } return iter->second; } const Option& Options::getOption(const std::string& name) const { assert(Option::nameValid(name, true)); auto iter = m_options.find(name); if (iter == m_options.end()) { std::ostringstream oss; oss << "Options::getOption: Required option '" << name << "' was not found on this stage"; throw Option::not_found(oss.str()); } return iter->second; } std::vector<Option> Options::getOptions(std::string const& name) const { std::vector<Option> output; // If we have an empty name, return them all if (name.empty()) { for (auto it = m_options.begin(); it != m_options.end(); ++it) { output.push_back(it->second); } } else { auto ret = m_options.equal_range(name); for (auto it = ret.first; it != ret.second; ++it) { output.push_back(it->second); } } return output; } bool Options::hasOption(std::string const& name) const { try { (void)getOption(name); return true; } catch (Option::not_found) {} return false; } void Options::dump() const { std::cout << *this; } std::ostream& operator<<(std::ostream& ostr, const Options& options) { const boost::property_tree::ptree tree = pdal::Utils::toPTree(options); boost::property_tree::write_json(ostr, tree); return ostr; } } // namespace pdal <|endoftext|>
<commit_before>// // Macro designed for use with the AliAnalysisTaskDptDptCorrelations task. // // Author: Claude Pruneau, Wayne State ///////////////////////////////////////////////////////////////////////////////// AliAnalysisTaskDptDptCorrelations *AddTaskDptDptCorrelations(int singlesOnly = 1, int useWeights = 0, int centralityMethod = 4) { // Set Default Configuration of this analysis // ========================================== int debugLevel = 0; int singlesOnly = 1; int useWeights = 0; int rejectPileup = 1; int rejectPairConversion = 1; int sameFilter = 1; int centralityMethod = 4; int nCentrality = 10; double minCentrality[] = { 0.5, 5., 10., 20., 30., 40., 50., 60., 70., 80. }; double maxCentrality[] = { 5.0, 10., 20., 30., 40., 50., 60., 70., 80., 90. }; int nChargeSets = 1; int chargeSets[] = { 1, 0, 3 }; double zMin = -10.; double zMax = 10.; double ptMin = 0.2; double ptMax = 2.0; double etaMin = -1.0; double etaMax = 1.0; double dcaZMin = -3.0; double dcaZMax = 3.0; double dcaXYMin = -3.0; double dcaXYMax = 3.0; double dedxMin = 0.0; double dedxMax = 20000.0; int nClusterMin = 70; int trackFilterBit = 128; int requestedCharge1 = 1; //default int requestedCharge2 = -1; //default // Get the pointer to the existing analysis manager via the static access method. // ============================================================================== AliAnalysisManager *analysisManager = AliAnalysisManager::GetAnalysisManager(); if (!analysisManager) { ::Error("AddTaskDptDptCorrelations", "No analysis manager to connect to."); return NULL; } TString part1Name; TString part2Name; TString eventName; TString prefixName = "Corr_"; TString pileupRejecSuffix = "_PileupRejec"; TString pairRejecSuffix = "_PairRejec"; TString calibSuffix = "_calib"; TString singlesOnlySuffix = "_SO"; TString suffix; TString inputPath = "."; TString outputPath = "."; TString baseName; TString listName; TString taskName; TString inputHistogramFileName; TString outputHistogramFileName; // Create the task and add subtask. // =========================================================================== int iTask = 0; // task counter AliAnalysisDataContainer *taskInputContainer; AliAnalysisDataContainer *taskOutputContainer; for (int iCentrality=0; iCentrality < nCentrality; ++iCentrality) { for (int iChargeSet=0; iChargeSet < nChargeSets; iChargeSet++) { switch (chargeSets[iChargeSet]) { case 0: part1Name = "P_"; part2Name = "P_"; requestedCharge1 = 1; requestedCharge2 = 1; sameFilter = 1; break; case 1: part1Name = "P_"; part2Name = "M_"; requestedCharge1 = 1; requestedCharge2 = -1; sameFilter = 0; break; case 2: part1Name = "M_"; part2Name = "P_"; requestedCharge1 = -1; requestedCharge2 = 1; sameFilter = 0; break; case 3: part1Name = "M_"; part2Name = "M_"; requestedCharge1 = -1; requestedCharge2 = -1; sameFilter = 1; break; } //part1Name += int(1000*etaMin); part1Name += "eta"; part1Name += int(1000*etaMax); part1Name += "_"; part1Name += int(1000*ptMin); part1Name += "pt"; part1Name += int(1000*ptMax); part1Name += "_"; //part2Name += int(1000*etaMin); part2Name += "eta"; part2Name += int(1000*etaMax); part2Name += "_"; part2Name += int(1000*ptMin); part2Name += "pt"; part2Name += int(1000*ptMax); part2Name += "_"; eventName = ""; eventName += int(10.*minCentrality[iCentrality] ); eventName += "Vo"; eventName += int(10.*maxCentrality[iCentrality] ); //eventName += "_"; //eventName += int(10*zMin ); //eventName += "Z"; //eventName += int(10*zMax ); if (rejectPileup) eventName += pileupRejecSuffix; if (rejectPairConversion) eventName += pairRejecSuffix; baseName = prefixName; baseName += part1Name; baseName += part2Name; baseName += eventName; listName = baseName; taskName = baseName; //inputHistogramFileName = inputPath; //inputHistogramFileName += "/"; inputHistogramFileName = baseName; inputHistogramFileName += calibSuffix; inputHistogramFileName += ".root"; //outputHistogramFileName = outputPath; //outputHistogramFileName += "/"; outputHistogramFileName = baseName; if (singlesOnly) outputHistogramFileName += singlesOnlySuffix; outputHistogramFileName += ".root"; cout << " iTask: " << iTask << endl; cout << " Task Name: " << taskName << endl; cout << " List Name: " << listName << endl; cout << " inputHistogramFileName: " << inputHistogramFileName << endl; cout << " outputHistogramFileName: " << outputHistogramFileName << endl; cout << " using weights: " << useWeights << endl; TFile * inputFile = 0; TList * histoList = 0; TH3F * weight_1 = 0; TH3F * weight_2 = 0; if (useWeights) { inputFile = new TFile(inputHistogramFileName); if (!inputFile) { cout << "Requested file:" << inputHistogramFileName << " was not opened. ABORT." << endl; return; } histoList = (TList *) inputFile->Get(listName); if (!histoList) { cout << "Requested list:" << listName << " was not found. ABORT." << endl; return; } if (requestedCharge1 == 1) weight_1 = (TH3 *) histoList->FindObject("correction_p"); else weight_1 = (TH3 *) histoList->FindObject("correction_m"); if (!weight_1) { cout << "Requested histogram 'correction_p/m' was not found. ABORT." << endl; return; } if (!sameFilter) { weight_2 = 0; if (requestedCharge2 == 1) weight_2 = (TH3 *) histoList->FindObject("correction_p"); else weight_2 = (TH3 *) histoList->FindObject("correction_m"); if (!weight_2) { cout << "Requested histogram 'correction_p/m' was not found. ABORT." << endl; return; } } } AliAnalysisTaskDptDptCorrelations* task = new AliAnalysisTaskDptDptCorrelations(taskName); //configure my task task->SetDebugLevel( debugLevel ); task->SetSameFilter( sameFilter ); task->SetSinglesOnly( singlesOnly ); task->SetUseWeights( useWeights ); task->SetRejectPileup( rejectPileup ); task->SetRejectPairConversion(rejectPairConversion); task->SetVertexZMin( zMin ); task->SetVertexZMax( zMax ); task->SetVertexXYMin( -1. ); task->SetVertexXYMax( 1. ); task->SetCentralityMethod( centralityMethod); task->SetCentrality( minCentrality[iCentrality], maxCentrality[iCentrality]); task->SetPtMin1( ptMin ); task->SetPtMax1( ptMax ); task->SetEtaMin1( etaMin ); task->SetEtaMax1( etaMax ); task->SetPtMin2( ptMin ); task->SetPtMax2( ptMax ); task->SetEtaMin2( etaMin ); task->SetEtaMax2( etaMax ); task->SetDcaZMin( dcaZMin ); task->SetDcaZMax( dcaZMax ); task->SetDcaXYMin( dcaXYMin ); task->SetDcaXYMax( dcaXYMax ); task->SetDedxMin( dedxMin ); task->SetDedxMax( dedxMax ); task->SetNClusterMin( nClusterMin ); task->SetTrackFilterBit( trackFilterBit ); task->SetRequestedCharge_1( requestedCharge1); task->SetRequestedCharge_2( requestedCharge2); task->SetWeigth_1( weight_1 ); task->SetWeigth_2( weight_2 ); cout << "Creating task output container" << endl; taskOutputContainer = analysisManager->CreateContainer(listName, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:Histos", AliAnalysisManager::GetCommonFileName())); cout << "Add task to analysis manager and connect it to input and output containers" << endl; analysisManager->AddTask(task); analysisManager->ConnectInput( task, 0, analysisManager->GetCommonInputContainer()); analysisManager->ConnectOutput(task, 0, taskOutputContainer ); cout << "Task added ...." << endl; iTask++; } } return task; } <commit_msg>update from Claude<commit_after>// // Macro designed for use with the AliAnalysisTaskDptDptCorrelations task. // // Author: Claude Pruneau, Wayne State ///////////////////////////////////////////////////////////////////////////////// AliAnalysisTaskDptDptCorrelations *AddTaskDptDptCorrelations(int singlesOnly = 0, int useWeights = 1, int centralityMethod = 4, int chargeSet = 1) { // Set Default Configuration of this analysis // ========================================== int debugLevel = 0; //int singlesOnly = 1; //int useWeights = 0; int rejectPileup = 1; int rejectPairConversion = 1; int sameFilter = 1; //int centralityMethod = 4; int nCentrality = 10; double minCentrality[] = { 0.5, 5., 10., 20., 30., 40., 50., 60., 70., 80. }; double maxCentrality[] = { 5.0, 10., 20., 30., 40., 50., 60., 70., 80., 90. }; double zMin = -10.; double zMax = 10.; double ptMin = 0.2; double ptMax = 2.0; double etaMin = -1.0; double etaMax = 1.0; double dcaZMin = -3.0; double dcaZMax = 3.0; double dcaXYMin = -3.0; double dcaXYMax = 3.0; double dedxMin = 0.0; double dedxMax = 20000.0; int nClusterMin = 70; int trackFilterBit = 128; int requestedCharge1 = 1; //default int requestedCharge2 = -1; //default // Get the pointer to the existing analysis manager via the static access method. // ============================================================================== AliAnalysisManager *analysisManager = AliAnalysisManager::GetAnalysisManager(); if (!analysisManager) { ::Error("AddTaskDptDptCorrelations", "No analysis manager to connect to."); return NULL; } TString part1Name; TString part2Name; TString eventName; TString prefixName = "Corr_"; TString pileupRejecSuffix = "_PileupRejec"; TString pairRejecSuffix = "_PairRejec"; TString calibSuffix = "_calib"; TString singlesOnlySuffix = "_SO"; TString suffix; TString inputPath = "."; TString outputPath = "."; TString baseName; TString listName; TString taskName; TString inputHistogramFileName; TString outputHistogramFileName; // Create the task and add subtask. // =========================================================================== int iTask = 0; // task counter AliAnalysisDataContainer *taskInputContainer; AliAnalysisDataContainer *taskOutputContainer; AliAnalysisTaskDptDptCorrelations* task; for (int iCentrality=0; iCentrality < nCentrality; ++iCentrality) { switch (chargeSet) { case 0: part1Name = "P_"; part2Name = "P_"; requestedCharge1 = 1; requestedCharge2 = 1; sameFilter = 1; break; case 1: part1Name = "P_"; part2Name = "M_"; requestedCharge1 = 1; requestedCharge2 = -1; sameFilter = 0; break; case 2: part1Name = "M_"; part2Name = "P_"; requestedCharge1 = -1; requestedCharge2 = 1; sameFilter = 0; break; case 3: part1Name = "M_"; part2Name = "M_"; requestedCharge1 = -1; requestedCharge2 = -1; sameFilter = 1; break; } //part1Name += int(1000*etaMin); part1Name += "eta"; part1Name += int(1000*etaMax); part1Name += "_"; part1Name += int(1000*ptMin); part1Name += "pt"; part1Name += int(1000*ptMax); part1Name += "_"; //part2Name += int(1000*etaMin); part2Name += "eta"; part2Name += int(1000*etaMax); part2Name += "_"; part2Name += int(1000*ptMin); part2Name += "pt"; part2Name += int(1000*ptMax); part2Name += "_"; eventName = ""; eventName += int(10.*minCentrality[iCentrality] ); eventName += "Vo"; eventName += int(10.*maxCentrality[iCentrality] ); //eventName += "_"; //eventName += int(10*zMin ); //eventName += "Z"; //eventName += int(10*zMax ); //if (rejectPileup) eventName += pileupRejecSuffix; //if (rejectPairConversion) eventName += pairRejecSuffix; baseName = prefixName; baseName += part1Name; baseName += part2Name; baseName += eventName; listName = baseName; taskName = baseName; //inputHistogramFileName = inputPath; //inputHistogramFileName += "/"; //inputHistogramFileName = baseName; //inputHistogramFileName += calibSuffix; //inputHistogramFileName += ".root"; //outputHistogramFileName = outputPath; //outputHistogramFileName += "/"; //inputHistogramFileName = "/home/pruneau//wrk/Alice/PbPb/2730GeV/DptDpt/Calib/PbPb273Calibration.root"; inputHistogramFileName = "alien:///alice/cern.ch/user/c/cpruneau/PbPb273Calibration.root"; //TFile::Open(); outputHistogramFileName = baseName; if (singlesOnly) outputHistogramFileName += singlesOnlySuffix; outputHistogramFileName += ".root"; cout << " iTask: " << iTask << endl; cout << " Task Name: " << taskName << endl; cout << " List Name: " << listName << endl; cout << " inputHistogramFileName: " << inputHistogramFileName << endl; cout << " outputHistogramFileName: " << outputHistogramFileName << endl; cout << " using weights: " << useWeights << endl; TFile * inputFile = 0; TList * histoList = 0; TH3F * weight_1 = 0; TH3F * weight_2 = 0; if (useWeights) { TGrid::Connect("alien:"); inputFile = TFile::Open(inputHistogramFileName,"OLD"); if (!inputFile) { cout << "Requested file:" << inputHistogramFileName << " was not opened. ABORT." << endl; return; } TString nameHistoBase = "correction_"; TString nameHisto; nameHistoBase += eventName; if (requestedCharge1 == 1) { nameHisto = nameHistoBase + "_p"; cout << "Input Histogram named: " << nameHisto << endl; weight_1 = (TH3F *) inputFile->Get(nameHisto); } else { nameHisto = nameHistoBase + "_m"; cout << "Input Histogram named: " << nameHisto << endl; weight_1 = (TH3F *) inputFile->Get(nameHisto); } if (!weight_1) { cout << "Requested histogram 'correction_p/m' was not found. ABORT." << endl; return 0; } if (!sameFilter) { weight_2 = 0; if (requestedCharge2 == 1) { nameHisto = nameHistoBase + "_p"; cout << "Input Histogram named: " << nameHisto << endl; weight_2 = (TH3F *) inputFile->Get(nameHisto); } else { nameHisto = nameHistoBase + "_m"; cout << "Input Histogram named: " << nameHisto << endl; weight_2 = (TH3F *) inputFile->Get(nameHisto); } if (!weight_2) { cout << "Requested histogram 'correction_p/m' was not found. ABORT." << endl; return 0; } } } task = new AliAnalysisTaskDptDptCorrelations(taskName); //configure my task task->SetDebugLevel( debugLevel ); task->SetSameFilter( sameFilter ); task->SetSinglesOnly( singlesOnly ); task->SetUseWeights( useWeights ); task->SetRejectPileup( rejectPileup ); task->SetRejectPairConversion(rejectPairConversion); task->SetVertexZMin( zMin ); task->SetVertexZMax( zMax ); task->SetVertexXYMin( -1. ); task->SetVertexXYMax( 1. ); task->SetCentralityMethod( centralityMethod); task->SetCentrality( minCentrality[iCentrality], maxCentrality[iCentrality]); task->SetPtMin1( ptMin ); task->SetPtMax1( ptMax ); task->SetEtaMin1( etaMin ); task->SetEtaMax1( etaMax ); task->SetPtMin2( ptMin ); task->SetPtMax2( ptMax ); task->SetEtaMin2( etaMin ); task->SetEtaMax2( etaMax ); task->SetDcaZMin( dcaZMin ); task->SetDcaZMax( dcaZMax ); task->SetDcaXYMin( dcaXYMin ); task->SetDcaXYMax( dcaXYMax ); task->SetDedxMin( dedxMin ); task->SetDedxMax( dedxMax ); task->SetNClusterMin( nClusterMin ); task->SetTrackFilterBit( trackFilterBit ); task->SetRequestedCharge_1( requestedCharge1); task->SetRequestedCharge_2( requestedCharge2); task->SetWeigth_1( weight_1 ); task->SetWeigth_2( weight_2 ); cout << "Creating task output container" << endl; taskOutputContainer = analysisManager->CreateContainer(listName, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:Histos", AliAnalysisManager::GetCommonFileName())); cout << "Add task to analysis manager and connect it to input and output containers" << endl; analysisManager->AddTask(task); analysisManager->ConnectInput( task, 0, analysisManager->GetCommonInputContainer()); analysisManager->ConnectOutput(task, 0, taskOutputContainer ); cout << "Task added ...." << endl; iTask++; } return task; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <stdlib.h> //exit #include <stdio.h> //perror #include <errno.h> //perror #include <sys/types.h> //wait #include <sys/wait.h> //wait #include <unistd.h> //execvp, fork, gethost, getlogin #include <string.h> //strtok #include <vector> #include <fcntl.h> #include <sys/stat.h> using namespace std; //checks for comments and if stuff is after comments, it deletes it void checkcomm(string &str){ size_t comment = str.find("#"); //cout << "THis is pos of comment: " << comment << endl; str[comment] = '\0'; if(comment != string :: npos) str.erase(str.begin()+comment, str.end()); //cout << "This is str: " << str << endl; } void IOredir(char **argv); void tokenize(char *cmnd, char **argv); void forkPipes(char **argv, char **afterPipe); void simpleFork(char **argv); void getPipes(char** argv); int main(/*int argc, char *argv[]*/){ //couldn't get argv to work //get username and hostname char login[100]; if(getlogin_r(login, sizeof(login)-1)){ perror("Error with getlogin_r"); } char host[100]; if(-1 == gethostname(host,sizeof(host)-1)){ perror("Error with gethostname."); } for(int pos=0; pos<30; pos++){ if(host[pos] == '.'){ host[pos] = '\0'; } } //execute while(1){ string input; char buf[1000]; int sdi = dup(0), sdo = dup(1); //char **argv; //argv = new char*[1024]; cout << login << "@" << host << "$ "; //get the input from user getline(cin, input); //check if user pushes enter if(input == "") continue; //check for comments checkcomm(input); strcpy(buf, input.c_str()); //check if user inputs exit if( input.find("exit") != string::npos ) exit(1); //tokenize(buf, argv); //tokenize the commandline //char *tok;// *save; char delim[]= " \t\n"; int size=input.size()+1; //vector<int> order; char **argv=new char*[size]; int pos=0; argv[pos]=strtok(buf, delim); while(argv[pos] != NULL) { pos++; argv[pos] = strtok(NULL,delim); } //argv[pos]=NULL; //for(unsigned i=0; argv[i] != NULL ; i++) // cout << argv[i] << ' '; //simpleFork(argv); IOredir(argv); getPipes(argv); if(dup2(sdi, 0) == -1) perror("There was an error with dup2"); if(dup2(sdo,1) == -1) perror("There was an error with dup2"); delete[] argv; } return 0; } void simpleFork(char **argv, bool BG){ int status = 0; int i = fork(); if(i == -1){ //error check fork perror("There was an error with fork()"); exit(1); } else if(i == 0) { //error check execvp if (-1==execvp(argv[0], argv)) { perror("execvp didn't work correctly"); exit(1); } } //in parent if(! BG){ //error check parent if(wait(&status)==-1){ perror("Error in wait"); exit(1); } } } void getPipes(char** argv){ bool pipeFound = false; //save spots for the beginning arguments and ending arguments char **args = argv; char **nextA = argv; //go through argv and check if pipes are found //if they are found, it goes into function forkpipes for(int i=0; argv[i] != '\0'; i++){ if(strcmp(argv[i], "|") == 0){ pipeFound=true; argv[i] = '\0'; char** beforeA = args; nextA = args + i + 1; forkPipes(beforeA, nextA); break; } } //if pipe isn't found, it goes into the simple fork if(!pipeFound){ bool BG = false; for(int i=0; nextA[i] != '\0'; i++){ if(strcmp(nextA[i], "&") == 0) BG=true; } simpleFork(nextA, BG); } } void forkPipes(char **argv, char **afterPipe){ int fd[2]; int pid; //pipe new file descriptors if(pipe(fd) == -1){ perror("Error with pipe."); exit(EXIT_FAILURE); } pid = fork(); if(pid == -1){ perror("There was an error with piping fork."); exit(1); } //in child else if(pid ==0){ //close stdin if(close(fd[0]) == -1){ perror("Error with close in piping."); exit(1); } //save stdout if(dup2(fd[1],1)==-1){ perror("Error with dup2 in piping."); } //execute if(execvp(argv[0], argv) == -1){ perror("There was an error with execvp piping"); exit(1); } else{ exit(0); } } //in parent //save stdin int savestdin=dup(0); if((savestdin == -1)) perror("There was an error with dup."); //close std out if(close(fd[1]) == -1){ perror("Error with close in piping."); exit(1); } //make stdin with dup2 if(dup2(fd[0],0) == -1){ perror("Error with dup2 in piping."); } //make sure the parent waits if(wait(0) == -1) perror("There was an error in wait."); //while(waitpid(-1, &status, 0) >= 0); //check for pipes after we execute getPipes(afterPipe); if(dup2(savestdin,0)==-1){ perror("Error with dup2 in piping."); } } void IOredir(char *argv[]){ for(int i=0; argv[i] != '\0'; i++){ if(strcmp(argv[i], "<") == 0){ int file = open(argv[i+1], O_RDONLY); if(file == -1) perror("There was an error with open"); if(dup2(file, 0)==-1) perror("There was an error in dup2"); argv[i] = NULL; break; } else if(strcmp(argv[i], ">") == 0){ int file = open(argv[i + 1], O_CREAT|O_TRUNC|O_WRONLY, 0666); if(file ==-1) perror("There was an error with open"); if(dup2(file, 1)== -1) perror("There was an error with dup2"); argv[i] = NULL; break; } else if(!strcmp(argv[i], ">>")){ argv[i] = NULL; int file = open(argv[i+1], O_CREAT|O_WRONLY|O_APPEND, 0666); if(file == -1) perror("There was an error with open"); if(dup2(file,1) == -1) perror("There was an error with dup2"); break; } } } <commit_msg>fixed spacing for |'<commit_after>#include <iostream> #include <string> #include <stdlib.h> //exit #include <stdio.h> //perror #include <errno.h> //perror #include <sys/types.h> //wait #include <sys/wait.h> //wait #include <unistd.h> //execvp, fork, gethost, getlogin #include <string.h> //strtok #include <vector> #include <fcntl.h> #include <sys/stat.h> using namespace std; //checks for comments and if stuff is after comments, it deletes it void checkcomm(string &str){ size_t comment = str.find("#"); //cout << "THis is pos of comment: " << comment << endl; str[comment] = '\0'; if(comment != string :: npos) str.erase(str.begin()+comment, str.end()); //cout << "This is str: " << str << endl; } void fixSpaces(string &input); void IOredir(char **argv); void forkPipes(char **argv, char **afterPipe); void simpleFork(char **argv); void getPipes(char** argv); int main(){ //get username and hostname char login[100]; if(getlogin_r(login, sizeof(login)-1)){ perror("Error with getlogin_r"); } char host[100]; if(-1 == gethostname(host,sizeof(host)-1)){ perror("Error with gethostname."); } for(int pos=0; pos<30; pos++){ if(host[pos] == '.'){ host[pos] = '\0'; } } //execute while(1){ string input; char buf[1000]; int sdi = dup(0), sdo = dup(1); cout << login << "@" << host << "$ "; //get the input from user getline(cin, input); //check if user pushes enter if(input == "") continue; //checks the spacing fixSpaces(input); //check for comments checkcomm(input); strcpy(buf, input.c_str()); //check if user inputs exit if( input.find("exit") != string::npos ) exit(1); //tokenize the commandline char delim[]= " \t\n"; int size=input.size()+1; char **argv=new char*[size]; int pos=0; argv[pos]=strtok(buf, delim); while(argv[pos] != NULL) { pos++; argv[pos] = strtok(NULL,delim); } //argv[pos]=NULL; //for(unsigned i=0; argv[i] != NULL ; i++) // cout << argv[i] << ' '; IOredir(argv); getPipes(argv); if(dup2(sdi, 0) == -1) perror("There was an error with dup2"); if(dup2(sdo,1) == -1) perror("There was an error with dup2"); delete[] argv; } return 0; } void simpleFork(char **argv, bool BG){ int status = 0; int i = fork(); if(i == -1){ //error check fork perror("There was an error with fork()"); exit(1); } else if(i == 0) { //error check execvp if (-1==execvp(argv[0], argv)) { perror("execvp didn't work correctly"); exit(1); } } //in parent if(! BG){ //error check parent if(wait(&status)==-1){ perror("Error in wait"); exit(1); } } } void getPipes(char** argv){ bool pipeFound = false; //save spots for the beginning arguments and ending arguments char **args = argv; char **nextA = argv; //go through argv and check if pipes are found //if they are found, it goes into function forkpipes for(int i=0; argv[i] != '\0'; i++){ if(strcmp(argv[i], "|") == 0){ pipeFound=true; argv[i] = '\0'; char** beforeA = args; nextA = args + i + 1; forkPipes(beforeA, nextA); break; } } //if pipe isn't found, it goes into the simple fork if(!pipeFound){ bool BG = false; for(int i=0; nextA[i] != '\0'; i++){ if(strcmp(nextA[i], "&") == 0) BG=true; } simpleFork(nextA, BG); } } //execution if the command line has pipes void forkPipes(char **argv, char **afterPipe){ int fd[2]; int pid; //pipe new file descriptors if(pipe(fd) == -1){ perror("Error with pipe."); exit(EXIT_FAILURE); } pid = fork(); if(pid == -1){ perror("There was an error with piping fork."); exit(1); } //in child else if(pid ==0){ //close stdin if(close(fd[0]) == -1){ perror("Error with close in piping."); exit(1); } //save stdout if(dup2(fd[1],1)==-1){ perror("Error with dup2 in piping."); } //execute if(execvp(argv[0], argv) == -1){ perror("There was an error with execvp piping"); exit(1); } else{ exit(0); } } //in parent //save stdin int save=dup(0); if((save== -1)) perror("There was an error with dup."); //close std out if(close(fd[1]) == -1){ perror("Error with close in piping."); exit(1); } //make stdin with dup2 if(dup2(fd[0],0) == -1){ perror("Error with dup2 in piping."); } //make sure the parent waits if(wait(0) == -1) perror("There was an error in wait."); //while(waitpid(-1, &status, 0) >= 0); //check for pipes after we execute getPipes(afterPipe); if(dup2(save,0)==-1){ perror("Error with dup2 in piping."); } } //deals with the IO redirection void IOredir(char *argv[]){ //check if there are any I/O redirection symbols for(int i=0; argv[i] != '\0'; i++){ //check for "<" output redir if(strcmp(argv[i], "<") == 0){ //open the file for read only int file = open(argv[i+1], O_RDONLY); if(file == -1) perror("There was an error with open"); if(dup2(file, 0)==-1) perror("There was an error in dup2"); argv[i] = NULL; break; } //check for ">" input redir else if(strcmp(argv[i], ">") == 0){ //open the file, create or truncate and make write only int file = open(argv[i + 1], O_CREAT|O_TRUNC|O_WRONLY, 0666); if(file ==-1) perror("There was an error with open"); if(dup2(file, 1)== -1) perror("There was an error with dup2"); argv[i] = NULL; break; } //check for appending ">>" input redir else if(!strcmp(argv[i], ">>")){ argv[i] = NULL; //open the file, create or append to old file and make write only int file = open(argv[i+1], O_CREAT|O_WRONLY|O_APPEND, 0666); if(file == -1) perror("There was an error with open"); if(dup2(file,1) == -1) perror("There was an error with dup2"); break; } } } void fixSpaces(string &input){ for(unsigned int i = 0; i < input.size(); i++){ //check if | is right next to word //if | is in the middle of a word if(input[i] == '|' && input[i+1] != ' ' && input[i-1] != ' ' && i !=0){ input.insert(i+1, " "); input.insert(i, " "); } //if | is right before a word else if(input[i] == '|' && input[i+1] != ' ') input.insert(i+1, " "); //if | is right after word else if(input[i] == '|' && input[i-1] != ' ' && i!=0) input.insert(i, " "); } } <|endoftext|>
<commit_before>// $Id$ // // Jet embedding from PYTHIA task. // // Author: S.Aiola, C.Loizides #include "AliJetEmbeddingFromPYTHIATask.h" #include <TFile.h> #include <TMath.h> #include <TString.h> #include <TRandom.h> #include <TParameter.h> #include <TH1I.h> #include <TGrid.h> #include <THashTable.h> #include <TSystem.h> #include "AliVEvent.h" #include "AliLog.h" ClassImp(AliJetEmbeddingFromPYTHIATask) //________________________________________________________________________ AliJetEmbeddingFromPYTHIATask::AliJetEmbeddingFromPYTHIATask() : AliJetEmbeddingFromAODTask("AliJetEmbeddingFromPYTHIATask"), fPYTHIAPath(), fPtHardBinScaling(), fLHC11hAnchorRun(kTRUE), fAnchorRun(-1), fFileTable(0), fUseAsVetoTable(kTRUE), fMinEntriesPerPtHardBin(1), fCurrentPtHardBin(-1), fPtHardBinParam(0), fPtHardBinCount(0), fHistPtHardBins(0) { // Default constructor. SetSuffix("PYTHIAEmbedding"); fTotalFiles = 140; fRandomAccess = kTRUE; SetAODMC(kTRUE); } //________________________________________________________________________ AliJetEmbeddingFromPYTHIATask::AliJetEmbeddingFromPYTHIATask(const char *name, Bool_t drawqa) : AliJetEmbeddingFromAODTask(name, drawqa), fPYTHIAPath("alien:///alice/sim/2012/LHC12a15e_fix/%d/%d/AOD149/%04d/AliAOD.root"), fPtHardBinScaling(), fLHC11hAnchorRun(kTRUE), fAnchorRun(-1), fFileTable(0), fUseAsVetoTable(kTRUE), fMinEntriesPerPtHardBin(1), fCurrentPtHardBin(-1), fPtHardBinParam(0), fPtHardBinCount(0), fHistPtHardBins(0) { // Standard constructor. SetSuffix("PYTHIAEmbedding"); fTotalFiles = 140; fRandomAccess = kTRUE; SetAODMC(kTRUE); } //________________________________________________________________________ AliJetEmbeddingFromPYTHIATask::~AliJetEmbeddingFromPYTHIATask() { // Destructor } //________________________________________________________________________ void AliJetEmbeddingFromPYTHIATask::UserCreateOutputObjects() { if (!fQAhistos) return; AliJetModelBaseTask::UserCreateOutputObjects(); fHistPtHardBins = new TH1F("fHistPtHardBins", "fHistPtHardBins", 11, 0, 11); fHistPtHardBins->GetXaxis()->SetTitle("p_{T} hard bin"); fHistPtHardBins->GetYaxis()->SetTitle("total events"); fOutput->Add(fHistPtHardBins); const Int_t ptHardLo[11] = { 0, 5,11,21,36,57, 84,117,152,191,234}; const Int_t ptHardHi[11] = { 5,11,21,36,57,84,117,152,191,234,1000000}; for (Int_t i = 1; i < 12; i++) fHistPtHardBins->GetXaxis()->SetBinLabel(i, Form("%d-%d",ptHardLo[i-1],ptHardHi[i-1])); fHistEmbeddingQA = new TH1F("fHistEmbeddingQA", "fHistEmbeddingQA", 2, 0, 2); fHistEmbeddingQA->GetXaxis()->SetTitle("Event state"); fHistEmbeddingQA->GetYaxis()->SetTitle("counts"); fHistEmbeddingQA->GetXaxis()->SetBinLabel(1, "OK"); fHistEmbeddingQA->GetXaxis()->SetBinLabel(2, "Not embedded"); fOutput->Add(fHistEmbeddingQA); fHistRejectedEvents = new TH1F("fHistRejectedEvents", "fHistRejectedEvents", 500, -0.5, 499.5); fHistRejectedEvents->GetXaxis()->SetTitle("# of rejected events"); fHistRejectedEvents->GetYaxis()->SetTitle("counts"); fOutput->Add(fHistRejectedEvents); PostData(1, fOutput); } //________________________________________________________________________ Bool_t AliJetEmbeddingFromPYTHIATask::ExecOnce() { if (fPtHardBinScaling.GetSize() > 0) { Double_t sum = 0; for (Int_t i = 0; i < fPtHardBinScaling.GetSize(); i++) sum += fPtHardBinScaling[i]; if (sum == 0) { AliWarning("No hard pt bin scaling!"); sum = fPtHardBinScaling.GetSize(); } for (Int_t i = 0; i < fPtHardBinScaling.GetSize(); i++) fPtHardBinScaling[i] /= sum; } fPtHardBinParam = static_cast<TParameter<int>*>(InputEvent()->FindListObject("PYTHIAPtHardBin")); if (!fPtHardBinParam) { fPtHardBinParam = new TParameter<int>("PYTHIAPtHardBin", 0); AliDebug(3,"Adding pt hard bin param object to the event list..."); InputEvent()->AddObject(fPtHardBinParam); } return AliJetEmbeddingFromAODTask::ExecOnce(); } //________________________________________________________________________ Bool_t AliJetEmbeddingFromPYTHIATask::GetNextEntry() { if (fPtHardBinCount >= fMinEntriesPerPtHardBin || fCurrentPtHardBin < 0) { if (fHistPtHardBins && fPtHardBinCount > 0) fHistPtHardBins->SetBinContent(fCurrentPtHardBin+1, fHistPtHardBins->GetBinContent(fCurrentPtHardBin+1)+fPtHardBinCount); fPtHardBinCount = 0; Int_t newPtHard = GetRandomPtHardBin(); if (newPtHard != fCurrentPtHardBin) { new (fPtHardBinParam) TParameter<int>("PYTHIAPtHardBin", newPtHard); fCurrentPtHardBin = newPtHard; if (!OpenNextFile()) return kFALSE; } } return AliJetEmbeddingFromAODTask::GetNextEntry(); } //________________________________________________________________________ Int_t AliJetEmbeddingFromPYTHIATask::GetRandomPtHardBin() { static Int_t order[20]={-1}; if (order[0] == -1) TMath::Sort(fPtHardBinScaling.GetSize(), fPtHardBinScaling.GetArray(), order); Double_t rnd = gRandom->Rndm(); Double_t sum = 0; Int_t ptHard = -1; for (Int_t i = 0; i < fPtHardBinScaling.GetSize(); i++) { sum += fPtHardBinScaling[order[i]]; if (sum >= rnd) { ptHard = order[i]; break; } } return ptHard; } //________________________________________________________________________ Bool_t AliJetEmbeddingFromPYTHIATask::UserNotify() { if (!fLHC11hAnchorRun) return kTRUE; Int_t runNumber = InputEvent()->GetRunNumber(); Int_t semiGoodRunList[32] = {169975, 169981, 170038, 170040, 170083, 170084, 170085, 170088, 170089, 170091, 170152, 170155, 170159, 170163, 170193, 170195, 170203, 170204, 170228, 170230, 170268, 170269, 170270, 170306, 170308, 170309, 169238, 169160, 169156, 169148, 169145, 169144}; fAnchorRun = 169838; // Assume it is a good run for (Int_t i = 0; i < 32; i++) { if (runNumber == semiGoodRunList[i]) { // If it is semi good, change the anchor run fAnchorRun = 170040; break; } } return kTRUE; } //________________________________________________________________________ TFile* AliJetEmbeddingFromPYTHIATask::GetNextFile() { fCurrentAODFileID = TMath::Nint(gRandom->Rndm()*(fTotalFiles-1))+1; TString fileName; if (fAnchorRun>0) fileName = Form(fPYTHIAPath.Data(), fAnchorRun, fCurrentPtHardBin, fCurrentAODFileID); else fileName = Form(fPYTHIAPath.Data(), fCurrentPtHardBin, fCurrentAODFileID); if (fFileTable && fFileTable->GetEntries() > 0) { TObject* obj = fFileTable->FindObject(fileName); if (obj != 0 && fUseAsVetoTable) { AliWarning(Form("File %s found in the vetoed file table. Skipping...", fileName.Data())); return 0; } if (obj == 0 && !fUseAsVetoTable) { AliWarning(Form("File %s not found in the allowed file table. Skipping...", fileName.Data())); return 0; } } if (fileName.BeginsWith("alien://") && !gGrid) { AliInfo("Trying to connect to AliEn ..."); TGrid::Connect("alien://"); } TString baseFileName(fileName); if (baseFileName.Contains(".zip#")) { Ssiz_t pos = baseFileName.Last('#'); baseFileName.Remove(pos); } if (gSystem->AccessPathName(baseFileName)) { AliError(Form("File %s does not exist!", baseFileName.Data())); return 0; } AliDebug(3,Form("Trying to open file %s...", fileName.Data())); TFile *file = TFile::Open(fileName); if (!file || file->IsZombie()) { AliError(Form("Unable to open file: %s!", fileName.Data())); return 0; } return file; } <commit_msg>Increase pt hard bin entry counter<commit_after>// $Id$ // // Jet embedding from PYTHIA task. // // Author: S.Aiola, C.Loizides #include "AliJetEmbeddingFromPYTHIATask.h" #include <TFile.h> #include <TMath.h> #include <TString.h> #include <TRandom.h> #include <TParameter.h> #include <TH1I.h> #include <TGrid.h> #include <THashTable.h> #include <TSystem.h> #include "AliVEvent.h" #include "AliLog.h" ClassImp(AliJetEmbeddingFromPYTHIATask) //________________________________________________________________________ AliJetEmbeddingFromPYTHIATask::AliJetEmbeddingFromPYTHIATask() : AliJetEmbeddingFromAODTask("AliJetEmbeddingFromPYTHIATask"), fPYTHIAPath(), fPtHardBinScaling(), fLHC11hAnchorRun(kTRUE), fAnchorRun(-1), fFileTable(0), fUseAsVetoTable(kTRUE), fMinEntriesPerPtHardBin(1), fCurrentPtHardBin(-1), fPtHardBinParam(0), fPtHardBinCount(0), fHistPtHardBins(0) { // Default constructor. SetSuffix("PYTHIAEmbedding"); fTotalFiles = 140; fRandomAccess = kTRUE; SetAODMC(kTRUE); } //________________________________________________________________________ AliJetEmbeddingFromPYTHIATask::AliJetEmbeddingFromPYTHIATask(const char *name, Bool_t drawqa) : AliJetEmbeddingFromAODTask(name, drawqa), fPYTHIAPath("alien:///alice/sim/2012/LHC12a15e_fix/%d/%d/AOD149/%04d/AliAOD.root"), fPtHardBinScaling(), fLHC11hAnchorRun(kTRUE), fAnchorRun(-1), fFileTable(0), fUseAsVetoTable(kTRUE), fMinEntriesPerPtHardBin(1), fCurrentPtHardBin(-1), fPtHardBinParam(0), fPtHardBinCount(0), fHistPtHardBins(0) { // Standard constructor. SetSuffix("PYTHIAEmbedding"); fTotalFiles = 140; fRandomAccess = kTRUE; SetAODMC(kTRUE); } //________________________________________________________________________ AliJetEmbeddingFromPYTHIATask::~AliJetEmbeddingFromPYTHIATask() { // Destructor } //________________________________________________________________________ void AliJetEmbeddingFromPYTHIATask::UserCreateOutputObjects() { if (!fQAhistos) return; AliJetModelBaseTask::UserCreateOutputObjects(); fHistPtHardBins = new TH1F("fHistPtHardBins", "fHistPtHardBins", 11, 0, 11); fHistPtHardBins->GetXaxis()->SetTitle("p_{T} hard bin"); fHistPtHardBins->GetYaxis()->SetTitle("total events"); fOutput->Add(fHistPtHardBins); const Int_t ptHardLo[11] = { 0, 5,11,21,36,57, 84,117,152,191,234}; const Int_t ptHardHi[11] = { 5,11,21,36,57,84,117,152,191,234,1000000}; for (Int_t i = 1; i < 12; i++) fHistPtHardBins->GetXaxis()->SetBinLabel(i, Form("%d-%d",ptHardLo[i-1],ptHardHi[i-1])); fHistEmbeddingQA = new TH1F("fHistEmbeddingQA", "fHistEmbeddingQA", 2, 0, 2); fHistEmbeddingQA->GetXaxis()->SetTitle("Event state"); fHistEmbeddingQA->GetYaxis()->SetTitle("counts"); fHistEmbeddingQA->GetXaxis()->SetBinLabel(1, "OK"); fHistEmbeddingQA->GetXaxis()->SetBinLabel(2, "Not embedded"); fOutput->Add(fHistEmbeddingQA); fHistRejectedEvents = new TH1F("fHistRejectedEvents", "fHistRejectedEvents", 500, -0.5, 499.5); fHistRejectedEvents->GetXaxis()->SetTitle("# of rejected events"); fHistRejectedEvents->GetYaxis()->SetTitle("counts"); fOutput->Add(fHistRejectedEvents); PostData(1, fOutput); } //________________________________________________________________________ Bool_t AliJetEmbeddingFromPYTHIATask::ExecOnce() { if (fPtHardBinScaling.GetSize() > 0) { Double_t sum = 0; for (Int_t i = 0; i < fPtHardBinScaling.GetSize(); i++) sum += fPtHardBinScaling[i]; if (sum == 0) { AliWarning("No hard pt bin scaling!"); sum = fPtHardBinScaling.GetSize(); } for (Int_t i = 0; i < fPtHardBinScaling.GetSize(); i++) fPtHardBinScaling[i] /= sum; } fPtHardBinParam = static_cast<TParameter<int>*>(InputEvent()->FindListObject("PYTHIAPtHardBin")); if (!fPtHardBinParam) { fPtHardBinParam = new TParameter<int>("PYTHIAPtHardBin", 0); AliDebug(3,"Adding pt hard bin param object to the event list..."); InputEvent()->AddObject(fPtHardBinParam); } return AliJetEmbeddingFromAODTask::ExecOnce(); } //________________________________________________________________________ Bool_t AliJetEmbeddingFromPYTHIATask::GetNextEntry() { if (fPtHardBinCount >= fMinEntriesPerPtHardBin || fCurrentPtHardBin < 0) { fPtHardBinCount = 0; Int_t newPtHard = GetRandomPtHardBin(); if (newPtHard != fCurrentPtHardBin) { new (fPtHardBinParam) TParameter<int>("PYTHIAPtHardBin", newPtHard); fCurrentPtHardBin = newPtHard; if (!OpenNextFile()) return kFALSE; } } fPtHardBinCount++; fHistPtHardBins->SetBinContent(fCurrentPtHardBin+1, fHistPtHardBins->GetBinContent(fCurrentPtHardBin+1)+1); return AliJetEmbeddingFromAODTask::GetNextEntry(); } //________________________________________________________________________ Int_t AliJetEmbeddingFromPYTHIATask::GetRandomPtHardBin() { static Int_t order[20]={-1}; if (order[0] == -1) TMath::Sort(fPtHardBinScaling.GetSize(), fPtHardBinScaling.GetArray(), order); Double_t rnd = gRandom->Rndm(); Double_t sum = 0; Int_t ptHard = -1; for (Int_t i = 0; i < fPtHardBinScaling.GetSize(); i++) { sum += fPtHardBinScaling[order[i]]; if (sum >= rnd) { ptHard = order[i]; break; } } return ptHard; } //________________________________________________________________________ Bool_t AliJetEmbeddingFromPYTHIATask::UserNotify() { if (!fLHC11hAnchorRun) return kTRUE; Int_t runNumber = InputEvent()->GetRunNumber(); Int_t semiGoodRunList[32] = {169975, 169981, 170038, 170040, 170083, 170084, 170085, 170088, 170089, 170091, 170152, 170155, 170159, 170163, 170193, 170195, 170203, 170204, 170228, 170230, 170268, 170269, 170270, 170306, 170308, 170309, 169238, 169160, 169156, 169148, 169145, 169144}; fAnchorRun = 169838; // Assume it is a good run for (Int_t i = 0; i < 32; i++) { if (runNumber == semiGoodRunList[i]) { // If it is semi good, change the anchor run fAnchorRun = 170040; break; } } return kTRUE; } //________________________________________________________________________ TFile* AliJetEmbeddingFromPYTHIATask::GetNextFile() { fCurrentAODFileID = TMath::Nint(gRandom->Rndm()*(fTotalFiles-1))+1; TString fileName; if (fAnchorRun>0) fileName = Form(fPYTHIAPath.Data(), fAnchorRun, fCurrentPtHardBin, fCurrentAODFileID); else fileName = Form(fPYTHIAPath.Data(), fCurrentPtHardBin, fCurrentAODFileID); if (fFileTable && fFileTable->GetEntries() > 0) { TObject* obj = fFileTable->FindObject(fileName); if (obj != 0 && fUseAsVetoTable) { AliWarning(Form("File %s found in the vetoed file table. Skipping...", fileName.Data())); return 0; } if (obj == 0 && !fUseAsVetoTable) { AliWarning(Form("File %s not found in the allowed file table. Skipping...", fileName.Data())); return 0; } } if (fileName.BeginsWith("alien://") && !gGrid) { AliInfo("Trying to connect to AliEn ..."); TGrid::Connect("alien://"); } TString baseFileName(fileName); if (baseFileName.Contains(".zip#")) { Ssiz_t pos = baseFileName.Last('#'); baseFileName.Remove(pos); } if (gSystem->AccessPathName(baseFileName)) { AliError(Form("File %s does not exist!", baseFileName.Data())); return 0; } AliDebug(3,Form("Trying to open file %s...", fileName.Data())); TFile *file = TFile::Open(fileName); if (!file || file->IsZombie()) { AliError(Form("Unable to open file: %s!", fileName.Data())); return 0; } return file; } <|endoftext|>
<commit_before>#include <common/log.h> #include <common/opt.h> #include <gdb/gdb.h> #include <gui/gui.h> #include <user_cmd/cmd.h> #include <stdlib.h> #include <signal.h> #include <pthread.h> #ifdef GUI_CURSES #include <gui/curses/cursesui.h> #elif GUI_VIM #include <gui/vim/vimui.h> #endif /* static prototypes */ void cleanup(int signum); int cleanup(); int main(int argc, char** argv){ char* line; /* initialise */ thread_name[pthread_self()] = "main"; if(opt_parse(argc, argv) != 0) return 1; // signals signal(SIGTERM, cleanup); signal(SIGINT, cleanup); // user interface #ifdef GUI_CURSES ui = new cursesui(); #elif GUI_VIM ui = new vimui(); #else #error "invalid gui defined" #endif if(ui->init() != 0) return 1; // logging if(log::init(LOG_FILE, LOG_LEVEL) != 0) return 1; // gdb DEBUG("initialise gdbctrl\n"); gdb = new gdbif; DEBUG("initialising gdb interface\n"); if(gdb->init() != 0) return 2; gdb->on_stop(cmd_var_print); gdb->on_stop(cmd_callstack_update); gdb->on_stop(cmd_register_print); gdb->on_stop(cmd_memory_update); gdb->on_exit(cleanup); /* main loop */ while(1){ line = ui->readline(); if(line == 0){ DEBUG("detect ui shutdown\n"); goto end; } cmd_exec(line); } end: // call cleanup() through signal to prevent nested signals // from other threads like closing ui and gdb cleanup(); } /* static functions */ void cleanup(int signum){ cleanup(); } int cleanup(){ static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; DEBUG("recv cleanup request\n"); /* ensure cleanup is only executed once */ if(pthread_mutex_trylock(&m) != 0) return 0; /* destroy gdb */ DEBUG("close gdb interface\n"); delete gdb; gdb = 0; /* close log */ DEBUG("close log\n"); log::cleanup(); /* close gui */ if(ui) ui->destroy(); delete ui; ui = 0; pthread_mutex_unlock(&m); exit(0); } <commit_msg>[main: error message]<commit_after>#include <common/log.h> #include <common/opt.h> #include <gdb/gdb.h> #include <gui/gui.h> #include <user_cmd/cmd.h> #include <stdlib.h> #include <signal.h> #include <pthread.h> #ifdef GUI_CURSES #include <gui/curses/cursesui.h> #elif GUI_VIM #include <gui/vim/vimui.h> #endif /* static prototypes */ void cleanup(int signum); int cleanup(); int main(int argc, char** argv){ char* line; /* initialise */ thread_name[pthread_self()] = "main"; if(opt_parse(argc, argv) != 0) return 1; // signals signal(SIGTERM, cleanup); signal(SIGINT, cleanup); // user interface #ifdef GUI_CURSES ui = new cursesui(); #elif GUI_VIM ui = new vimui(); #else #error "invalid gui defined" #endif if(ui->init() != 0) return 1; // logging if(log::init(LOG_FILE, LOG_LEVEL) != 0) return 1; // gdb DEBUG("initialise gdbctrl\n"); gdb = new gdbif; DEBUG("initialising gdb interface\n"); if(gdb->init() != 0){ ERROR("initialising gdb interface\n"); return 2; } gdb->on_stop(cmd_var_print); gdb->on_stop(cmd_callstack_update); gdb->on_stop(cmd_register_print); gdb->on_stop(cmd_memory_update); gdb->on_exit(cleanup); /* main loop */ while(1){ line = ui->readline(); if(line == 0){ DEBUG("detect ui shutdown\n"); goto end; } cmd_exec(line); } end: // call cleanup() through signal to prevent nested signals // from other threads like closing ui and gdb cleanup(); } /* static functions */ void cleanup(int signum){ cleanup(); } int cleanup(){ static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; DEBUG("recv cleanup request\n"); /* ensure cleanup is only executed once */ if(pthread_mutex_trylock(&m) != 0) return 0; /* destroy gdb */ DEBUG("close gdb interface\n"); delete gdb; gdb = 0; /* close log */ DEBUG("close log\n"); log::cleanup(); /* close gui */ if(ui) ui->destroy(); delete ui; ui = 0; pthread_mutex_unlock(&m); exit(0); } <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2002 Jan-Pascal van Best <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <qfile.h> #include <kapplication.h> #include <kconfig.h> #include <kstandarddirs.h> #include <kurl.h> #include <kdebug.h> #include <kmessagebox.h> #include <klocale.h> #include <kaction.h> #include <kglobal.h> #include "korganizer/korganizer.h" #include "korganizer/calendarview.h" #include <exchangeclient.h> #include <exchangeaccount.h> #include "exchange.h" #include "exchangedialog.h" #include "exchangeconfig.h" using namespace KCal; // Needed for connecting slots class ExchangeFactory : public KOrg::PartFactory { public: KOrg::Part *create(KOrg::MainWindow *parent, const char *name) { return new Exchange(parent,name); } }; extern "C" { void *init_libkorg_exchange() { kdDebug() << "Registering Exchange Plugin...\n"; KGlobal::locale()->insertCatalogue("libkpimexchange"); return (new ExchangeFactory); } } Exchange::Exchange(KOrg::MainWindow *parent, const char *name) : KOrg::Part(parent,name) { kdDebug() << "Creating Exchange Plugin...\n"; mAccount = new KPIM::ExchangeAccount( "Calendar/Exchange Plugin" ); mClient = new KPIM::ExchangeClient( mAccount ); mClient->setWindow( parent ); setXMLFile("plugins/exchangeui.rc"); new KAction(i18n("Download..."), 0, this, SLOT(download()), actionCollection(), "exchange_download"); // new KAction(i18n("Test"), 0, this, SLOT(test()), // actionCollection(), "exchange_test"); KAction *action = new KAction(i18n("Upload Event..."), 0, this, SLOT(upload()), actionCollection(), "exchange_upload"); QObject::connect(mainWindow()->view(),SIGNAL(incidenceSelected(Incidence *)), this, SLOT(slotIncidenceSelected(Incidence *))); action->setEnabled( false ); QObject::connect(this,SIGNAL(enableIncidenceActions(bool)), action,SLOT(setEnabled(bool))); // action,SLOT(setEnabled(bool))); action = new KAction(i18n("Delete Event"), 0, this, SLOT(remove()), actionCollection(), "exchange_delete"); QObject::connect(this,SIGNAL(enableIncidenceActions(bool)), action,SLOT(setEnabled(bool))); action->setEnabled( false ); new KAction(i18n("Configure..."), 0, this, SLOT(configure()), actionCollection(), "exchange_configure"); connect( this, SIGNAL( calendarChanged() ), mainWindow()->view(), SLOT( updateView() ) ); connect( this, SIGNAL( calendarChanged(const QDate &, const QDate &)), mainWindow()->view(), SLOT(updateView(const QDate &, const QDate &)) ); } Exchange::~Exchange() { kdDebug() << "Exchange Plugin destructor" << endl; } QString Exchange::info() { return i18n("This plugin imports and export calendar events from/to a Microsoft Exchange 2000 Server."); } void Exchange::slotIncidenceSelected( Incidence *incidence ) { emit enableIncidenceActions( incidence != 0 ); } void Exchange::download() { ExchangeDialog dialog( mainWindow()->view()->startDate(), mainWindow()->view()->endDate() ); if (dialog.exec() != QDialog::Accepted ) return; QDate start = dialog.m_start->date(); QDate end = dialog.m_end->date(); KCal::Calendar* calendar = mainWindow()->view()->calendar(); int result = mClient->downloadSynchronous(calendar, start, end, true ); if ( result == KPIM::ExchangeClient::ResultOK ) emit calendarChanged(); else showError( result, mClient->detailedErrorString() ); } void Exchange::upload() { kdDebug() << "Called Exchange::upload()" << endl; Event* event = static_cast<Event *> ( mainWindow()->view()->currentSelection() ); if ( ! event ) { KMessageBox::information( 0L, i18n("Please select an appointment"), i18n("Exchange Plugin") ); return; } if ( KMessageBox::warningContinueCancel( 0L, i18n("Exchange Upload is EXPERIMENTAL, you may lose data on this appointment!"), i18n("Exchange Plugin") ) == KMessageBox::Continue ) { kdDebug() << "Trying to add appointment " << event->summary() << endl; int result = mClient->uploadSynchronous( event ); if ( result != KPIM::ExchangeClient::ResultOK ) showError( result, mClient->detailedErrorString() ); } } void Exchange::remove() { kdDebug() << "Called Exchange::remove()" << endl; Event* event = static_cast<Event *> ( mainWindow()->view()->currentSelection() ); if ( ! event ) { KMessageBox::information( 0L, i18n("Please select an appointment"), i18n("Exchange Plugin") ); return; } if ( KMessageBox::warningContinueCancel( 0L, i18n("Exchange Delete is EXPERIMENTAL, if this is a recurring event it will delete all instances!"), i18n("Exchange Plugin") ) == KMessageBox::Continue ) { kdDebug() << "Trying to delete appointment " << event->summary() << endl; int result = mClient->removeSynchronous( event ); if ( result == KPIM::ExchangeClient::ResultOK ) { mainWindow()->view()->calendar()->deleteEvent( event ); emit calendarChanged(); } else showError( result, mClient->detailedErrorString() ); } } void Exchange::configure() { kdDebug() << "Exchange::configure" << endl; ExchangeConfig dialog( mAccount ); if (dialog.exec() == QDialog::Accepted ) mAccount->save( "Calendar/Exchange Plugin" ); } void Exchange::showError( int error, const QString& moreInfo /* = QString::null */ ) { QString errorText; switch( error ) { case KPIM::ExchangeClient::ResultOK: errorText = i18n( "No Error" ); break; case KPIM::ExchangeClient::CommunicationError: errorText = i18n( "The Exchange server could not be reached or returned an error." ); break; case KPIM::ExchangeClient::ServerResponseError: errorText = i18n( "Server response could not be interpreted." ); break; case KPIM::ExchangeClient::IllegalAppointmentError: errorText = i18n( "Appointment data could not be interpreted." ); break; case KPIM::ExchangeClient::NonEventError: errorText = i18n( "This should not happen: trying to upload wrong type of event." ); break; case KPIM::ExchangeClient::EventWriteError: errorText = i18n( "An error occured trying to write an appointment to the server." ); break; case KPIM::ExchangeClient::DeleteUnknownEventError: errorText = i18n( "Trying to delete an event that is not present on the server." ); break; case KPIM::ExchangeClient::UnknownError: default: errorText = i18n( "Unknown Error" ); } if ( error != KPIM::ExchangeClient::ResultOK ) { if ( moreInfo.isNull() ) KMessageBox::error( mainWindow(), errorText, i18n( "Exchange Plugin" ) ); else KMessageBox::detailedError( mainWindow(), errorText, moreInfo, i18n( "Exchange Plugin" ) ); } } void Exchange::test() { kdDebug() << "Entering test()" << endl; mClient->test(); } void Exchange::test2() { kdDebug() << "Entering test2()" << endl; } #include "exchange.moc" <commit_msg>Corrected typographical errors<commit_after>/* This file is part of KOrganizer. Copyright (c) 2002 Jan-Pascal van Best <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <qfile.h> #include <kapplication.h> #include <kconfig.h> #include <kstandarddirs.h> #include <kurl.h> #include <kdebug.h> #include <kmessagebox.h> #include <klocale.h> #include <kaction.h> #include <kglobal.h> #include "korganizer/korganizer.h" #include "korganizer/calendarview.h" #include <exchangeclient.h> #include <exchangeaccount.h> #include "exchange.h" #include "exchangedialog.h" #include "exchangeconfig.h" using namespace KCal; // Needed for connecting slots class ExchangeFactory : public KOrg::PartFactory { public: KOrg::Part *create(KOrg::MainWindow *parent, const char *name) { return new Exchange(parent,name); } }; extern "C" { void *init_libkorg_exchange() { kdDebug() << "Registering Exchange Plugin...\n"; KGlobal::locale()->insertCatalogue("libkpimexchange"); return (new ExchangeFactory); } } Exchange::Exchange(KOrg::MainWindow *parent, const char *name) : KOrg::Part(parent,name) { kdDebug() << "Creating Exchange Plugin...\n"; mAccount = new KPIM::ExchangeAccount( "Calendar/Exchange Plugin" ); mClient = new KPIM::ExchangeClient( mAccount ); mClient->setWindow( parent ); setXMLFile("plugins/exchangeui.rc"); new KAction(i18n("Download..."), 0, this, SLOT(download()), actionCollection(), "exchange_download"); // new KAction(i18n("Test"), 0, this, SLOT(test()), // actionCollection(), "exchange_test"); KAction *action = new KAction(i18n("Upload Event..."), 0, this, SLOT(upload()), actionCollection(), "exchange_upload"); QObject::connect(mainWindow()->view(),SIGNAL(incidenceSelected(Incidence *)), this, SLOT(slotIncidenceSelected(Incidence *))); action->setEnabled( false ); QObject::connect(this,SIGNAL(enableIncidenceActions(bool)), action,SLOT(setEnabled(bool))); // action,SLOT(setEnabled(bool))); action = new KAction(i18n("Delete Event"), 0, this, SLOT(remove()), actionCollection(), "exchange_delete"); QObject::connect(this,SIGNAL(enableIncidenceActions(bool)), action,SLOT(setEnabled(bool))); action->setEnabled( false ); new KAction(i18n("Configure..."), 0, this, SLOT(configure()), actionCollection(), "exchange_configure"); connect( this, SIGNAL( calendarChanged() ), mainWindow()->view(), SLOT( updateView() ) ); connect( this, SIGNAL( calendarChanged(const QDate &, const QDate &)), mainWindow()->view(), SLOT(updateView(const QDate &, const QDate &)) ); } Exchange::~Exchange() { kdDebug() << "Exchange Plugin destructor" << endl; } QString Exchange::info() { return i18n("This plugin imports and export calendar events from/to a Microsoft Exchange 2000 Server."); } void Exchange::slotIncidenceSelected( Incidence *incidence ) { emit enableIncidenceActions( incidence != 0 ); } void Exchange::download() { ExchangeDialog dialog( mainWindow()->view()->startDate(), mainWindow()->view()->endDate() ); if (dialog.exec() != QDialog::Accepted ) return; QDate start = dialog.m_start->date(); QDate end = dialog.m_end->date(); KCal::Calendar* calendar = mainWindow()->view()->calendar(); int result = mClient->downloadSynchronous(calendar, start, end, true ); if ( result == KPIM::ExchangeClient::ResultOK ) emit calendarChanged(); else showError( result, mClient->detailedErrorString() ); } void Exchange::upload() { kdDebug() << "Called Exchange::upload()" << endl; Event* event = static_cast<Event *> ( mainWindow()->view()->currentSelection() ); if ( ! event ) { KMessageBox::information( 0L, i18n("Please select an appointment"), i18n("Exchange Plugin") ); return; } if ( KMessageBox::warningContinueCancel( 0L, i18n("Exchange Upload is EXPERIMENTAL, you may lose data on this appointment!"), i18n("Exchange Plugin") ) == KMessageBox::Continue ) { kdDebug() << "Trying to add appointment " << event->summary() << endl; int result = mClient->uploadSynchronous( event ); if ( result != KPIM::ExchangeClient::ResultOK ) showError( result, mClient->detailedErrorString() ); } } void Exchange::remove() { kdDebug() << "Called Exchange::remove()" << endl; Event* event = static_cast<Event *> ( mainWindow()->view()->currentSelection() ); if ( ! event ) { KMessageBox::information( 0L, i18n("Please select an appointment"), i18n("Exchange Plugin") ); return; } if ( KMessageBox::warningContinueCancel( 0L, i18n("Exchange Delete is EXPERIMENTAL, if this is a recurring event it will delete all instances!"), i18n("Exchange Plugin") ) == KMessageBox::Continue ) { kdDebug() << "Trying to delete appointment " << event->summary() << endl; int result = mClient->removeSynchronous( event ); if ( result == KPIM::ExchangeClient::ResultOK ) { mainWindow()->view()->calendar()->deleteEvent( event ); emit calendarChanged(); } else showError( result, mClient->detailedErrorString() ); } } void Exchange::configure() { kdDebug() << "Exchange::configure" << endl; ExchangeConfig dialog( mAccount ); if (dialog.exec() == QDialog::Accepted ) mAccount->save( "Calendar/Exchange Plugin" ); } void Exchange::showError( int error, const QString& moreInfo /* = QString::null */ ) { QString errorText; switch( error ) { case KPIM::ExchangeClient::ResultOK: errorText = i18n( "No Error" ); break; case KPIM::ExchangeClient::CommunicationError: errorText = i18n( "The Exchange server could not be reached or returned an error." ); break; case KPIM::ExchangeClient::ServerResponseError: errorText = i18n( "Server response could not be interpreted." ); break; case KPIM::ExchangeClient::IllegalAppointmentError: errorText = i18n( "Appointment data could not be interpreted." ); break; case KPIM::ExchangeClient::NonEventError: errorText = i18n( "This should not happen: trying to upload wrong type of event." ); break; case KPIM::ExchangeClient::EventWriteError: errorText = i18n( "An error occurred trying to write an appointment to the server." ); break; case KPIM::ExchangeClient::DeleteUnknownEventError: errorText = i18n( "Trying to delete an event that is not present on the server." ); break; case KPIM::ExchangeClient::UnknownError: default: errorText = i18n( "Unknown Error" ); } if ( error != KPIM::ExchangeClient::ResultOK ) { if ( moreInfo.isNull() ) KMessageBox::error( mainWindow(), errorText, i18n( "Exchange Plugin" ) ); else KMessageBox::detailedError( mainWindow(), errorText, moreInfo, i18n( "Exchange Plugin" ) ); } } void Exchange::test() { kdDebug() << "Entering test()" << endl; mClient->test(); } void Exchange::test2() { kdDebug() << "Entering test2()" << endl; } #include "exchange.moc" <|endoftext|>
<commit_before>#include "../common/certs.hpp" #include "../common/mock_connector.hpp" #include "root_path.hpp" #include <pxp-agent/external_module.hpp> #include <pxp-agent/request_processor.hpp> #include <pxp-agent/configuration.hpp> #include <leatherman/json_container/json_container.hpp> #include <cpp-pcp-client/util/thread.hpp> // this_thread::sleep_for #include <cpp-pcp-client/util/chrono.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/operations.hpp> #include <catch.hpp> namespace PXPAgent { #ifdef TEST_VIRTUAL namespace lth_jc = leatherman::json_container; namespace pcp_util = PCPClient::Util; namespace fs = boost::filesystem; static const std::string REVERSE_VALID_MODULE_NAME { "reverse_valid" }; TEST_CASE("Valid External Module Configuration", "[component]") { AGENT_CONFIGURATION.modules_config_dir = VALID_MODULES_CONFIG; auto c_ptr = std::make_shared<MockConnector>(); RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION }; SECTION("retrieves the configuration from file if valid JSON format") { REQUIRE(r_p.hasModuleConfig(REVERSE_VALID_MODULE_NAME)); } SECTION("does load the module when the configuration is valid") { REQUIRE(r_p.hasModuleConfig(REVERSE_VALID_MODULE_NAME)); REQUIRE(r_p.hasModule(REVERSE_VALID_MODULE_NAME)); } } TEST_CASE("Badly formatted External Module Configuration", "[component]") { AGENT_CONFIGURATION.modules_config_dir = BAD_FORMAT_MODULES_CONFIG; auto c_ptr = std::make_shared<MockConnector>(); RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION }; SECTION("stores a null JSON value as the configuration, if it's in an " "invalid JSON format") { REQUIRE(r_p.getModuleConfig(REVERSE_VALID_MODULE_NAME) == "null"); } SECTION("does not load the module when the configuration is in " "bad JSON format") { REQUIRE(r_p.getModuleConfig(REVERSE_VALID_MODULE_NAME) == "null"); REQUIRE_FALSE(r_p.hasModule(REVERSE_VALID_MODULE_NAME)); } } TEST_CASE("Invalid (by metadata) External Module Configuration", "[component]") { SECTION("does not load the module when the configuration is invalid") { AGENT_CONFIGURATION.modules_config_dir = BROKEN_MODULES_CONFIG; auto c_ptr = std::make_shared<MockConnector>(); RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION }; REQUIRE(r_p.hasModuleConfig(REVERSE_VALID_MODULE_NAME)); REQUIRE_FALSE(r_p.hasModule(REVERSE_VALID_MODULE_NAME)); } } TEST_CASE("Process correctly requests for external modules", "[component]") { AGENT_CONFIGURATION.modules_config_dir = ""; auto c_ptr = std::make_shared<MockConnector>(); RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION }; lth_jc::JsonContainer envelope { VALID_ENVELOPE_TXT }; std::vector<lth_jc::JsonContainer> debug {}; lth_jc::JsonContainer data {}; data.set<std::string>("transaction_id", "42"); SECTION("correctly process nonblocking requests") { SECTION("send a blocking response when the requested action succeeds") { REQUIRE(!c_ptr->sent_blocking_response); data.set<std::string>("module", "reverse_valid"); data.set<std::string>("action", "string"); lth_jc::JsonContainer params {}; params.set<std::string>("argument", "was"); data.set<lth_jc::JsonContainer>("params", params); const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 }; REQUIRE_NOTHROW(r_p.processRequest(RequestType::Blocking, p_c)); // Wait a bit to let the execution thread finish pcp_util::this_thread::sleep_for( pcp_util::chrono::microseconds(100000)); REQUIRE(c_ptr->sent_blocking_response); } SECTION("send a PXP error in case of action failure") { data.set<std::string>("module", "failures_test"); data.set<std::string>("action", "broken_action"); lth_jc::JsonContainer params {}; params.set<std::string>("argument", "bikini"); data.set<lth_jc::JsonContainer>("params", params); const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 }; REQUIRE_THROWS_AS(r_p.processRequest(RequestType::Blocking, p_c), MockConnector::pxpError_msg); } } SECTION("correctly process non-blocking requests") { SECTION("send a provisional response when the requested action starts " "successfully") { REQUIRE(!c_ptr->sent_provisional_response); data.set<std::string>("module", "reverse_valid"); data.set<bool>("notify_outcome", false); data.set<std::string>("action", "string"); lth_jc::JsonContainer params {}; params.set<std::string>("argument", "lemon"); data.set<lth_jc::JsonContainer>("params", params); const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 }; REQUIRE_NOTHROW(r_p.processRequest(RequestType::NonBlocking, p_c)); // Wait a bit to let the execution thread finish pcp_util::this_thread::sleep_for( pcp_util::chrono::microseconds(100000)); REQUIRE(c_ptr->sent_provisional_response); } SECTION("send a non-blocking response when the requested action succeeds") { REQUIRE(!c_ptr->sent_provisional_response); REQUIRE(!c_ptr->sent_non_blocking_response); data.set<std::string>("module", "reverse_valid"); data.set<bool>("notify_outcome", true); data.set<std::string>("action", "string"); lth_jc::JsonContainer params {}; params.set<std::string>("argument", "kondogbia"); data.set<lth_jc::JsonContainer>("params", params); const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 }; REQUIRE_NOTHROW(r_p.processRequest(RequestType::NonBlocking, p_c)); // Wait a bit to let the execution thread finish plus the // 100 ms of pause for getting the output pcp_util::this_thread::sleep_for( pcp_util::chrono::microseconds(200000)); REQUIRE(c_ptr->sent_provisional_response); REQUIRE(c_ptr->sent_non_blocking_response); } } fs::remove_all(SPOOL); } #endif // TEST_VIRTUAL } // namespace PXPAgent <commit_msg>(maint) Consider output processing delay in component test<commit_after>#include "../common/certs.hpp" #include "../common/mock_connector.hpp" #include "root_path.hpp" #include <pxp-agent/external_module.hpp> #include <pxp-agent/request_processor.hpp> #include <pxp-agent/configuration.hpp> #include <leatherman/json_container/json_container.hpp> #include <cpp-pcp-client/util/thread.hpp> // this_thread::sleep_for #include <cpp-pcp-client/util/chrono.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/operations.hpp> #include <catch.hpp> namespace PXPAgent { #ifdef TEST_VIRTUAL namespace lth_jc = leatherman::json_container; namespace pcp_util = PCPClient::Util; namespace fs = boost::filesystem; static const std::string REVERSE_VALID_MODULE_NAME { "reverse_valid" }; TEST_CASE("Valid External Module Configuration", "[component]") { AGENT_CONFIGURATION.modules_config_dir = VALID_MODULES_CONFIG; auto c_ptr = std::make_shared<MockConnector>(); RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION }; SECTION("retrieves the configuration from file if valid JSON format") { REQUIRE(r_p.hasModuleConfig(REVERSE_VALID_MODULE_NAME)); } SECTION("does load the module when the configuration is valid") { REQUIRE(r_p.hasModuleConfig(REVERSE_VALID_MODULE_NAME)); REQUIRE(r_p.hasModule(REVERSE_VALID_MODULE_NAME)); } } TEST_CASE("Badly formatted External Module Configuration", "[component]") { AGENT_CONFIGURATION.modules_config_dir = BAD_FORMAT_MODULES_CONFIG; auto c_ptr = std::make_shared<MockConnector>(); RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION }; SECTION("stores a null JSON value as the configuration, if it's in an " "invalid JSON format") { REQUIRE(r_p.getModuleConfig(REVERSE_VALID_MODULE_NAME) == "null"); } SECTION("does not load the module when the configuration is in " "bad JSON format") { REQUIRE(r_p.getModuleConfig(REVERSE_VALID_MODULE_NAME) == "null"); REQUIRE_FALSE(r_p.hasModule(REVERSE_VALID_MODULE_NAME)); } } TEST_CASE("Invalid (by metadata) External Module Configuration", "[component]") { SECTION("does not load the module when the configuration is invalid") { AGENT_CONFIGURATION.modules_config_dir = BROKEN_MODULES_CONFIG; auto c_ptr = std::make_shared<MockConnector>(); RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION }; REQUIRE(r_p.hasModuleConfig(REVERSE_VALID_MODULE_NAME)); REQUIRE_FALSE(r_p.hasModule(REVERSE_VALID_MODULE_NAME)); } } TEST_CASE("Process correctly requests for external modules", "[component]") { AGENT_CONFIGURATION.modules_config_dir = ""; auto c_ptr = std::make_shared<MockConnector>(); RequestProcessor r_p { c_ptr, AGENT_CONFIGURATION }; lth_jc::JsonContainer envelope { VALID_ENVELOPE_TXT }; std::vector<lth_jc::JsonContainer> debug {}; lth_jc::JsonContainer data {}; data.set<std::string>("transaction_id", "42"); SECTION("correctly process nonblocking requests") { SECTION("send a blocking response when the requested action succeeds") { REQUIRE(!c_ptr->sent_blocking_response); data.set<std::string>("module", "reverse_valid"); data.set<std::string>("action", "string"); lth_jc::JsonContainer params {}; params.set<std::string>("argument", "was"); data.set<lth_jc::JsonContainer>("params", params); const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 }; REQUIRE_NOTHROW(r_p.processRequest(RequestType::Blocking, p_c)); // Wait a bit to let the execution thread finish pcp_util::this_thread::sleep_for( pcp_util::chrono::microseconds(100000)); REQUIRE(c_ptr->sent_blocking_response); } SECTION("send a PXP error in case of action failure") { data.set<std::string>("module", "failures_test"); data.set<std::string>("action", "broken_action"); lth_jc::JsonContainer params {}; params.set<std::string>("argument", "bikini"); data.set<lth_jc::JsonContainer>("params", params); const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 }; REQUIRE_THROWS_AS(r_p.processRequest(RequestType::Blocking, p_c), MockConnector::pxpError_msg); } } SECTION("correctly process non-blocking requests") { SECTION("send a provisional response when the requested action starts " "successfully") { REQUIRE(!c_ptr->sent_provisional_response); data.set<std::string>("module", "reverse_valid"); data.set<bool>("notify_outcome", false); data.set<std::string>("action", "string"); lth_jc::JsonContainer params {}; params.set<std::string>("argument", "lemon"); data.set<lth_jc::JsonContainer>("params", params); const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 }; REQUIRE_NOTHROW(r_p.processRequest(RequestType::NonBlocking, p_c)); // Wait a bit to let the execution thread finish pcp_util::this_thread::sleep_for( pcp_util::chrono::microseconds(100000)); REQUIRE(c_ptr->sent_provisional_response); } SECTION("send a non-blocking response when the requested action succeeds") { REQUIRE(!c_ptr->sent_provisional_response); REQUIRE(!c_ptr->sent_non_blocking_response); data.set<std::string>("module", "reverse_valid"); data.set<bool>("notify_outcome", true); data.set<std::string>("action", "string"); lth_jc::JsonContainer params {}; params.set<std::string>("argument", "kondogbia"); data.set<lth_jc::JsonContainer>("params", params); const PCPClient::ParsedChunks p_c { envelope, data, debug, 0 }; REQUIRE_NOTHROW(r_p.processRequest(RequestType::NonBlocking, p_c)); // Wait a bit to let the module complete, the execution // thread process the output (there's a OUTPUT_DELAY_MS // pause) and send the non-blocking response pcp_util::this_thread::sleep_for( pcp_util::chrono::milliseconds(300 + ExternalModule::OUTPUT_DELAY_MS)); REQUIRE(c_ptr->sent_provisional_response); REQUIRE(c_ptr->sent_non_blocking_response); } } fs::remove_all(SPOOL); } #endif // TEST_VIRTUAL } // namespace PXPAgent <|endoftext|>
<commit_before>#include "RE_tree.h" enum { Regex_symbol = 0, A_symbol, B_symbol, C_symbol, D_symbol, E_symbol, F_symbol, e_symbol, sign_symbol, eof_symbol }; class Grammar_node { public: int symbol; char value; Grammar_node *prt_node; Grammar_node *lch_node; Grammar_node *bro_node; Grammar_node(int s, Grammar_node *p, char v = '\0', Grammar_node *l = NULL, Grammar_node *b = NULL); }; Grammar_node::Grammar_node(int s, Grammar_node *p, char v, Grammar_node *l, Grammar_node *b) { symbol = s; prt_node = p; lch_node = l; bro_node = b; value = v; } void insert_production_one_child(Grammar_node *p, char child_symbol, char num = '\0') { Grammar_node *p_child = new Grammar_node(child_symbol, p, num); p->lch_node = p_child; } void insert_production_two_child(Grammar_node *p, char lchild_symbol, char rchild_symbol) { Grammar_node *p_left = new Grammar_node(lchild_symbol, p); Grammar_node *p_right = new Grammar_node(rchild_symbol, p); p->lch_node = p_left; p_left->bro_node = p_right; } void insert_production_three_child(Grammar_node *p, char lchild_symbol, char mchild_symbol, char rchild_symbol) { Grammar_node *p_left = new Grammar_node(lchild_symbol, p); Grammar_node *p_middle = new Grammar_node(mchild_symbol, p); Grammar_node *p_right = new Grammar_node(rchild_symbol, p); p->lch_node = p_left; p_left->bro_node = p_middle; p_middle->bro_node = p_right; } /* RegEx -> B A */ void insert_production_Regex(char symbol, Grammar_node *p, char num) { insert_production_two_child(p, B_symbol, A_symbol); } /* A -> | B A -> eof */ void insert_production_A(char symbol, Grammar_node *p, char num) { if(symbol =='|') insert_production_three_child(p, '|', B_symbol, A_symbol); else insert_production_one_child(p, eof_symbol); } /* B -> D C */ void insert_production_B(char symbol, Grammar_node *p, char num) { insert_production_two_child(p, D_symbol, C_symbol); } /* C -> D C -> eof */ void insert_production_C(char symbol, Grammar_node *p, char num) { if(symbol == '(' || symbol == e_symbol) insert_production_two_child(p, B_symbol, A_symbol); else insert_production_one_child(p, eof_symbol); } /* D -> E F */ void insert_production_D(char symbol, Grammar_node *p, char num) { insert_production_two_child(p, E_symbol, F_symbol); } /* E -> ( RegEx ) -> element */ void insert_production_E(char symbol, Grammar_node *p, char num) { if(symbol == '(') insert_production_three_child(p, '(', Regex_symbol, ')'); else insert_production_one_child(p, e_symbol, num); } /* F -> * -> eof */ void insert_production_F(char symbol, Grammar_node *p, char num) { if(symbol == '*') insert_production_one_child(p, '*'); else insert_production_one_child(p, eof_symbol); } /* 初始化终结符集合terminator,以及产生式数组insert */ RE_tree::RE_tree() { terminator.insert('*'); terminator.insert('|'); terminator.insert('('); terminator.insert(')'); terminator.insert(e_symbol); terminator.insert(eof_symbol); insert.resize(7, NULL); insert[0] = insert_production_Regex; insert[1] = insert_production_A; insert[2] = insert_production_B; insert[3] = insert_production_C; insert[4] = insert_production_D; insert[5] = insert_production_E; insert[6] = insert_production_F; grammar_tree = new Grammar_node(Regex_symbol, NULL); regex_tree = new Regex_node; } /* 析构函数,释放new表达式所分配的内存 */ RE_tree::~RE_tree() { delete_grammar_tree(grammar_tree); delete_regex_tree(regex_tree); } void RE_tree::delete_grammar_tree(Grammar_node *node) { if(node == NULL) return; delete_grammar_tree(node->lch_node); delete_grammar_tree(node->bro_node); delete node; } void RE_tree::delete_regex_tree(Regex_node *node) { if(node == NULL) return; delete_regex_tree(node->left); delete_regex_tree(node->right); delete node; } /* 读入用户输入的正则表达式 */ void RE_tree::input_regex() { cout << "请输入正则表达式:" << endl; cin >> regex_string; } /* 构建文法分析树 */ void RE_tree::generate_tree() { string::iterator pos_current = regex_string.begin(); string::iterator pos_end = regex_string.end(); Grammar_node * node = grammar_tree; char symbol_current = get_current_symbol(pos_current); while(true) { if(terminator.find(node->symbol) != terminator.end() && node->symbol == eof_symbol) node = get_next_node(node); else if(terminator.find(node->symbol) != terminator.end() && symbol_current == node->symbol) { node = get_next_node(node); pos_current++; //这里不需要先判断是否pos_current != pos_end if(pos_current != pos_end) symbol_current = get_current_symbol(pos_current); else symbol_current = eof_symbol; } else if(terminator.find(node->symbol) == terminator.end()) { insert[node->symbol](symbol_current, node, *pos_current); node = node->lch_node; } if(node == NULL && pos_current == pos_end) return; } } /* 构建文法分析树辅助函数,获取下一个符号信息 */ char RE_tree::get_current_symbol(string::iterator pos_current) { if(terminator.find(*pos_current) != terminator.end()) return *pos_current; else return e_symbol; } /* 构建文法分析树辅助函数,获取下一个符号信息 */ Grammar_node *RE_tree::get_next_node(Grammar_node *p) { if(p == NULL) return NULL; if(p->bro_node != NULL) return p->bro_node; return get_next_node(p->prt_node); } /* 简化分析树作为输出,之后用该树来构造NFA */ void RE_tree::simplification(Grammar_node *root, Regex_node *node) { if(root->symbol == B_symbol) { if(root->bro_node->lch_node->symbol == eof_symbol) simplification(root->lch_node, node); else { node->value = ALT; Regex_node *left = new Regex_node; Regex_node *right = new Regex_node; node->left = left; node->right = right; simplification(root->lch_node, left); simplification(root->bro_node->lch_node->bro_node, right); } } else if(root->symbol == D_symbol) { if(root->bro_node->lch_node->symbol == eof_symbol) simplification(root->lch_node, node); else { node->value = CONCAT; Regex_node *left = new Regex_node; Regex_node *right = new Regex_node; node->left = left; node->right = right; simplification(root->lch_node, left); simplification(root->bro_node->lch_node, right); } } else if(root->symbol == E_symbol) { if(root->bro_node->lch_node->symbol == eof_symbol) simplification(root->lch_node, node); else { node->value = CLOSURE; Regex_node *left = new Regex_node; node->left = left; node->right = NULL; simplification(root->lch_node, left); } } else if(root->symbol == '(') simplification(root->bro_node, node); else if(root->symbol == e_symbol) { node->value = root->value; node->left = node->right = NULL; } else simplification(root->lch_node, node); } /* 打印RE树,检查是否得到正确结果 */ void RE_tree::print_tree(Regex_node *node) { if(node == NULL) cout<<"NULL "; else { cout<<(int)node->value<<" "; print_tree(node->left); print_tree(node->right); } } /* 执行输入的正则表达式到RE树的转换 */ Regex_node *RE_tree::get_re_tree() { input_regex(); generate_tree(); simplification(grammar_tree, regex_tree); // print_tree(regex_tree); return regex_tree; } /* int main() { RE_tree re; re.get_re_tree(); } */ <commit_msg>update<commit_after>#include "RE_tree.h" enum { Regex_symbol = 0, A_symbol, B_symbol, C_symbol, D_symbol, E_symbol, F_symbol, e_symbol, sign_symbol, eof_symbol }; class Grammar_node { public: int symbol; char value; Grammar_node *prt_node; Grammar_node *lch_node; Grammar_node *bro_node; Grammar_node(int s, Grammar_node *p, char v = '\0', Grammar_node *l = NULL, Grammar_node *b = NULL); }; Grammar_node::Grammar_node(int s, Grammar_node *p, char v, Grammar_node *l, Grammar_node *b) { symbol = s; prt_node = p; lch_node = l; bro_node = b; value = v; } void insert_production_one_child(Grammar_node *p, char child_symbol, char num = '\0') { Grammar_node *p_child = new Grammar_node(child_symbol, p, num); p->lch_node = p_child; } void insert_production_two_child(Grammar_node *p, char lchild_symbol, char rchild_symbol) { Grammar_node *p_left = new Grammar_node(lchild_symbol, p); Grammar_node *p_right = new Grammar_node(rchild_symbol, p); p->lch_node = p_left; p_left->bro_node = p_right; } void insert_production_three_child(Grammar_node *p, char lchild_symbol, char mchild_symbol, char rchild_symbol) { Grammar_node *p_left = new Grammar_node(lchild_symbol, p); Grammar_node *p_middle = new Grammar_node(mchild_symbol, p); Grammar_node *p_right = new Grammar_node(rchild_symbol, p); p->lch_node = p_left; p_left->bro_node = p_middle; p_middle->bro_node = p_right; } /* RegEx -> B A */ void insert_production_Regex(char symbol, Grammar_node *p, char num) { insert_production_two_child(p, B_symbol, A_symbol); } /* A -> | B A -> eof */ void insert_production_A(char symbol, Grammar_node *p, char num) { if(symbol =='|') insert_production_three_child(p, '|', B_symbol, A_symbol); else insert_production_one_child(p, eof_symbol); } /* B -> D C */ void insert_production_B(char symbol, Grammar_node *p, char num) { insert_production_two_child(p, D_symbol, C_symbol); } /* C -> D C -> eof */ void insert_production_C(char symbol, Grammar_node *p, char num) { if(symbol == '(' || symbol == e_symbol) insert_production_two_child(p, B_symbol, A_symbol); else insert_production_one_child(p, eof_symbol); } /* D -> E F */ void insert_production_D(char symbol, Grammar_node *p, char num) { insert_production_two_child(p, E_symbol, F_symbol); } /* E -> ( RegEx ) -> element */ void insert_production_E(char symbol, Grammar_node *p, char num) { if(symbol == '(') insert_production_three_child(p, '(', Regex_symbol, ')'); else insert_production_one_child(p, e_symbol, num); } /* F -> * -> eof */ void insert_production_F(char symbol, Grammar_node *p, char num) { if(symbol == '*') insert_production_one_child(p, '*'); else insert_production_one_child(p, eof_symbol); } /* 初始化终结符集合terminator,以及产生式数组insert */ RE_tree::RE_tree() { terminator.insert('*'); terminator.insert('|'); terminator.insert('('); terminator.insert(')'); terminator.insert(e_symbol); terminator.insert(eof_symbol); insert.reserve(7); insert.push_back(insert_production_Regex); insert.push_back(insert_production_A); insert.push_back(insert_production_B); insert.push_back(insert_production_C); insert.push_back(insert_production_D); insert.push_back(insert_production_E); insert.push_back(insert_production_F); grammar_tree = new Grammar_node(Regex_symbol, NULL); regex_tree = new Regex_node; } /* 析构函数,释放new表达式所分配的内存 */ RE_tree::~RE_tree() { delete_grammar_tree(grammar_tree); delete_regex_tree(regex_tree); } void RE_tree::delete_grammar_tree(Grammar_node *node) { if(node == NULL) return; delete_grammar_tree(node->lch_node); delete_grammar_tree(node->bro_node); delete node; } void RE_tree::delete_regex_tree(Regex_node *node) { if(node == NULL) return; delete_regex_tree(node->left); delete_regex_tree(node->right); delete node; } /* 读入用户输入的正则表达式 */ void RE_tree::input_regex() { cout << "请输入正则表达式:" << endl; cin >> regex_string; } /* 构建文法分析树 */ void RE_tree::generate_tree() { string::iterator pos_current = regex_string.begin(); string::iterator pos_end = regex_string.end(); Grammar_node * node = grammar_tree; char symbol_current = get_current_symbol(pos_current); while(true) { if(terminator.find(node->symbol) != terminator.end() && node->symbol == eof_symbol) node = get_next_node(node); else if(terminator.find(node->symbol) != terminator.end() && symbol_current == node->symbol) { node = get_next_node(node); pos_current++; //这里不需要先判断是否pos_current != pos_end if(pos_current != pos_end) symbol_current = get_current_symbol(pos_current); else symbol_current = eof_symbol; } else if(terminator.find(node->symbol) == terminator.end()) { insert[node->symbol](symbol_current, node, *pos_current); node = node->lch_node; } if(node == NULL && pos_current == pos_end) return; } } /* 构建文法分析树辅助函数,获取下一个符号信息 */ char RE_tree::get_current_symbol(string::iterator pos_current) { if(terminator.find(*pos_current) != terminator.end()) return *pos_current; else return e_symbol; } /* 构建文法分析树辅助函数,获取下一个符号信息 */ Grammar_node *RE_tree::get_next_node(Grammar_node *p) { if(p == NULL) return NULL; if(p->bro_node != NULL) return p->bro_node; return get_next_node(p->prt_node); } /* 简化分析树作为输出,之后用该树来构造NFA */ void RE_tree::simplification(Grammar_node *root, Regex_node *node) { if(root->symbol == B_symbol) { if(root->bro_node->lch_node->symbol == eof_symbol) simplification(root->lch_node, node); else { node->value = ALT; Regex_node *left = new Regex_node; Regex_node *right = new Regex_node; node->left = left; node->right = right; simplification(root->lch_node, left); simplification(root->bro_node->lch_node->bro_node, right); } } else if(root->symbol == D_symbol) { if(root->bro_node->lch_node->symbol == eof_symbol) simplification(root->lch_node, node); else { node->value = CONCAT; Regex_node *left = new Regex_node; Regex_node *right = new Regex_node; node->left = left; node->right = right; simplification(root->lch_node, left); simplification(root->bro_node->lch_node, right); } } else if(root->symbol == E_symbol) { if(root->bro_node->lch_node->symbol == eof_symbol) simplification(root->lch_node, node); else { node->value = CLOSURE; Regex_node *left = new Regex_node; node->left = left; node->right = NULL; simplification(root->lch_node, left); } } else if(root->symbol == '(') simplification(root->bro_node, node); else if(root->symbol == e_symbol) { node->value = root->value; node->left = node->right = NULL; } else simplification(root->lch_node, node); } /* 打印RE树,检查是否得到正确结果 */ void RE_tree::print_tree(Regex_node *node) { if(node == NULL) cout<<"NULL "; else { cout<<(int)node->value<<" "; print_tree(node->left); print_tree(node->right); } } /* 执行输入的正则表达式到RE树的转换 */ Regex_node *RE_tree::get_re_tree() { input_regex(); generate_tree(); simplification(grammar_tree, regex_tree); // print_tree(regex_tree); return regex_tree; } /* int main() { RE_tree re; re.get_re_tree(); } */ <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: MultiResMIRegistration.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium 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. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 "itkPhysicalImage.h" #include "itkImageRegionIterator.h" #include "itkMultiResolutionMutualInformationRigidRegistration.h" #include <iostream> int main() { //------------------------------------------------------------ // Create two simple images // Two Gaussians with one translated (7,3,2) pixels from another //------------------------------------------------------------ //Allocate Images typedef float PixelType; typedef itk::PhysicalImage<PixelType,3> ReferenceType; typedef itk::PhysicalImage<PixelType,3> TargetType; enum { ImageDimension = ReferenceType::ImageDimension }; ReferenceType::SizeType size = {{100,100,40}}; ReferenceType::IndexType index = {{0,0,0}}; ReferenceType::RegionType region; region.SetSize( size ); region.SetIndex( index ); ReferenceType::Pointer imgReference = ReferenceType::New(); imgReference->SetLargestPossibleRegion( region ); imgReference->SetBufferedRegion( region ); imgReference->SetRequestedRegion( region ); imgReference->Allocate(); TargetType::Pointer imgTarget = TargetType::New(); imgTarget->SetLargestPossibleRegion( region ); imgTarget->SetBufferedRegion( region ); imgTarget->SetRequestedRegion( region ); imgTarget->Allocate(); // Fill images with a 3D gaussian typedef itk::ImageRegionIterator<ReferenceType> ReferenceIteratorType; typedef itk::ImageRegionIterator<TargetType> TargetIteratorType; itk::Point<double,3> center; center[0] = (double)region.GetSize()[0]/2.0; center[1] = (double)region.GetSize()[1]/2.0; center[2] = (double)region.GetSize()[2]/2,0; const double s = (double)region.GetSize()[0]/2.0; itk::Point<double,3> p; itk::Vector<double,3> d; // Set the displacement itk::Vector<double,3> displacement; displacement[0] = 7; displacement[1] = 3; displacement[2] = 2; ReferenceIteratorType ri(imgReference,region); TargetIteratorType ti(imgTarget,region); ri.Begin(); while(!ri.IsAtEnd()) { p[0] = ri.GetIndex()[0]; p[1] = ri.GetIndex()[1]; p[2] = ri.GetIndex()[2]; d = p-center; d += displacement; const double x = d[0]; const double y = d[1]; const double z = d[2]; ri.Set( (PixelType)( 200.0 * exp( - ( x*x + y*y + z*z )/(s*s) ) ) ); ++ri; } ti.Begin(); while(!ti.IsAtEnd()) { p[0] = ti.GetIndex()[0]; p[1] = ti.GetIndex()[1]; p[2] = ti.GetIndex()[2]; d = p-center; const double x = d[0]; const double y = d[1]; const double z = d[2]; ti.Set( (PixelType)( 200.0 * exp( - ( x*x + y*y + z*z )/(s*s) ) ) ); ++ti; } // set image origin to be center of the image double transCenter[3]; for( unsigned int j = 0; j < 3; j++ ) { transCenter[j] = -0.5 * double(size[j] - 1); } imgReference->SetOrigin( transCenter ); imgTarget->SetOrigin( transCenter ); /** * Setup the registrator */ typedef itk::MultiResolutionMutualInformationRigidRegistration< ReferenceType,TargetType> MRRegistrationType; MRRegistrationType::Pointer registrator = MRRegistrationType::New(); registrator->SetTarget( imgTarget ); registrator->SetReference( imgReference ); registrator->SetNumberOfLevels( 3 ); unsigned int niter[4] = { 300, 300, 300 }; double rates[4] = { 1e-6, 1e-6, 1e-7 }; double scales[4] = { 1000, 100, 100 }; registrator->SetNumberOfIterations( niter ); registrator->SetLearningRates( rates ); registrator->SetTranslationScales( scales ); MRRegistrationType::RegistrationPointer method = registrator->GetInternalRegistrationMethod(); // set metric related parameters method->GetMetric()->SetTargetStandardDeviation( 5.0 ); method->GetMetric()->SetReferenceStandardDeviation( 5.0 ); method->GetMetric()->SetNumberOfSpatialSamples( 50 ); std::cout << "Target schedule: " << std::endl; std::cout << registrator->GetTargetPyramid()->GetSchedule() << std::endl; std::cout << "Reference schedule: " << std::endl; std::cout << registrator->GetReferencePyramid()->GetSchedule() << std::endl; /** * Do the registration */ registrator->StartRegistration(); /** * Check the results */ MRRegistrationType::RegistrationType::ParametersType solution = method->GetParameters(); std::cout << "Solution is: " << solution << std::endl; // // check results to see if it is within range // bool pass = true; double trueParameters[7] = { 0, 0, 0, 1, 0, 0, 0 }; trueParameters[4] = - displacement[0]; trueParameters[5] = - displacement[1]; trueParameters[6] = - displacement[2]; for( unsigned int j = 0; j < 4; j++ ) { if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.02 ) { pass = false; } } for( unsigned int j = 4; j < 7; j++ ) { if( vnl_math_abs( solution[j] - trueParameters[j] ) > 1.0 ) { pass = false; } } if( !pass ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; return 0; } <commit_msg>ENH: new multi-resolution example using real data<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: MultiResMIRegistration.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium 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. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 "MIRegistrationApp.h" #include "itkExceptionObject.h" int main(int argc, char *argv[]) { if ( argc < 2 ) { std::cout << "Parameter file name missing" << std::endl; std::cout << std::endl; std::cout << "Usage: MIRigidRegistration param.file" << std::endl; return 1; } // run the registration try { MIRegistrationApp theApp( argv[1] ); theApp.Execute(); } catch( itk::ExceptionObject& err) { std::cout << "Caught an exception: " << std::endl; std::cout << err.GetLocation() << std::endl; std::cout << err.GetDescription() << std::endl; } return 0; } <|endoftext|>
<commit_before>// // Copyright 2013 Jeff Bush // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <iostream> #include "Vverilator_tb.h" #include "verilated.h" #if VM_TRACE #include <verilated_vcd_c.h> #endif using namespace std; vluint64_t currentTime = 0; int main(int argc, char **argv, char **env) { Verilated::commandArgs(argc, argv); Verilated::debug(0); Vverilator_tb* testbench = new Vverilator_tb; testbench->reset = 1; #if VM_TRACE // If verilator was invoked with --trace Verilated::traceEverOn(true); VL_PRINTF("Enabling waves...\n"); VerilatedVcdC* tfp = new VerilatedVcdC; testbench->trace(tfp, 99); tfp->open("trace.vcd"); #endif while (!Verilated::gotFinish()) { if (currentTime > 10) testbench->reset = 0; // Deassert reset // Toggle clock testbench->clk = !testbench->clk; testbench->eval(); #if VM_TRACE if (tfp) tfp->dump(currentTime); // Create waveform trace for this timestamp #endif currentTime++; } #if VM_TRACE if (tfp) tfp->close(); #endif testbench->final(); delete testbench; exit(0); } // This is invoked directly from verilator_tb, as there isn't a builtin method // to write binary data in verilog. void fputw(IData fileid, int value) { FILE *fp = VL_CVT_I_FP(fileid); int swapped = ((value & 0xff000000) >> 24) | ((value & 0x00ff0000) >> 8) | ((value & 0x0000ff00) << 8) | ((value & 0x000000ff) << 24); fwrite(&swapped, 1, 4, fp); } <commit_msg>Properly support $time in Verilator<commit_after>// // Copyright 2013 Jeff Bush // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <iostream> #include "Vverilator_tb.h" #include "verilated.h" #if VM_TRACE #include <verilated_vcd_c.h> #endif using namespace std; vluint64_t currentTime = 0; double sc_time_stamp() { return currentTime; } int main(int argc, char **argv, char **env) { Verilated::commandArgs(argc, argv); Verilated::debug(0); Vverilator_tb* testbench = new Vverilator_tb; testbench->reset = 1; #if VM_TRACE // If verilator was invoked with --trace Verilated::traceEverOn(true); VL_PRINTF("Enabling waves...\n"); VerilatedVcdC* tfp = new VerilatedVcdC; testbench->trace(tfp, 99); tfp->open("trace.vcd"); #endif while (!Verilated::gotFinish()) { if (currentTime > 10) testbench->reset = 0; // Deassert reset // Toggle clock testbench->clk = !testbench->clk; testbench->eval(); #if VM_TRACE if (tfp) tfp->dump(currentTime); // Create waveform trace for this timestamp #endif currentTime++; } #if VM_TRACE if (tfp) tfp->close(); #endif testbench->final(); delete testbench; exit(0); } // This is invoked directly from verilator_tb, as there isn't a builtin method // to write binary data in verilog. void fputw(IData fileid, int value) { FILE *fp = VL_CVT_I_FP(fileid); int swapped = ((value & 0xff000000) >> 24) | ((value & 0x00ff0000) >> 8) | ((value & 0x0000ff00) << 8) | ((value & 0x000000ff) << 24); fwrite(&swapped, 1, 4, fp); } <|endoftext|>
<commit_before>//===-- ClangFuzzer.cpp - Fuzz Clang --------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements a function that runs Clang on a single /// input. This function is then linked into the Fuzzer library. /// //===----------------------------------------------------------------------===// #include "clang/Tooling/Tooling.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Frontend/CompilerInstance.h" #include "llvm/Option/Option.h" using namespace clang; extern "C" void TestOneInput(uint8_t *data, size_t size) { std::string s((const char *)data, size); llvm::opt::ArgStringList CC1Args; CC1Args.push_back("-cc1"); CC1Args.push_back("test.cc"); llvm::IntrusiveRefCntPtr<FileManager> Files( new FileManager(FileSystemOptions())); IgnoringDiagConsumer Diags; IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, &Diags, false); std::unique_ptr<clang::CompilerInvocation> Invocation( tooling::newInvocation(&Diagnostics, CC1Args)); std::unique_ptr<llvm::MemoryBuffer> Input = llvm::MemoryBuffer::getMemBuffer(s); Invocation->getPreprocessorOpts().addRemappedFile("test.cc", Input.release()); std::unique_ptr<tooling::ToolAction> action( tooling::newFrontendActionFactory<clang::SyntaxOnlyAction>()); action->runInvocation(Invocation.release(), Files.get(), &Diags); } <commit_msg>[clang-fuzzer] make clang-fuzzer slightly faster by removing one redundant directory scan<commit_after>//===-- ClangFuzzer.cpp - Fuzz Clang --------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements a function that runs Clang on a single /// input. This function is then linked into the Fuzzer library. /// //===----------------------------------------------------------------------===// #include "clang/Tooling/Tooling.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Frontend/CompilerInstance.h" #include "llvm/Option/Option.h" using namespace clang; extern "C" void TestOneInput(uint8_t *data, size_t size) { std::string s((const char *)data, size); llvm::opt::ArgStringList CC1Args; CC1Args.push_back("-cc1"); CC1Args.push_back("./test.cc"); llvm::IntrusiveRefCntPtr<FileManager> Files( new FileManager(FileSystemOptions())); IgnoringDiagConsumer Diags; IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, &Diags, false); std::unique_ptr<clang::CompilerInvocation> Invocation( tooling::newInvocation(&Diagnostics, CC1Args)); std::unique_ptr<llvm::MemoryBuffer> Input = llvm::MemoryBuffer::getMemBuffer(s); Invocation->getPreprocessorOpts().addRemappedFile("./test.cc", Input.release()); std::unique_ptr<tooling::ToolAction> action( tooling::newFrontendActionFactory<clang::SyntaxOnlyAction>()); action->runInvocation(Invocation.release(), Files.get(), &Diags); } <|endoftext|>
<commit_before>#include <signal.h> #include <cstdlib> #include <string> #include <vector> #include <algorithm> #include <mutex> #include <Wt/WServer> #include <Wt/WResource> #include <Wt/Http/Request> #include <Wt/Http/Response> #include <Wt/WTemplate> #include <Wt/Utils> #include <Wt/Dbo/Dbo> #include <Wt/Dbo/Json> #ifndef BENCHMARK_USE_POSTGRES #include <Wt/Dbo/backend/MySQL> #else #include <Wt/Dbo/backend/Postgres> #endif #include <boost/random/uniform_int_distribution.hpp> #include <boost/random/taus88.hpp> #include <boost/thread/tss.hpp> class MyMessage { public: std::string message; template<class Action> void persist(Action& a) { Wt::Dbo::field(a, message, "message"); } }; class World { public: int randomNumber; template<class Action> void persist(Action& a) { // Workaround for issue #783 if (a.getsValue()) { Wt::Dbo::field(a, randomNumber, "randomNumber"); } else { Wt::Dbo::field(a, randomNumber, "randomnumber"); } } }; class Fortune { public: std::string message; template<class Action> void persist(Action& a) { Wt::Dbo::field(a, message, "message"); } }; namespace Wt { namespace Dbo { template<> struct dbo_traits<World> : public dbo_default_traits { static const char *versionField() { return 0; } static IdType invalidId() { return 0; } }; template<> struct dbo_traits<Fortune> : public dbo_default_traits { static const char *versionField() { return 0; } static IdType invalidId() { return 0; } }; } } class JsonResource : public Wt::WResource { public: virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) { response.setMimeType("application/json"); response.addHeader("Server", "Wt"); MyMessage message; message.message = "Hello, World!"; Wt::Dbo::JsonSerializer writer(response.out()); writer.serialize(message); } }; std::mutex mtx; struct DbStruct { #ifndef BENCHMARK_USE_POSTGRES Wt::Dbo::backend::MySQL connection; #else Wt::Dbo::backend::Postgres connection; #endif Wt::Dbo::Session session; Wt::Dbo::Transaction *transaction; boost::taus88 rng; boost::random::uniform_int_distribution<int> distribution; #ifndef BENCHMARK_USE_POSTGRES DbStruct() : connection("hello_world", "benchmarkdbuser", "benchmarkdbpass", "INSERT_DB_HOST_HERE", 3306), #else DbStruct() : connection("host=INSERT_DB_HOST_HERE port=5432 user=benchmarkdbuser password=benchmarkdbpass dbname=hello_world"), #endif rng(clock()), distribution(1, 10000) { session.setConnection(connection); session.mapClass<World>("world"); session.mapClass<Fortune>("fortune"); transaction = new Wt::Dbo::Transaction(session); } ~DbStruct() { delete transaction; } int rand() { return distribution(rng); } }; struct DbStructNoTransaction { #ifndef BENCHMARK_USE_POSTGRES Wt::Dbo::backend::MySQL connection; #else Wt::Dbo::backend::Postgres connection; #endif Wt::Dbo::Session session; boost::taus88 rng; boost::random::uniform_int_distribution<int> distribution; #ifndef BENCHMARK_USE_POSTGRES DbStructNoTransaction() : connection("hello_world", "benchmarkdbuser", "benchmarkdbpass", "INSERT_DB_HOST_HERE", 3306), #else DbStructNoTransaction() : connection("host=INSERT_DB_HOST_HERE port=5432 user=benchmarkdbuser password=benchmarkdbpass dbname=hello_world"), #endif rng(clock()), distribution(1, 10000) { session.setConnection(connection); session.mapClass<World>("world"); session.mapClass<Fortune>("fortune"); } int rand() { return distribution(rng); } }; class DbResource : public Wt::WResource { private: boost::thread_specific_ptr<DbStruct> dbStruct_; public: virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) { response.setMimeType("application/json"); response.addHeader("Server", "Wt"); DbStruct* db = dbStruct_.get(); if (!db) { std::lock_guard<std::mutex> lock(mtx); if (!db) { db = new DbStruct(); dbStruct_.reset(db); } } Wt::Dbo::ptr<World> entry = db->session.load<World>(db->rand()); Wt::Dbo::JsonSerializer writer(response.out()); writer.serialize(entry); } }; class QueriesResource : public Wt::WResource { private: boost::thread_specific_ptr<DbStruct> dbStruct_; public: virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) { int n; if (const std::string *queries = request.getParameter("queries")) { n = atoi(queries->c_str()); if (n < 1) n = 1; else if (n > 500) n = 500; } else { n = 1; } response.setMimeType("application/json"); response.addHeader("Server", "Wt"); DbStruct* db = dbStruct_.get(); if (!db) { std::lock_guard<std::mutex> lock(mtx); if (!db) { db = new DbStruct(); dbStruct_.reset(db); } } std::vector<Wt::Dbo::ptr<World> > results; results.reserve(n); for (int i = 0; i < n; ++i) { results.push_back(db->session.load<World>(db->rand())); } Wt::Dbo::JsonSerializer writer(response.out()); writer.serialize(results); } }; typedef Wt::Dbo::collection< Wt::Dbo::ptr<Fortune> > Fortunes; typedef std::vector<Wt::Dbo::ptr<Fortune> > VFortunes; bool fortuneCmp(const Wt::Dbo::ptr<Fortune>& f1, const Wt::Dbo::ptr<Fortune>& f2) { return strcmp(f1->message.c_str(), f2->message.c_str()) < 0; } class FortuneTemplate : public Wt::WTemplate { private: const VFortunes *fortunes_; mutable std::vector<Wt::Dbo::ptr<Fortune> >::const_iterator it_; public: FortuneTemplate(const std::vector<Wt::Dbo::ptr<Fortune> >& fortunes) : fortunes_(&fortunes), it_(fortunes.end()), Wt::WTemplate(Wt::WString::tr("fortunes")) { addFunction("while", &Wt::WTemplate::Functions::while_f); } virtual bool conditionValue(const std::string& name) const { if (name == "next-fortune") { if (it_ == fortunes_->end()) it_ = fortunes_->begin(); else ++it_; if (it_ == fortunes_->end()) return false; return true; } else return Wt::WTemplate::conditionValue(name); } virtual void resolveString(const std::string& varName, const std::vector<Wt::WString>& vars, std::ostream& result) { if (varName == "id") format(result, Wt::WString::fromUTF8(boost::lexical_cast<std::string>(it_->id())), Wt::XHTMLUnsafeText); else if (varName == "message") format(result, Wt::WString::fromUTF8((*it_)->message)); else Wt::WTemplate::resolveString(varName, vars, result); } }; class FortuneResource : public Wt::WResource { private: boost::thread_specific_ptr<DbStruct> dbStruct_; public: virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) { response.setMimeType("text/html; charset=utf-8"); response.addHeader("Server", "Wt"); DbStruct* db = dbStruct_.get(); if (!db) { std::lock_guard<std::mutex> lock(mtx); if (!db) { db = new DbStruct(); dbStruct_.reset(db); } } Fortunes fortunes = db->session.find<Fortune>(); VFortunes vFortunes; for (Fortunes::const_iterator i = fortunes.begin(); i != fortunes.end(); ++i) vFortunes.push_back(*i); Fortune* additionalFortune = new Fortune(); additionalFortune->message = "Additional fortune added at request time."; vFortunes.push_back(Wt::Dbo::ptr<Fortune>(additionalFortune)); std::sort(vFortunes.begin(), vFortunes.end(), fortuneCmp); FortuneTemplate tpl(vFortunes); response.out() << "<!DOCTYPE html>"; tpl.renderTemplate(response.out()); } }; class UpdateResource : public Wt::WResource { private: boost::thread_specific_ptr<DbStructNoTransaction> dbStruct_; public: virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) { int n; if (const std::string *queries = request.getParameter("queries")) { n = atoi(queries->c_str()); if (n < 1) n = 1; else if (n > 500) n = 500; } else { n = 1; } response.setMimeType("application/json"); response.addHeader("Server", "Wt"); DbStructNoTransaction* db = dbStruct_.get(); if (!db) { std::lock_guard<std::mutex> lock(mtx); if (!db) { db = new DbStructNoTransaction(); dbStruct_.reset(db); } } std::vector<Wt::Dbo::ptr<World> > results; for (int i = 0; i < n; ++i) { bool success = false; while (!success) { try { Wt::Dbo::Transaction transaction(db->session); Wt::Dbo::ptr<World> world = db->session.load<World>(db->rand()); world.modify()->randomNumber = db->rand(); transaction.commit(); results.push_back(world); success = true; } catch (Wt::Dbo::Exception& e) { // Retry } } } Wt::Dbo::JsonSerializer writer(response.out()); writer.serialize(results); } }; class PlaintextResource : public Wt::WResource { virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) { response.setMimeType("text/plain"); response.addHeader("Server", "Wt"); response.out() << "Hello, World!"; } }; int main(int argc, char** argv) { try { Wt::WServer server(argv[0]); Wt::WMessageResourceBundle *bundle = new Wt::WMessageResourceBundle(); bundle->use("fortunes"); server.setLocalizedStrings(bundle); server.setServerConfiguration(argc, argv, WTHTTP_CONFIGURATION); JsonResource jsonResource; server.addResource(&jsonResource, "/json"); DbResource dbResource; server.addResource(&dbResource, "/db"); QueriesResource queriesResource; server.addResource(&queriesResource, "/queries"); FortuneResource fortuneResource; server.addResource(&fortuneResource, "/fortune"); UpdateResource updateResource; server.addResource(&updateResource, "/updates"); PlaintextResource plaintextResource; server.addResource(&plaintextResource, "/plaintext"); if (server.start()) { int sig = Wt::WServer::waitForShutdown(argv[0]); std::cerr << "Shutdown (signal = " << sig << ")" << std::endl; server.stop(); if (sig == SIGHUP) Wt::WServer::restart(argc, argv, environ); } } catch (Wt::WServer::Exception& e) { std::cerr << e.what() << "\n"; return 1; } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; return 1; } } <commit_msg>Formatting: replaced tabs with 8 spaces, removed PostgreSQL workaround<commit_after>#include <signal.h> #include <cstdlib> #include <string> #include <vector> #include <algorithm> #include <mutex> #include <Wt/WServer> #include <Wt/WResource> #include <Wt/Http/Request> #include <Wt/Http/Response> #include <Wt/WTemplate> #include <Wt/Utils> #include <Wt/Dbo/Dbo> #include <Wt/Dbo/Json> #ifndef BENCHMARK_USE_POSTGRES #include <Wt/Dbo/backend/MySQL> #else #include <Wt/Dbo/backend/Postgres> #endif #include <boost/random/uniform_int_distribution.hpp> #include <boost/random/taus88.hpp> #include <boost/thread/tss.hpp> class MyMessage { public: std::string message; template<class Action> void persist(Action& a) { Wt::Dbo::field(a, message, "message"); } }; class World { public: int randomNumber; template<class Action> void persist(Action& a) { Wt::Dbo::field(a, randomNumber, "randomnumber"); } }; class Fortune { public: std::string message; template<class Action> void persist(Action& a) { Wt::Dbo::field(a, message, "message"); } }; namespace Wt { namespace Dbo { template<> struct dbo_traits<World> : public dbo_default_traits { static const char *versionField() { return 0; } static IdType invalidId() { return 0; } }; template<> struct dbo_traits<Fortune> : public dbo_default_traits { static const char *versionField() { return 0; } static IdType invalidId() { return 0; } }; } } class JsonResource : public Wt::WResource { public: virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) { response.setMimeType("application/json"); response.addHeader("Server", "Wt"); MyMessage message; message.message = "Hello, World!"; Wt::Dbo::JsonSerializer writer(response.out()); writer.serialize(message); } }; std::mutex mtx; struct DbStruct { #ifndef BENCHMARK_USE_POSTGRES Wt::Dbo::backend::MySQL connection; #else Wt::Dbo::backend::Postgres connection; #endif Wt::Dbo::Session session; Wt::Dbo::Transaction *transaction; boost::taus88 rng; boost::random::uniform_int_distribution<int> distribution; #ifndef BENCHMARK_USE_POSTGRES DbStruct() : connection("hello_world", "benchmarkdbuser", "benchmarkdbpass", "INSERT_DB_HOST_HERE", 3306), #else DbStruct() : connection("host=INSERT_DB_HOST_HERE port=5432 user=benchmarkdbuser password=benchmarkdbpass dbname=hello_world"), #endif rng(clock()), distribution(1, 10000) { session.setConnection(connection); session.mapClass<World>("world"); session.mapClass<Fortune>("fortune"); transaction = new Wt::Dbo::Transaction(session); } ~DbStruct() { delete transaction; } int rand() { return distribution(rng); } }; struct DbStructNoTransaction { #ifndef BENCHMARK_USE_POSTGRES Wt::Dbo::backend::MySQL connection; #else Wt::Dbo::backend::Postgres connection; #endif Wt::Dbo::Session session; boost::taus88 rng; boost::random::uniform_int_distribution<int> distribution; #ifndef BENCHMARK_USE_POSTGRES DbStructNoTransaction() : connection("hello_world", "benchmarkdbuser", "benchmarkdbpass", "INSERT_DB_HOST_HERE", 3306), #else DbStructNoTransaction() : connection("host=INSERT_DB_HOST_HERE port=5432 user=benchmarkdbuser password=benchmarkdbpass dbname=hello_world"), #endif rng(clock()), distribution(1, 10000) { session.setConnection(connection); session.mapClass<World>("world"); session.mapClass<Fortune>("fortune"); } int rand() { return distribution(rng); } }; class DbResource : public Wt::WResource { private: boost::thread_specific_ptr<DbStruct> dbStruct_; public: virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) { response.setMimeType("application/json"); response.addHeader("Server", "Wt"); DbStruct* db = dbStruct_.get(); if (!db) { std::lock_guard<std::mutex> lock(mtx); if (!db) { db = new DbStruct(); dbStruct_.reset(db); } } Wt::Dbo::ptr<World> entry = db->session.load<World>(db->rand()); Wt::Dbo::JsonSerializer writer(response.out()); writer.serialize(entry); } }; class QueriesResource : public Wt::WResource { private: boost::thread_specific_ptr<DbStruct> dbStruct_; public: virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) { int n; if (const std::string *queries = request.getParameter("queries")) { n = atoi(queries->c_str()); if (n < 1) n = 1; else if (n > 500) n = 500; } else { n = 1; } response.setMimeType("application/json"); response.addHeader("Server", "Wt"); DbStruct* db = dbStruct_.get(); if (!db) { std::lock_guard<std::mutex> lock(mtx); if (!db) { db = new DbStruct(); dbStruct_.reset(db); } } std::vector<Wt::Dbo::ptr<World> > results; results.reserve(n); for (int i = 0; i < n; ++i) { results.push_back(db->session.load<World>(db->rand())); } Wt::Dbo::JsonSerializer writer(response.out()); writer.serialize(results); } }; typedef Wt::Dbo::collection< Wt::Dbo::ptr<Fortune> > Fortunes; typedef std::vector<Wt::Dbo::ptr<Fortune> > VFortunes; bool fortuneCmp(const Wt::Dbo::ptr<Fortune>& f1, const Wt::Dbo::ptr<Fortune>& f2) { return strcmp(f1->message.c_str(), f2->message.c_str()) < 0; } class FortuneTemplate : public Wt::WTemplate { private: const VFortunes *fortunes_; mutable std::vector<Wt::Dbo::ptr<Fortune> >::const_iterator it_; public: FortuneTemplate(const std::vector<Wt::Dbo::ptr<Fortune> >& fortunes) : fortunes_(&fortunes), it_(fortunes.end()), Wt::WTemplate(Wt::WString::tr("fortunes")) { addFunction("while", &Wt::WTemplate::Functions::while_f); } virtual bool conditionValue(const std::string& name) const { if (name == "next-fortune") { if (it_ == fortunes_->end()) it_ = fortunes_->begin(); else ++it_; if (it_ == fortunes_->end()) return false; return true; } else return Wt::WTemplate::conditionValue(name); } virtual void resolveString(const std::string& varName, const std::vector<Wt::WString>& vars, std::ostream& result) { if (varName == "id") format(result, Wt::WString::fromUTF8(boost::lexical_cast<std::string>(it_->id())), Wt::XHTMLUnsafeText); else if (varName == "message") format(result, Wt::WString::fromUTF8((*it_)->message)); else Wt::WTemplate::resolveString(varName, vars, result); } }; class FortuneResource : public Wt::WResource { private: boost::thread_specific_ptr<DbStruct> dbStruct_; public: virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) { response.setMimeType("text/html; charset=utf-8"); response.addHeader("Server", "Wt"); DbStruct* db = dbStruct_.get(); if (!db) { std::lock_guard<std::mutex> lock(mtx); if (!db) { db = new DbStruct(); dbStruct_.reset(db); } } Fortunes fortunes = db->session.find<Fortune>(); VFortunes vFortunes; for (Fortunes::const_iterator i = fortunes.begin(); i != fortunes.end(); ++i) vFortunes.push_back(*i); Fortune* additionalFortune = new Fortune(); additionalFortune->message = "Additional fortune added at request time."; vFortunes.push_back(Wt::Dbo::ptr<Fortune>(additionalFortune)); std::sort(vFortunes.begin(), vFortunes.end(), fortuneCmp); FortuneTemplate tpl(vFortunes); response.out() << "<!DOCTYPE html>"; tpl.renderTemplate(response.out()); } }; class UpdateResource : public Wt::WResource { private: boost::thread_specific_ptr<DbStructNoTransaction> dbStruct_; public: virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) { int n; if (const std::string *queries = request.getParameter("queries")) { n = atoi(queries->c_str()); if (n < 1) n = 1; else if (n > 500) n = 500; } else { n = 1; } response.setMimeType("application/json"); response.addHeader("Server", "Wt"); DbStructNoTransaction* db = dbStruct_.get(); if (!db) { std::lock_guard<std::mutex> lock(mtx); if (!db) { db = new DbStructNoTransaction(); dbStruct_.reset(db); } } std::vector<Wt::Dbo::ptr<World> > results; for (int i = 0; i < n; ++i) { bool success = false; while (!success) { try { Wt::Dbo::Transaction transaction(db->session); Wt::Dbo::ptr<World> world = db->session.load<World>(db->rand()); world.modify()->randomNumber = db->rand(); transaction.commit(); results.push_back(world); success = true; } catch (Wt::Dbo::Exception& e) { // Retry } } } Wt::Dbo::JsonSerializer writer(response.out()); writer.serialize(results); } }; class PlaintextResource : public Wt::WResource { virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) { response.setMimeType("text/plain"); response.addHeader("Server", "Wt"); response.out() << "Hello, World!"; } }; int main(int argc, char** argv) { try { Wt::WServer server(argv[0]); Wt::WMessageResourceBundle *bundle = new Wt::WMessageResourceBundle(); bundle->use("fortunes"); server.setLocalizedStrings(bundle); server.setServerConfiguration(argc, argv, WTHTTP_CONFIGURATION); JsonResource jsonResource; server.addResource(&jsonResource, "/json"); DbResource dbResource; server.addResource(&dbResource, "/db"); QueriesResource queriesResource; server.addResource(&queriesResource, "/queries"); FortuneResource fortuneResource; server.addResource(&fortuneResource, "/fortune"); UpdateResource updateResource; server.addResource(&updateResource, "/updates"); PlaintextResource plaintextResource; server.addResource(&plaintextResource, "/plaintext"); if (server.start()) { int sig = Wt::WServer::waitForShutdown(argv[0]); std::cerr << "Shutdown (signal = " << sig << ")" << std::endl; server.stop(); if (sig == SIGHUP) Wt::WServer::restart(argc, argv, environ); } } catch (Wt::WServer::Exception& e) { std::cerr << e.what() << "\n"; return 1; } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; return 1; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2017-2018 Daniel Nicoletti <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "enginerequest.h" #include "common.h" #include <Cutelyst/response_p.h> #include <Cutelyst/Context> #include <QLoggingCategory> Q_LOGGING_CATEGORY(CUTELYST_ENGINEREQUEST, "cutelyst.engine_request", QtWarningMsg) using namespace Cutelyst; EngineRequest::EngineRequest() { } EngineRequest::~EngineRequest() { delete context; } void EngineRequest::finalizeBody() { if (!(status & EngineRequest::Chunked)) { Response *response = context->response(); QIODevice *body = response->bodyDevice(); if (body) { body->seek(0); char block[64 * 1024]; while (!body->atEnd()) { qint64 in = body->read(block, sizeof(block)); if (in <= 0) { break; } if (write(block, in) != in) { qCWarning(CUTELYST_ENGINEREQUEST) << "Failed to write body"; break; } } } else { const QByteArray bodyByteArray = response->body(); write(bodyByteArray.constData(), bodyByteArray.size()); } } else if (!(status & EngineRequest::ChunkedDone)) { // Write the final '0' chunk doWrite("0\r\n\r\n", 5); } } void EngineRequest::finalizeError() { Response *res = context->response(); res->setContentType(QStringLiteral("text/html; charset=utf-8")); QByteArray body; // Trick IE. Old versions of IE would display their own error page instead // of ours if we'd give it less than 512 bytes. body.reserve(512); body.append(context->errors().join(QLatin1Char('\n')).toUtf8()); res->setBody(body); // Return 500 res->setStatus(Response::InternalServerError); } void EngineRequest::finalize() { if (context->error()) { finalizeError(); } if ((status & EngineRequest::FinalizedHeaders) || finalizeHeaders()) { finalizeBody(); } processingFinished(); } void EngineRequest::finalizeCookies() { Response *res = context->response(); Headers &headers = res->headers(); const auto cookies = res->cookies(); for (const QNetworkCookie &cookie : cookies) { headers.pushHeader(QStringLiteral("SET_COOKIE"), QString::fromLatin1(cookie.toRawForm())); } } bool EngineRequest::finalizeHeaders() { Response *response = context->response(); Headers &headers = response->headers(); // Fix missing content length if (headers.contentLength() < 0) { qint64 size = response->size(); if (size >= 0) { headers.setContentLength(size); } } finalizeCookies(); // Done status |= EngineRequest::FinalizedHeaders; return writeHeaders(response->status(), headers); } qint64 EngineRequest::write(const char *data, qint64 len) { if (!(status & EngineRequest::Chunked)) { return doWrite(data, len); } else if (!(status & EngineRequest::ChunkedDone)) { const QByteArray chunkSize = QByteArray::number(len, 16).toUpper(); QByteArray chunk; chunk.reserve(int(len + chunkSize.size() + 4)); chunk.append(chunkSize).append("\r\n", 2) .append(data, int(len)).append("\r\n", 2); qint64 retWrite = doWrite(chunk.data(), chunk.size()); // Flag if we wrote an empty chunk if (!len) { status |= EngineRequest::ChunkedDone; } return retWrite == chunk.size() ? len : -1; } return -1; } bool EngineRequest::webSocketHandshake(const QString &key, const QString &origin, const QString &protocol) { if (status & EngineRequest::FinalizedHeaders) { return false; } if (webSocketHandshakeDo(key, origin, protocol)) { status |= EngineRequest::FinalizedHeaders; return true; } return false; } bool EngineRequest::webSocketSendTextMessage(const QString &message) { Q_UNUSED(message) return false; } bool EngineRequest::webSocketSendBinaryMessage(const QByteArray &message) { Q_UNUSED(message) return false; } bool EngineRequest::webSocketSendPing(const QByteArray &payload) { Q_UNUSED(payload) return false; } bool EngineRequest::webSocketClose(quint16 code, const QString &reason) { Q_UNUSED(code) Q_UNUSED(reason) return false; } void EngineRequest::processingFinished() { } bool EngineRequest::webSocketHandshakeDo(const QString &key, const QString &origin, const QString &protocol) { Q_UNUSED(key) Q_UNUSED(origin) Q_UNUSED(protocol) return false; } void EngineRequest::setPath(char *rawPath, const int len) { if (len == 0) { path = QString(); return; } char *data = rawPath; const char *inputPtr = data; bool skipUtf8 = true; int outlen = 0; for (int i = 0; i < len; ++i, ++outlen) { const char c = inputPtr[i]; if (c == '%' && i + 2 < len) { int a = inputPtr[++i]; int b = inputPtr[++i]; if (a >= '0' && a <= '9') a -= '0'; else if (a >= 'a' && a <= 'f') a = a - 'a' + 10; else if (a >= 'A' && a <= 'F') a = a - 'A' + 10; if (b >= '0' && b <= '9') b -= '0'; else if (b >= 'a' && b <= 'f') b = b - 'a' + 10; else if (b >= 'A' && b <= 'F') b = b - 'A' + 10; *data++ = char((a << 4) | b); skipUtf8 = false; } else if (c == '+') { *data++ = ' '; } else { *data++ = c; } } if (skipUtf8) { path = QString::fromLatin1(rawPath, outlen); } else { path = QString::fromUtf8(rawPath, outlen); } } #include "moc_enginerequest.cpp" <commit_msg>Mark Context as Async when Websocket handshake is done to avoid end methods that would send HTML<commit_after>/* * Copyright (C) 2017-2018 Daniel Nicoletti <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "enginerequest.h" #include "common.h" #include <Cutelyst/response_p.h> #include <Cutelyst/Context> #include <QLoggingCategory> Q_LOGGING_CATEGORY(CUTELYST_ENGINEREQUEST, "cutelyst.engine_request", QtWarningMsg) using namespace Cutelyst; EngineRequest::EngineRequest() { } EngineRequest::~EngineRequest() { delete context; } void EngineRequest::finalizeBody() { if (!(status & EngineRequest::Chunked)) { Response *response = context->response(); QIODevice *body = response->bodyDevice(); if (body) { body->seek(0); char block[64 * 1024]; while (!body->atEnd()) { qint64 in = body->read(block, sizeof(block)); if (in <= 0) { break; } if (write(block, in) != in) { qCWarning(CUTELYST_ENGINEREQUEST) << "Failed to write body"; break; } } } else { const QByteArray bodyByteArray = response->body(); write(bodyByteArray.constData(), bodyByteArray.size()); } } else if (!(status & EngineRequest::ChunkedDone)) { // Write the final '0' chunk doWrite("0\r\n\r\n", 5); } } void EngineRequest::finalizeError() { Response *res = context->response(); res->setContentType(QStringLiteral("text/html; charset=utf-8")); QByteArray body; // Trick IE. Old versions of IE would display their own error page instead // of ours if we'd give it less than 512 bytes. body.reserve(512); body.append(context->errors().join(QLatin1Char('\n')).toUtf8()); res->setBody(body); // Return 500 res->setStatus(Response::InternalServerError); } void EngineRequest::finalize() { if (context->error()) { finalizeError(); } if ((status & EngineRequest::FinalizedHeaders) || finalizeHeaders()) { finalizeBody(); } processingFinished(); } void EngineRequest::finalizeCookies() { Response *res = context->response(); Headers &headers = res->headers(); const auto cookies = res->cookies(); for (const QNetworkCookie &cookie : cookies) { headers.pushHeader(QStringLiteral("SET_COOKIE"), QString::fromLatin1(cookie.toRawForm())); } } bool EngineRequest::finalizeHeaders() { Response *response = context->response(); Headers &headers = response->headers(); // Fix missing content length if (headers.contentLength() < 0) { qint64 size = response->size(); if (size >= 0) { headers.setContentLength(size); } } finalizeCookies(); // Done status |= EngineRequest::FinalizedHeaders; return writeHeaders(response->status(), headers); } qint64 EngineRequest::write(const char *data, qint64 len) { if (!(status & EngineRequest::Chunked)) { return doWrite(data, len); } else if (!(status & EngineRequest::ChunkedDone)) { const QByteArray chunkSize = QByteArray::number(len, 16).toUpper(); QByteArray chunk; chunk.reserve(int(len + chunkSize.size() + 4)); chunk.append(chunkSize).append("\r\n", 2) .append(data, int(len)).append("\r\n", 2); qint64 retWrite = doWrite(chunk.data(), chunk.size()); // Flag if we wrote an empty chunk if (!len) { status |= EngineRequest::ChunkedDone; } return retWrite == chunk.size() ? len : -1; } return -1; } bool EngineRequest::webSocketHandshake(const QString &key, const QString &origin, const QString &protocol) { if (status & EngineRequest::FinalizedHeaders) { return false; } if (webSocketHandshakeDo(key, origin, protocol)) { status |= EngineRequest::FinalizedHeaders | EngineRequest::Async; return true; } return false; } bool EngineRequest::webSocketSendTextMessage(const QString &message) { Q_UNUSED(message) return false; } bool EngineRequest::webSocketSendBinaryMessage(const QByteArray &message) { Q_UNUSED(message) return false; } bool EngineRequest::webSocketSendPing(const QByteArray &payload) { Q_UNUSED(payload) return false; } bool EngineRequest::webSocketClose(quint16 code, const QString &reason) { Q_UNUSED(code) Q_UNUSED(reason) return false; } void EngineRequest::processingFinished() { } bool EngineRequest::webSocketHandshakeDo(const QString &key, const QString &origin, const QString &protocol) { Q_UNUSED(key) Q_UNUSED(origin) Q_UNUSED(protocol) return false; } void EngineRequest::setPath(char *rawPath, const int len) { if (len == 0) { path = QString(); return; } char *data = rawPath; const char *inputPtr = data; bool skipUtf8 = true; int outlen = 0; for (int i = 0; i < len; ++i, ++outlen) { const char c = inputPtr[i]; if (c == '%' && i + 2 < len) { int a = inputPtr[++i]; int b = inputPtr[++i]; if (a >= '0' && a <= '9') a -= '0'; else if (a >= 'a' && a <= 'f') a = a - 'a' + 10; else if (a >= 'A' && a <= 'F') a = a - 'A' + 10; if (b >= '0' && b <= '9') b -= '0'; else if (b >= 'a' && b <= 'f') b = b - 'a' + 10; else if (b >= 'A' && b <= 'F') b = b - 'A' + 10; *data++ = char((a << 4) | b); skipUtf8 = false; } else if (c == '+') { *data++ = ' '; } else { *data++ = c; } } if (skipUtf8) { path = QString::fromLatin1(rawPath, outlen); } else { path = QString::fromUtf8(rawPath, outlen); } } #include "moc_enginerequest.cpp" <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/network_login_observer.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/login/base_login_display_host.h" #include "chrome/browser/chromeos/options/network_config_view.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/dialog_style.h" #include "chrome/browser/ui/views/window.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace chromeos { NetworkLoginObserver::NetworkLoginObserver(NetworkLibrary* netlib) { netlib->AddNetworkManagerObserver(this); } NetworkLoginObserver::~NetworkLoginObserver() { CrosLibrary::Get()->GetNetworkLibrary()->RemoveNetworkManagerObserver(this); } void NetworkLoginObserver::CreateModalPopup(views::WidgetDelegate* view) { #if defined(USE_AURA) // TODO(saintlou): This needs to be done for Aura. NOTIMPLEMENTED(); #else Browser* browser = BrowserList::GetLastActive(); if (browser && !browser->is_type_tabbed()) { browser = BrowserList::FindTabbedBrowser(browser->profile(), true); } if (browser) { views::Widget* window = browser::CreateViewsWindow( browser->window()->GetNativeHandle(), view, STYLE_GENERIC); window->SetAlwaysOnTop(true); window->Show(); } else { // Browser not found, so we should be in login/oobe screen. views::Widget* window = browser::CreateViewsWindow( BaseLoginDisplayHost::default_host()->GetNativeWindow(), view, STYLE_GENERIC); window->SetAlwaysOnTop(true); window->Show(); } #endif } void NetworkLoginObserver::OnNetworkManagerChanged(NetworkLibrary* cros) { const WifiNetworkVector& wifi_networks = cros->wifi_networks(); const VirtualNetworkVector& virtual_networks = cros->virtual_networks(); // Check to see if we have any newly failed wifi network. for (WifiNetworkVector::const_iterator it = wifi_networks.begin(); it != wifi_networks.end(); it++) { WifiNetwork* wifi = *it; if (wifi->notify_failure()) { // Display login dialog again for bad_passphrase and bad_wepkey errors. // Always re-display the login dialog for encrypted networks that were // added and failed to connect for any reason. if (wifi->error() == ERROR_BAD_PASSPHRASE || wifi->error() == ERROR_BAD_WEPKEY || (wifi->encrypted() && wifi->added())) { CreateModalPopup(new NetworkConfigView(wifi)); return; // Only support one failure per notification. } } } // Check to see if we have any newly failed virtual network. for (VirtualNetworkVector::const_iterator it = virtual_networks.begin(); it != virtual_networks.end(); it++) { VirtualNetwork* vpn = *it; if (vpn->notify_failure()) { // Display login dialog for any error or newly added network. if (vpn->error() != ERROR_NO_ERROR || vpn->added()) { CreateModalPopup(new NetworkConfigView(vpn)); return; // Only support one failure per notification. } } } } } // namespace chromeos <commit_msg>Remove NOTIMPLEMENTED for Aura in NetworkLoginObserver::CreateModalPopup.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/network_login_observer.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/login/base_login_display_host.h" #include "chrome/browser/chromeos/options/network_config_view.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/dialog_style.h" #include "chrome/browser/ui/views/window.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace chromeos { NetworkLoginObserver::NetworkLoginObserver(NetworkLibrary* netlib) { netlib->AddNetworkManagerObserver(this); } NetworkLoginObserver::~NetworkLoginObserver() { CrosLibrary::Get()->GetNetworkLibrary()->RemoveNetworkManagerObserver(this); } void NetworkLoginObserver::CreateModalPopup(views::WidgetDelegate* view) { Browser* browser = BrowserList::GetLastActive(); if (browser && !browser->is_type_tabbed()) { browser = BrowserList::FindTabbedBrowser(browser->profile(), true); } if (browser) { views::Widget* window = browser::CreateViewsWindow( browser->window()->GetNativeHandle(), view, STYLE_GENERIC); window->SetAlwaysOnTop(true); window->Show(); } else { // Browser not found, so we should be in login/oobe screen. views::Widget* window = browser::CreateViewsWindow( BaseLoginDisplayHost::default_host()->GetNativeWindow(), view, STYLE_GENERIC); window->SetAlwaysOnTop(true); window->Show(); } } void NetworkLoginObserver::OnNetworkManagerChanged(NetworkLibrary* cros) { const WifiNetworkVector& wifi_networks = cros->wifi_networks(); const VirtualNetworkVector& virtual_networks = cros->virtual_networks(); // Check to see if we have any newly failed wifi network. for (WifiNetworkVector::const_iterator it = wifi_networks.begin(); it != wifi_networks.end(); it++) { WifiNetwork* wifi = *it; if (wifi->notify_failure()) { // Display login dialog again for bad_passphrase and bad_wepkey errors. // Always re-display the login dialog for encrypted networks that were // added and failed to connect for any reason. if (wifi->error() == ERROR_BAD_PASSPHRASE || wifi->error() == ERROR_BAD_WEPKEY || (wifi->encrypted() && wifi->added())) { CreateModalPopup(new NetworkConfigView(wifi)); return; // Only support one failure per notification. } } } // Check to see if we have any newly failed virtual network. for (VirtualNetworkVector::const_iterator it = virtual_networks.begin(); it != virtual_networks.end(); it++) { VirtualNetwork* vpn = *it; if (vpn->notify_failure()) { // Display login dialog for any error or newly added network. if (vpn->error() != ERROR_NO_ERROR || vpn->added()) { CreateModalPopup(new NetworkConfigView(vpn)); return; // Only support one failure per notification. } } } } } // namespace chromeos <|endoftext|>
<commit_before>#include "registered_app.h" #include "registration.h" FXDEFMAP(registered_app) registered_app_map[]={ FXMAPFUNC(SEL_COMMAND, registered_app::ID_REGISTER_MARK, registered_app::on_registration_mark), FXMAPFUNC(SEL_COMMAND, registered_app::ID_REGISTER, registered_app::on_registration_enter), FXMAPFUNC(SEL_COMMAND, registered_app::ID_REGISTER_ASK, registered_app::on_registration_ask), }; // Object implementation FXIMPLEMENT(registered_app, FXApp, registered_app_map,ARRAYNUMBER(registered_app_map)); registered_app::registered_app(const FXString& name,const FXString& vendor) : FXApp(name, vendor), m_reg_count(0), m_registered(false) { } void registered_app::create() { FXApp::create(); check_registration(); } void registered_app::check_registration() { FXRegistry& reg = this->reg(); const char *user_name = reg.readStringEntry("Registration", "user", "no user"); const char *user_email = reg.readStringEntry("Registration", "email", NULL); const char *key = reg.readStringEntry("Registration", "key", NULL); if (!user_name || !user_email || !key) return; const int ver = REGISTRATION_VERSION; m_registered = registration_check (user_name, user_email, ver, key); } long registered_app::on_registration_mark(FXObject*,FXSelector,void*) { if (m_registered) return 0; m_reg_count ++; if (m_reg_count >= reg_count_limit) { show_registration_dialog(); m_reg_count = 0; return 1; } return 0; } long registered_app::on_registration_ask(FXObject*,FXSelector,void*) { if (m_registered) show_registration_message(); else show_registration_dialog(); return 1; } long registered_app::on_registration_enter(FXObject*,FXSelector,void*) { FXString user_name = m_user_name_entry->getText(); FXString user_email = m_user_email_entry->getText(); FXString key = m_key_entry->getText(); bool is_valid = registration_check (user_name.text(), user_email.text(), REGISTRATION_VERSION, key.text()); if (is_valid) { FXRegistry& reg = this->reg(); reg.writeStringEntry("Registration", "user", user_name.text()); reg.writeStringEntry("Registration", "email", user_email.text()); reg.writeStringEntry("Registration", "key", key.text()); reg.write(); FXMessageBox::information(this, MBOX_OK, "Regress Pro Registration", "Congratulation you have successfully registered\n" "Regress Pro for Windows, version %d.%d.%d.\n\n" "We would like to remember your that Regress Pro is Free Software.\n" "By registering your copy you support its development.\n" "Thank you very much.", VERSION_MAJOR,VERSION_MINOR,VERSION_PATCH); m_registered = true; m_dialog->handle(this, FXSEL(SEL_COMMAND, FXDialogBox::ID_ACCEPT), NULL); } else { FXMessageBox::warning(this, MBOX_OK, "Regress Pro Registration", "The Registration code is not correct"); } return 1; } void registered_app::show_registration_dialog() { m_dialog = new FXDialogBox(this, "Regress Pro registration", DECOR_TITLE|DECOR_BORDER,0,0,0,0, 0,0,0,0, 0,0); FXVerticalFrame* side=new FXVerticalFrame(m_dialog,LAYOUT_SIDE_RIGHT|LAYOUT_FILL_X|LAYOUT_FILL_Y,0,0,0,0, 10,10,10,10, 0,0); new FXLabel(side,"R e g r e s s P r o",NULL,JUSTIFY_LEFT|ICON_BEFORE_TEXT|LAYOUT_FILL_X); new FXHorizontalSeparator(side,SEPARATOR_LINE|LAYOUT_FILL_X); new FXLabel(side,FXString("\nPlease register your copy of Regress Pro for Windows.\n"),NULL,JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(side,FXStringFormat("Product Release Tag : %03i\n", REGISTRATION_VERSION),NULL,JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXMatrix *mat = new FXMatrix(side, 2, LAYOUT_FILL_X|LAYOUT_FILL_Y|MATRIX_BY_COLUMNS, 0, 0, 0, 0, DEFAULT_SPACING, DEFAULT_SPACING, DEFAULT_SPACING, DEFAULT_SPACING, 1, 1); new FXLabel(mat, "User name"); m_user_name_entry = new FXTextField(mat, 36); new FXLabel(mat, "User email"); m_user_email_entry = new FXTextField(mat, 36); new FXLabel(mat, "Key"); m_key_entry = new FXTextField(mat, 36); FXHorizontalFrame *bfrm = new FXHorizontalFrame(side, LAYOUT_SIDE_RIGHT|LAYOUT_FILL_X,0,0,0,0, 10,10,10,10, 0,0); new FXButton(bfrm,"Cancel",NULL,m_dialog,FXDialogBox::ID_CANCEL,FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT,0,0,0,0,32,32,2,2); FXButton *button = new FXButton(bfrm,"&Register",NULL,this,registered_app::ID_REGISTER,BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT,0,0,0,0,32,32,2,2); button->setFocus(); m_dialog->execute(PLACEMENT_OWNER); } void registered_app::show_registration_message() { FXDialogBox dlg(this, "Regress Pro registration", DECOR_TITLE|DECOR_BORDER,0,0,0,0, 0,0,0,0, 0,0); FXVerticalFrame* side=new FXVerticalFrame(&dlg,LAYOUT_SIDE_RIGHT|LAYOUT_FILL_X|LAYOUT_FILL_Y,0,0,0,0, 10,10,10,10, 0,0); new FXLabel(side,"R e g r e s s P r o",NULL,JUSTIFY_LEFT|ICON_BEFORE_TEXT|LAYOUT_FILL_X); new FXHorizontalSeparator(side,SEPARATOR_LINE|LAYOUT_FILL_X); new FXLabel(side,FXString("\nThis copy of Regress Pro is registered to:\n"),NULL,JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXMatrix *mat = new FXMatrix(side, 2, LAYOUT_FILL_X|LAYOUT_FILL_Y|MATRIX_BY_COLUMNS, 0, 0, 0, 0, DEFAULT_SPACING, DEFAULT_SPACING, DEFAULT_SPACING, DEFAULT_SPACING, 1, 1); FXRegistry& reg = this->reg(); const char *user_name = reg.readStringEntry("Registration", "user", "no user"); const char *user_email = reg.readStringEntry("Registration", "email", NULL); const char *key = reg.readStringEntry("Registration", "key", NULL); new FXLabel(mat, "user name:"); new FXLabel(mat, user_name, 0); new FXLabel(mat, "email:"); new FXLabel(mat, user_email); new FXLabel(mat, "Key:"); new FXLabel(mat, key); new FXLabel(side,FXStringFormat("Product Release Tag : %03i\n", REGISTRATION_VERSION),NULL,JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXHorizontalFrame *bfrm = new FXHorizontalFrame(side, LAYOUT_SIDE_RIGHT|LAYOUT_FILL_X,0,0,0,0, 10,10,10,10, 0,0); FXButton *button = new FXButton(bfrm,"&Ok",NULL,&dlg,FXDialogBox::ID_ACCEPT,BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT,0,0,0,0,32,32,2,2); button->setFocus(); dlg.execute(PLACEMENT_OWNER); } <commit_msg>Added basic user's registration informations check<commit_after>#include "registered_app.h" #include "registration.h" FXDEFMAP(registered_app) registered_app_map[]={ FXMAPFUNC(SEL_COMMAND, registered_app::ID_REGISTER_MARK, registered_app::on_registration_mark), FXMAPFUNC(SEL_COMMAND, registered_app::ID_REGISTER, registered_app::on_registration_enter), FXMAPFUNC(SEL_COMMAND, registered_app::ID_REGISTER_ASK, registered_app::on_registration_ask), }; // Object implementation FXIMPLEMENT(registered_app, FXApp, registered_app_map,ARRAYNUMBER(registered_app_map)); registered_app::registered_app(const FXString& name,const FXString& vendor) : FXApp(name, vendor), m_reg_count(0), m_registered(false) { } void registered_app::create() { FXApp::create(); check_registration(); } void registered_app::check_registration() { FXRegistry& reg = this->reg(); const char *user_name = reg.readStringEntry("Registration", "user", "no user"); const char *user_email = reg.readStringEntry("Registration", "email", NULL); const char *key = reg.readStringEntry("Registration", "key", NULL); if (!user_name || !user_email || !key) return; const int ver = REGISTRATION_VERSION; m_registered = registration_check (user_name, user_email, ver, key); } long registered_app::on_registration_mark(FXObject*,FXSelector,void*) { if (m_registered) return 0; m_reg_count ++; if (m_reg_count >= reg_count_limit) { show_registration_dialog(); m_reg_count = 0; return 1; } return 0; } long registered_app::on_registration_ask(FXObject*,FXSelector,void*) { if (m_registered) show_registration_message(); else show_registration_dialog(); return 1; } static bool user_email_is_correct(FXString& email, FXString& errmsg) { FXString name = email.before('@'), domain = email.after('@'); if (name.length() == 0) { if (email.find('@') < 0) errmsg = "does not contail the character '@'"; else errmsg = "missing name before '@'"; return false; } if (domain.length() == 0) { errmsg = "missing domain name after '@'"; return false; } return true; } long registered_app::on_registration_enter(FXObject*,FXSelector,void*) { FXString user_name = m_user_name_entry->getText(); FXString user_email = m_user_email_entry->getText(); FXString key = m_key_entry->getText(); if (user_name.length() < 8) { FXMessageBox::warning(this, MBOX_OK, "Regress Pro Registration", "User name should be at least 8 character long"); return 1; } FXString errmsg; if (! user_email_is_correct(user_email, errmsg)) { FXMessageBox::warning(this, MBOX_OK, "Regress Pro Registration", "Invalid email address: %s", errmsg.text()); return 1; } if (key.length() == 0) { FXMessageBox::warning(this, MBOX_OK, "Regress Pro Registration", "Please provide a non-empty registration key"); return 1; } bool is_valid = registration_check (user_name.text(), user_email.text(), REGISTRATION_VERSION, key.text()); if (is_valid) { FXRegistry& reg = this->reg(); reg.writeStringEntry("Registration", "user", user_name.text()); reg.writeStringEntry("Registration", "email", user_email.text()); reg.writeStringEntry("Registration", "key", key.text()); reg.write(); FXMessageBox::information(this, MBOX_OK, "Regress Pro Registration", "Congratulation you have successfully registered\n" "Regress Pro for Windows, version %d.%d.%d.\n\n" "We would like to remember your that Regress Pro is Free Software.\n" "By registering your copy you support its development.\n" "Thank you very much.", VERSION_MAJOR,VERSION_MINOR,VERSION_PATCH); m_registered = true; m_dialog->handle(this, FXSEL(SEL_COMMAND, FXDialogBox::ID_ACCEPT), NULL); } else { FXMessageBox::warning(this, MBOX_OK, "Regress Pro Registration", "The Registration code is not correct"); } return 1; } void registered_app::show_registration_dialog() { m_dialog = new FXDialogBox(this, "Regress Pro registration", DECOR_TITLE|DECOR_BORDER,0,0,0,0, 0,0,0,0, 0,0); FXVerticalFrame* side=new FXVerticalFrame(m_dialog,LAYOUT_SIDE_RIGHT|LAYOUT_FILL_X|LAYOUT_FILL_Y,0,0,0,0, 10,10,10,10, 0,0); new FXLabel(side,"R e g r e s s P r o",NULL,JUSTIFY_LEFT|ICON_BEFORE_TEXT|LAYOUT_FILL_X); new FXHorizontalSeparator(side,SEPARATOR_LINE|LAYOUT_FILL_X); new FXLabel(side,FXString("\nPlease register your copy of Regress Pro for Windows.\n"),NULL,JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(side,FXStringFormat("Product Release Tag : %03i\n", REGISTRATION_VERSION),NULL,JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXMatrix *mat = new FXMatrix(side, 2, LAYOUT_FILL_X|LAYOUT_FILL_Y|MATRIX_BY_COLUMNS, 0, 0, 0, 0, DEFAULT_SPACING, DEFAULT_SPACING, DEFAULT_SPACING, DEFAULT_SPACING, 1, 1); new FXLabel(mat, "User name"); m_user_name_entry = new FXTextField(mat, 36); new FXLabel(mat, "User email"); m_user_email_entry = new FXTextField(mat, 36); new FXLabel(mat, "Key"); m_key_entry = new FXTextField(mat, 36); FXHorizontalFrame *bfrm = new FXHorizontalFrame(side, LAYOUT_SIDE_RIGHT|LAYOUT_FILL_X,0,0,0,0, 10,10,10,10, 0,0); new FXButton(bfrm,"Cancel",NULL,m_dialog,FXDialogBox::ID_CANCEL,FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT,0,0,0,0,32,32,2,2); FXButton *button = new FXButton(bfrm,"&Register",NULL,this,registered_app::ID_REGISTER,BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT,0,0,0,0,32,32,2,2); button->setFocus(); m_dialog->execute(PLACEMENT_OWNER); } void registered_app::show_registration_message() { FXDialogBox dlg(this, "Regress Pro registration", DECOR_TITLE|DECOR_BORDER,0,0,0,0, 0,0,0,0, 0,0); FXVerticalFrame* side=new FXVerticalFrame(&dlg,LAYOUT_SIDE_RIGHT|LAYOUT_FILL_X|LAYOUT_FILL_Y,0,0,0,0, 10,10,10,10, 0,0); new FXLabel(side,"R e g r e s s P r o",NULL,JUSTIFY_LEFT|ICON_BEFORE_TEXT|LAYOUT_FILL_X); new FXHorizontalSeparator(side,SEPARATOR_LINE|LAYOUT_FILL_X); new FXLabel(side,FXString("\nThis copy of Regress Pro is registered to:\n"),NULL,JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXMatrix *mat = new FXMatrix(side, 2, LAYOUT_FILL_X|LAYOUT_FILL_Y|MATRIX_BY_COLUMNS, 0, 0, 0, 0, DEFAULT_SPACING, DEFAULT_SPACING, DEFAULT_SPACING, DEFAULT_SPACING, 1, 1); FXRegistry& reg = this->reg(); const char *user_name = reg.readStringEntry("Registration", "user", "no user"); const char *user_email = reg.readStringEntry("Registration", "email", NULL); const char *key = reg.readStringEntry("Registration", "key", NULL); new FXLabel(mat, "user name:"); new FXLabel(mat, user_name, 0); new FXLabel(mat, "email:"); new FXLabel(mat, user_email); new FXLabel(mat, "Key:"); new FXLabel(mat, key); new FXLabel(side,FXStringFormat("Product Release Tag : %03i\n", REGISTRATION_VERSION),NULL,JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXHorizontalFrame *bfrm = new FXHorizontalFrame(side, LAYOUT_SIDE_RIGHT|LAYOUT_FILL_X,0,0,0,0, 10,10,10,10, 0,0); FXButton *button = new FXButton(bfrm,"&Ok",NULL,&dlg,FXDialogBox::ID_ACCEPT,BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT,0,0,0,0,32,32,2,2); button->setFocus(); dlg.execute(PLACEMENT_OWNER); } <|endoftext|>
<commit_before>#include "process.hpp" #include <cstdlib> #include <unistd.h> #include <signal.h> #include <iostream> //TODO: remove using namespace std; //TODO: remove Process::Data::Data(): id(-1) {} Process::id_type Process::open(const std::string &command, const std::string &path) { if(open_stdin) stdin_fd=std::unique_ptr<fd_type>(new fd_type); if(read_stdout) stdout_fd=std::unique_ptr<fd_type>(new fd_type); if(read_stderr) stderr_fd=std::unique_ptr<fd_type>(new fd_type); int stdin_p[2], stdout_p[2], stderr_p[2]; if(stdin_fd && pipe(stdin_p)!=0) { close(stdin_p[0]); close(stdin_p[1]); return -1; } if(stdout_fd && pipe(stdout_p)!=0) { if(stdin_fd) close(stdin_p[0]); if(stdin_fd) close(stdin_p[1]); close(stdout_p[0]); close(stdout_p[1]); return -1; } if(stderr_fd && pipe(stderr_p)!=0) { if(stdin_fd) close(stdin_p[0]); if(stdin_fd) close(stdin_p[1]); if(stdout_fd) close(stdout_p[0]); if(stdout_fd) close(stdout_p[1]); close(stderr_p[0]); close(stderr_p[1]); return -1; } id_type pid = fork(); if (pid < 0) { if(stdin_fd) close(stdin_p[0]); if(stdin_fd) close(stdin_p[1]); if(stdout_fd) close(stdout_p[0]); if(stdout_fd) close(stdout_p[1]); if(stderr_fd) close(stderr_p[0]); if(stderr_fd) close(stderr_p[1]); return pid; } else if (pid == 0) { if(stdin_fd) close(stdin_p[1]); if(stdout_fd) close(stdout_p[0]); if(stderr_fd) close(stderr_p[0]); if(stdin_fd) dup2(stdin_p[0], 0); if(stdout_fd) dup2(stdout_p[1], 1); if(stderr_fd) dup2(stderr_p[1], 2); setpgid(0, 0); //TODO: See here on how to emulate tty for colors: http://stackoverflow.com/questions/1401002/trick-an-application-into-thinking-its-stdin-is-interactive-not-a-pipe //TODO: One solution is: echo "command;exit"|script -q /dev/null if(!path.empty()) { auto path_escaped=path; size_t pos=0; //Based on https://www.reddit.com/r/cpp/comments/3vpjqg/a_new_platform_independent_process_library_for_c11/cxsxyb7 while((pos=path_escaped.find('\"', pos))!=std::string::npos) { path_escaped.insert(pos, "\\"); pos+=2; } execl("/bin/sh", "sh", "-c", ("cd \""+path_escaped+"\" && "+command).c_str(), NULL); } else execl("/bin/sh", "sh", "-c", command.c_str(), NULL); _exit(EXIT_FAILURE); } if(stdin_fd) close(stdin_p[0]); if(stdout_fd) close(stdout_p[1]); if(stderr_fd) close(stderr_p[1]); if(stdin_fd) *stdin_fd = stdin_p[1]; if(stdout_fd) *stdout_fd = stdout_p[0]; if(stderr_fd) *stderr_fd = stderr_p[0]; closed=false; data.id=pid; return pid; } void Process::async_read() { if(data.id<=0) return; if(stdout_fd) { stdout_thread=std::thread([this](){ char buffer[buffer_size]; ssize_t n; while ((n=read(*stdout_fd, buffer, buffer_size)) > 0) read_stdout(buffer, static_cast<size_t>(n)); }); } if(stderr_fd) { stderr_thread=std::thread([this](){ char buffer[buffer_size]; ssize_t n; while ((n=read(*stderr_fd, buffer, buffer_size)) > 0) read_stderr(buffer, static_cast<size_t>(n)); }); } } int Process::get_exit_status() { if(data.id<=0) return -1; int exit_status; waitpid(data.id, &exit_status, 0); close_mutex.lock(); closed=true; close_mutex.unlock(); close_fds(); return exit_status; } void Process::close_fds() { if(stdout_thread.joinable()) stdout_thread.join(); if(stderr_thread.joinable()) stderr_thread.join(); if(stdin_fd) close_stdin(); if(stdout_fd) { close(*stdout_fd); stdout_fd.reset(); } if(stderr_fd) { close(*stderr_fd); stderr_fd.reset(); } } bool Process::write(const char *bytes, size_t n) { stdin_mutex.lock(); if(stdin_fd) { if(::write(*stdin_fd, bytes, n)>=0) { stdin_mutex.unlock(); return true; } else { stdin_mutex.unlock(); return false; } } stdin_mutex.unlock(); return false; } void Process::close_stdin() { stdin_mutex.lock(); if(stdin_fd) { close(*stdin_fd); stdin_fd.reset(); } stdin_mutex.unlock(); } void Process::kill(bool force) { close_mutex.lock(); if(data.id>0 && !closed) { if(force) ::kill(-data.id, SIGTERM); else ::kill(-data.id, SIGINT); } close_mutex.unlock(); } void Process::kill(id_type id, bool force) { if(id<=0) return; if(force) ::kill(-id, SIGTERM); else ::kill(-id, SIGINT); } <commit_msg>Now correctly closes file descriptors on unix-like systems<commit_after>#include "process.hpp" #include <cstdlib> #include <unistd.h> #include <signal.h> #include <iostream> //TODO: remove using namespace std; //TODO: remove Process::Data::Data(): id(-1) {} Process::id_type Process::open(const std::string &command, const std::string &path) { if(open_stdin) stdin_fd=std::unique_ptr<fd_type>(new fd_type); if(read_stdout) stdout_fd=std::unique_ptr<fd_type>(new fd_type); if(read_stderr) stderr_fd=std::unique_ptr<fd_type>(new fd_type); int stdin_p[2], stdout_p[2], stderr_p[2]; if(stdin_fd && pipe(stdin_p)!=0) { close(stdin_p[0]);close(stdin_p[1]); return -1; } if(stdout_fd && pipe(stdout_p)!=0) { if(stdin_fd) {close(stdin_p[0]);close(stdin_p[1]);} close(stdout_p[0]);close(stdout_p[1]); return -1; } if(stderr_fd && pipe(stderr_p)!=0) { if(stdin_fd) {close(stdin_p[0]);close(stdin_p[1]);} if(stdout_fd) {close(stdout_p[0]);close(stdout_p[1]);} close(stderr_p[0]);close(stderr_p[1]); return -1; } id_type pid = fork(); if (pid < 0) { if(stdin_fd) {close(stdin_p[0]);close(stdin_p[1]);} if(stdout_fd) {close(stdout_p[0]);close(stdout_p[1]);} if(stderr_fd) {close(stderr_p[0]);close(stderr_p[1]);} return pid; } else if (pid == 0) { if(stdin_fd) dup2(stdin_p[0], 0); if(stdout_fd) dup2(stdout_p[1], 1); if(stderr_fd) dup2(stderr_p[1], 2); if(stdin_fd) {close(stdin_p[0]);close(stdin_p[1]);} if(stdout_fd) {close(stdout_p[0]);close(stdout_p[1]);} if(stderr_fd) {close(stderr_p[0]);close(stderr_p[1]);} //Based on http://stackoverflow.com/a/899533/3808293 int fd_max=sysconf(_SC_OPEN_MAX); for(int fd=3;fd<fd_max;fd++) close(fd); setpgid(0, 0); //TODO: See here on how to emulate tty for colors: http://stackoverflow.com/questions/1401002/trick-an-application-into-thinking-its-stdin-is-interactive-not-a-pipe //TODO: One solution is: echo "command;exit"|script -q /dev/null if(!path.empty()) { auto path_escaped=path; size_t pos=0; //Based on https://www.reddit.com/r/cpp/comments/3vpjqg/a_new_platform_independent_process_library_for_c11/cxsxyb7 while((pos=path_escaped.find('\"', pos))!=std::string::npos) { path_escaped.insert(pos, "\\"); pos+=2; } execl("/bin/sh", "sh", "-c", ("cd \""+path_escaped+"\" && "+command).c_str(), NULL); } else execl("/bin/sh", "sh", "-c", command.c_str(), NULL); _exit(EXIT_FAILURE); } if(stdin_fd) close(stdin_p[0]); if(stdout_fd) close(stdout_p[1]); if(stderr_fd) close(stderr_p[1]); if(stdin_fd) *stdin_fd = stdin_p[1]; if(stdout_fd) *stdout_fd = stdout_p[0]; if(stderr_fd) *stderr_fd = stderr_p[0]; closed=false; data.id=pid; return pid; } void Process::async_read() { if(data.id<=0) return; if(stdout_fd) { stdout_thread=std::thread([this](){ char buffer[buffer_size]; ssize_t n; while ((n=read(*stdout_fd, buffer, buffer_size)) > 0) read_stdout(buffer, static_cast<size_t>(n)); }); } if(stderr_fd) { stderr_thread=std::thread([this](){ char buffer[buffer_size]; ssize_t n; while ((n=read(*stderr_fd, buffer, buffer_size)) > 0) read_stderr(buffer, static_cast<size_t>(n)); }); } } int Process::get_exit_status() { if(data.id<=0) return -1; int exit_status; waitpid(data.id, &exit_status, 0); close_mutex.lock(); closed=true; close_mutex.unlock(); close_fds(); return exit_status; } void Process::close_fds() { if(stdout_thread.joinable()) stdout_thread.join(); if(stderr_thread.joinable()) stderr_thread.join(); if(stdin_fd) close_stdin(); if(stdout_fd) { close(*stdout_fd); stdout_fd.reset(); } if(stderr_fd) { close(*stderr_fd); stderr_fd.reset(); } } bool Process::write(const char *bytes, size_t n) { stdin_mutex.lock(); if(stdin_fd) { if(::write(*stdin_fd, bytes, n)>=0) { stdin_mutex.unlock(); return true; } else { stdin_mutex.unlock(); return false; } } stdin_mutex.unlock(); return false; } void Process::close_stdin() { stdin_mutex.lock(); if(stdin_fd) { close(*stdin_fd); stdin_fd.reset(); } stdin_mutex.unlock(); } void Process::kill(bool force) { close_mutex.lock(); if(data.id>0 && !closed) { if(force) ::kill(-data.id, SIGTERM); else ::kill(-data.id, SIGINT); } close_mutex.unlock(); } void Process::kill(id_type id, bool force) { if(id<=0) return; if(force) ::kill(-id, SIGTERM); else ::kill(-id, SIGINT); } <|endoftext|>
<commit_before>#include "MultiSmoothCircleIC.h" #include "MooseRandom.h" template<> InputParameters validParams<MultiSmoothCircleIC>() { InputParameters params = validParams<SmoothCircleBaseIC>(); params.addRequiredParam<unsigned int>("numbub", "The number of bubbles to be placed on GB"); params.addRequiredParam<Real>("bubspac", "minimum spacing of bubbles, measured from center to center"); params.addParam<unsigned int>("rand_seed", 2000, "random seed"); params.addParam<unsigned int>("numtries", 1000, "The number of tries"); params.addRequiredParam<Real>("radius", "Mean radius value for the circels"); params.addParam<Real>("radius_variation", 0.0, "Plus or minus fraction of random variation in the bubble radius for uniform, standard deviation for normal"); MooseEnum rand_options("uniform normal none","none"); params.addParam<MooseEnum>("radius_variation_type", rand_options, "Type of distribution that random circle radii will follow"); return params; } MultiSmoothCircleIC::MultiSmoothCircleIC(const std::string & name, InputParameters parameters) : SmoothCircleBaseIC(name, parameters), _numbub(getParam<unsigned int>("numbub")), _bubspac(getParam<Real>("bubspac")), _numtries(getParam<unsigned int>("numtries")), _radius(getParam<Real>("radius")), _radius_variation(getParam<Real>("radius_variation")), _radius_variation_type(getParam<MooseEnum>("radius_variation_type")) { MooseRandom::seed(getParam<unsigned int>("rand_seed")); } void MultiSmoothCircleIC::initialSetup() { //Set up domain bounds with mesh tools for (unsigned int i = 0; i < LIBMESH_DIM; i++) { _bottom_left(i) = _mesh.getMinInDimension(i); _top_right(i) = _mesh.getMaxInDimension(i); } _range = _top_right - _bottom_left; _range.print(); switch (_radius_variation_type) { case 2: //No variation if (_radius_variation > 0.0) mooseError("If radius_variation > 0.0, you must pass in a radius_variation_type in MultiSmoothCircleIC"); break; } SmoothCircleBaseIC::initialSetup(); } void MultiSmoothCircleIC::computeCircleRadii() { _radii.resize(_numbub); for (unsigned int i = 0; i < _numbub; i++) { //Vary bubble radius switch (_radius_variation_type) { case 0: //Uniform distrubtion _radii[i] = _radius*(1.0 + (1.0 - 2.0*MooseRandom::rand())*_radius_variation); break; case 1: //Normal distribution _radii[i] = MooseRandom::randNormal(_radius,_radius_variation); break; case 2: //No variation _radii[i] = _radius; } if (_radii[i] < 0.0) _radii[i] = 0.0; } } void MultiSmoothCircleIC::computeCircleCenters() { _centers.resize(_numbub); for (unsigned int i = 0; i < _numbub; i++) { //Vary circle center positions unsigned int num_tries = 0; Real rr = 0.0; Point newcenter = 0.0; while (rr < _bubspac && num_tries < _numtries) { num_tries++; //Moose::out<<"num_tries: "<<num_tries<<std::endl; Real ran1 = MooseRandom::rand(); Real ran2 = MooseRandom::rand(); Real ran3 = MooseRandom::rand(); newcenter(0) = _bottom_left(0) + ran1*_range(0); newcenter(1) = _bottom_left(1) + ran2*_range(1); newcenter(2) = _bottom_left(2) + ran3*_range(2); for (unsigned int j = 0; j < i; j++) { if (j == 0) rr = _range.size(); Real tmp_rr = _mesh.minPeriodicDistance(_var.number(), _centers[j], newcenter); if (tmp_rr < rr) rr = tmp_rr; } if (i == 0) rr = _range.size(); } if (num_tries == _numtries) mooseError("Too many tries in MultiSmoothCircleIC"); _centers[i] = newcenter; } } <commit_msg>Removed print() from MultiSmoothCircleIC for #3962<commit_after>#include "MultiSmoothCircleIC.h" #include "MooseRandom.h" template<> InputParameters validParams<MultiSmoothCircleIC>() { InputParameters params = validParams<SmoothCircleBaseIC>(); params.addRequiredParam<unsigned int>("numbub", "The number of bubbles to be placed on GB"); params.addRequiredParam<Real>("bubspac", "minimum spacing of bubbles, measured from center to center"); params.addParam<unsigned int>("rand_seed", 2000, "random seed"); params.addParam<unsigned int>("numtries", 1000, "The number of tries"); params.addRequiredParam<Real>("radius", "Mean radius value for the circels"); params.addParam<Real>("radius_variation", 0.0, "Plus or minus fraction of random variation in the bubble radius for uniform, standard deviation for normal"); MooseEnum rand_options("uniform normal none","none"); params.addParam<MooseEnum>("radius_variation_type", rand_options, "Type of distribution that random circle radii will follow"); return params; } MultiSmoothCircleIC::MultiSmoothCircleIC(const std::string & name, InputParameters parameters) : SmoothCircleBaseIC(name, parameters), _numbub(getParam<unsigned int>("numbub")), _bubspac(getParam<Real>("bubspac")), _numtries(getParam<unsigned int>("numtries")), _radius(getParam<Real>("radius")), _radius_variation(getParam<Real>("radius_variation")), _radius_variation_type(getParam<MooseEnum>("radius_variation_type")) { MooseRandom::seed(getParam<unsigned int>("rand_seed")); } void MultiSmoothCircleIC::initialSetup() { //Set up domain bounds with mesh tools for (unsigned int i = 0; i < LIBMESH_DIM; i++) { _bottom_left(i) = _mesh.getMinInDimension(i); _top_right(i) = _mesh.getMaxInDimension(i); } _range = _top_right - _bottom_left; switch (_radius_variation_type) { case 2: //No variation if (_radius_variation > 0.0) mooseError("If radius_variation > 0.0, you must pass in a radius_variation_type in MultiSmoothCircleIC"); break; } SmoothCircleBaseIC::initialSetup(); } void MultiSmoothCircleIC::computeCircleRadii() { _radii.resize(_numbub); for (unsigned int i = 0; i < _numbub; i++) { //Vary bubble radius switch (_radius_variation_type) { case 0: //Uniform distrubtion _radii[i] = _radius*(1.0 + (1.0 - 2.0*MooseRandom::rand())*_radius_variation); break; case 1: //Normal distribution _radii[i] = MooseRandom::randNormal(_radius,_radius_variation); break; case 2: //No variation _radii[i] = _radius; } if (_radii[i] < 0.0) _radii[i] = 0.0; } } void MultiSmoothCircleIC::computeCircleCenters() { _centers.resize(_numbub); for (unsigned int i = 0; i < _numbub; i++) { //Vary circle center positions unsigned int num_tries = 0; Real rr = 0.0; Point newcenter = 0.0; while (rr < _bubspac && num_tries < _numtries) { num_tries++; //Moose::out<<"num_tries: "<<num_tries<<std::endl; Real ran1 = MooseRandom::rand(); Real ran2 = MooseRandom::rand(); Real ran3 = MooseRandom::rand(); newcenter(0) = _bottom_left(0) + ran1*_range(0); newcenter(1) = _bottom_left(1) + ran2*_range(1); newcenter(2) = _bottom_left(2) + ran3*_range(2); for (unsigned int j = 0; j < i; j++) { if (j == 0) rr = _range.size(); Real tmp_rr = _mesh.minPeriodicDistance(_var.number(), _centers[j], newcenter); if (tmp_rr < rr) rr = tmp_rr; } if (i == 0) rr = _range.size(); } if (num_tries == _numtries) mooseError("Too many tries in MultiSmoothCircleIC"); _centers[i] = newcenter; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. * */ #include "ThreadLocalSSLContextProvider.h" #include <unordered_map> #include <folly/Singleton.h> #include <folly/hash/Hash.h> #include <folly/io/async/SSLContext.h> #include <wangle/client/persistence/SharedMutexCacheLockGuard.h> #include <wangle/client/ssl/SSLSessionCacheData.h> #include <wangle/client/ssl/SSLSessionPersistentCache.h> #include <wangle/ssl/SSLCacheOptions.h> #include <wangle/ssl/SSLContextConfig.h> #include <wangle/ssl/SSLSessionCacheManager.h> #include <wangle/ssl/ServerSSLContext.h> #include <wangle/ssl/TLSTicketKeyManager.h> #include <wangle/ssl/TLSTicketKeySeeds.h> #include "mcrouter/lib/fbi/cpp/LogFailure.h" using folly::SSLContext; namespace facebook { namespace memcache { namespace { /* Sessions are valid for upto 24 hours */ constexpr size_t kSessionLifeTime = 86400; struct CertPaths { folly::StringPiece pemCertPath; folly::StringPiece pemKeyPath; folly::StringPiece pemCaPath; bool isClient; bool operator==(const CertPaths& other) const { return pemCertPath == other.pemCertPath && pemKeyPath == other.pemKeyPath && pemCaPath == other.pemCaPath && isClient == other.isClient; } }; struct ContextInfo { std::string pemCertPath; std::string pemKeyPath; std::string pemCaPath; std::shared_ptr<SSLContext> context; std::chrono::time_point<std::chrono::steady_clock> lastLoadTime; }; struct CertPathsHasher { size_t operator()(const CertPaths& paths) const { return folly::Hash()( paths.pemCertPath, paths.pemKeyPath, paths.pemCaPath, paths.isClient); } }; void logCertFailure( folly::StringPiece name, folly::StringPiece path, const std::exception& ex) { LOG_FAILURE( "SSLCert", failure::Category::kBadEnvironment, "Failed to load {} from \"{}\", ex: {}", name, path, ex.what()); } bool configureSSLContext( folly::SSLContext& sslContext, folly::StringPiece pemCertPath, folly::StringPiece pemKeyPath, folly::StringPiece pemCaPath) { // Load certificate. try { sslContext.loadCertificate(pemCertPath.begin()); } catch (const std::exception& ex) { logCertFailure("certificate", pemCertPath, ex); return false; } // Load private key. try { sslContext.loadPrivateKey(pemKeyPath.begin()); } catch (const std::exception& ex) { logCertFailure("private key", pemKeyPath, ex); return false; } // Load trusted certificates. try { sslContext.loadTrustedCertificates(pemCaPath.begin()); } catch (const std::exception& ex) { logCertFailure("trusted certificates", pemCaPath, ex); return false; } // Load client CA list. try { sslContext.loadClientCAList(pemCaPath.begin()); } catch (const std::exception& ex) { logCertFailure("client CA list", pemCaPath, ex); return false; } // Try to disable compression if possible to reduce CPU and memory usage. #ifdef SSL_OP_NO_COMPRESSION try { sslContext.setOptions(SSL_OP_NO_COMPRESSION); } catch (const std::runtime_error& ex) { LOG_FAILURE( "SSLCert", failure::Category::kSystemError, "Failed to apply SSL_OP_NO_COMPRESSION flag onto SSLContext " "with files: pemCertPath='{}', pemKeyPath='{}', pemCaPath='{}'", pemCertPath, pemKeyPath, pemCaPath); // We failed to disable compression, but the SSLContext itself is good to // use. } #endif return true; } using TicketCacheLayer = wangle::LRUPersistentCache< std::string, wangle::SSLSessionCacheData, folly::SharedMutex>; // a SSL session cache that keys off string class SSLTicketCache : public wangle::SSLSessionPersistentCacheBase<std::string> { public: explicit SSLTicketCache(std::shared_ptr<TicketCacheLayer> cache) : wangle::SSLSessionPersistentCacheBase<std::string>(std::move(cache)) {} protected: std::string getKey(const std::string& identity) const override { return identity; } }; // global thread safe ticket cache // TODO(jmswen) Try to come up with a cleaner approach here that doesn't require // leaking. folly::LeakySingleton<SSLTicketCache> ticketCache([] { // create cache layer of max size 100; auto cacheLayer = std::make_shared<TicketCacheLayer>(100); return new SSLTicketCache(std::move(cacheLayer)); }); std::shared_ptr<SSLContext> createServerSSLContext( folly::StringPiece pemCertPath, folly::StringPiece pemKeyPath, folly::StringPiece pemCaPath, folly::Optional<wangle::TLSTicketKeySeeds> ticketKeySeeds) { wangle::SSLContextConfig cfg; // don't need to set any certs on the cfg since the context is configured // in configureSSLContext; cfg.sessionTicketEnabled = true; cfg.sessionCacheEnabled = true; cfg.sessionContext = "async-server"; // we'll use our own internal session cache instead of openssl's wangle::SSLCacheOptions cacheOpts; cacheOpts.sslCacheTimeout = std::chrono::seconds(kSessionLifeTime); // defaults from wangle/acceptor/ServerSocketConfig.h cacheOpts.maxSSLCacheSize = 20480; cacheOpts.sslCacheFlushSize = 200; auto sslContext = std::make_shared<wangle::ServerSSLContext>(); if (!configureSSLContext(*sslContext, pemCertPath, pemKeyPath, pemCaPath)) { return nullptr; } #ifdef SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB // ServerSSLContext handles null sslContext->setupTicketManager(ticketKeySeeds.get_pointer(), cfg, nullptr); #endif sslContext->setupSessionCache( cfg, cacheOpts, nullptr, // external cache "async-server", // session context nullptr); // SSL Stats #ifdef SSL_CTRL_SET_MAX_SEND_FRAGMENT // reduce send fragment size SSL_CTX_set_max_send_fragment(sslContext->getSSLCtx(), 8000); #endif return sslContext; } std::shared_ptr<SSLContext> createClientSSLContext( folly::StringPiece pemCertPath, folly::StringPiece pemKeyPath, folly::StringPiece pemCaPath) { auto context = std::make_shared<ClientSSLContext>(ticketCache.get()); if (!configureSSLContext(*context, pemCertPath, pemKeyPath, pemCaPath)) { return nullptr; } return context; } } // anonymous std::shared_ptr<SSLContext> getSSLContext( folly::StringPiece pemCertPath, folly::StringPiece pemKeyPath, folly::StringPiece pemCaPath, folly::Optional<wangle::TLSTicketKeySeeds> ticketKeySeeds, bool clientContext) { static constexpr std::chrono::minutes kSslReloadInterval{30}; thread_local std::unordered_map<CertPaths, ContextInfo, CertPathsHasher> localContexts; CertPaths paths; paths.pemCertPath = pemCertPath; paths.pemKeyPath = pemKeyPath; paths.pemCaPath = pemCaPath; paths.isClient = clientContext; auto iter = localContexts.find(paths); if (localContexts.find(paths) == localContexts.end()) { // Copy strings. ContextInfo info; info.pemCertPath = pemCertPath.toString(); info.pemKeyPath = pemKeyPath.toString(); info.pemCaPath = pemCaPath.toString(); // Point all StringPiece's to our own strings. paths.pemCertPath = info.pemCertPath; paths.pemKeyPath = info.pemKeyPath; paths.pemCaPath = info.pemCaPath; iter = localContexts.insert(std::make_pair(paths, std::move(info))).first; } auto& contextInfo = iter->second; auto now = std::chrono::steady_clock::now(); if (contextInfo.context == nullptr || now - contextInfo.lastLoadTime > kSslReloadInterval) { auto updated = clientContext ? createClientSSLContext(pemCertPath, pemKeyPath, pemCaPath) : createServerSSLContext( pemCertPath, pemKeyPath, pemCaPath, std::move(ticketKeySeeds)); if (updated) { contextInfo.lastLoadTime = now; contextInfo.context = std::move(updated); } } return contextInfo.context; } } // memcache } // facebook <commit_msg>Set an EC Curve<commit_after>/* * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. * */ #include "ThreadLocalSSLContextProvider.h" #include <unordered_map> #include <folly/Singleton.h> #include <folly/hash/Hash.h> #include <folly/io/async/SSLContext.h> #include <wangle/client/persistence/SharedMutexCacheLockGuard.h> #include <wangle/client/ssl/SSLSessionCacheData.h> #include <wangle/client/ssl/SSLSessionPersistentCache.h> #include <wangle/ssl/SSLCacheOptions.h> #include <wangle/ssl/SSLContextConfig.h> #include <wangle/ssl/SSLSessionCacheManager.h> #include <wangle/ssl/ServerSSLContext.h> #include <wangle/ssl/TLSTicketKeyManager.h> #include <wangle/ssl/TLSTicketKeySeeds.h> #include "mcrouter/lib/fbi/cpp/LogFailure.h" using folly::SSLContext; namespace facebook { namespace memcache { namespace { /* Sessions are valid for upto 24 hours */ constexpr size_t kSessionLifeTime = 86400; struct CertPaths { folly::StringPiece pemCertPath; folly::StringPiece pemKeyPath; folly::StringPiece pemCaPath; bool isClient; bool operator==(const CertPaths& other) const { return pemCertPath == other.pemCertPath && pemKeyPath == other.pemKeyPath && pemCaPath == other.pemCaPath && isClient == other.isClient; } }; struct ContextInfo { std::string pemCertPath; std::string pemKeyPath; std::string pemCaPath; std::shared_ptr<SSLContext> context; std::chrono::time_point<std::chrono::steady_clock> lastLoadTime; }; struct CertPathsHasher { size_t operator()(const CertPaths& paths) const { return folly::Hash()( paths.pemCertPath, paths.pemKeyPath, paths.pemCaPath, paths.isClient); } }; void logCertFailure( folly::StringPiece name, folly::StringPiece path, const std::exception& ex) { LOG_FAILURE( "SSLCert", failure::Category::kBadEnvironment, "Failed to load {} from \"{}\", ex: {}", name, path, ex.what()); } bool configureSSLContext( folly::SSLContext& sslContext, folly::StringPiece pemCertPath, folly::StringPiece pemKeyPath, folly::StringPiece pemCaPath) { // Load certificate. try { sslContext.loadCertificate(pemCertPath.begin()); } catch (const std::exception& ex) { logCertFailure("certificate", pemCertPath, ex); return false; } // Load private key. try { sslContext.loadPrivateKey(pemKeyPath.begin()); } catch (const std::exception& ex) { logCertFailure("private key", pemKeyPath, ex); return false; } // Load trusted certificates. try { sslContext.loadTrustedCertificates(pemCaPath.begin()); } catch (const std::exception& ex) { logCertFailure("trusted certificates", pemCaPath, ex); return false; } // Load client CA list. try { sslContext.loadClientCAList(pemCaPath.begin()); } catch (const std::exception& ex) { logCertFailure("client CA list", pemCaPath, ex); return false; } // Try to disable compression if possible to reduce CPU and memory usage. #ifdef SSL_OP_NO_COMPRESSION try { sslContext.setOptions(SSL_OP_NO_COMPRESSION); } catch (const std::runtime_error& ex) { LOG_FAILURE( "SSLCert", failure::Category::kSystemError, "Failed to apply SSL_OP_NO_COMPRESSION flag onto SSLContext " "with files: pemCertPath='{}', pemKeyPath='{}', pemCaPath='{}'", pemCertPath, pemKeyPath, pemCaPath); // We failed to disable compression, but the SSLContext itself is good to // use. } #endif return true; } using TicketCacheLayer = wangle::LRUPersistentCache< std::string, wangle::SSLSessionCacheData, folly::SharedMutex>; // a SSL session cache that keys off string class SSLTicketCache : public wangle::SSLSessionPersistentCacheBase<std::string> { public: explicit SSLTicketCache(std::shared_ptr<TicketCacheLayer> cache) : wangle::SSLSessionPersistentCacheBase<std::string>(std::move(cache)) {} protected: std::string getKey(const std::string& identity) const override { return identity; } }; // global thread safe ticket cache // TODO(jmswen) Try to come up with a cleaner approach here that doesn't require // leaking. folly::LeakySingleton<SSLTicketCache> ticketCache([] { // create cache layer of max size 100; auto cacheLayer = std::make_shared<TicketCacheLayer>(100); return new SSLTicketCache(std::move(cacheLayer)); }); std::shared_ptr<SSLContext> createServerSSLContext( folly::StringPiece pemCertPath, folly::StringPiece pemKeyPath, folly::StringPiece pemCaPath, folly::Optional<wangle::TLSTicketKeySeeds> ticketKeySeeds) { wangle::SSLContextConfig cfg; // don't need to set any certs on the cfg since the context is configured // in configureSSLContext; cfg.sessionTicketEnabled = true; cfg.sessionCacheEnabled = true; cfg.sessionContext = "async-server"; // we'll use our own internal session cache instead of openssl's wangle::SSLCacheOptions cacheOpts; cacheOpts.sslCacheTimeout = std::chrono::seconds(kSessionLifeTime); // defaults from wangle/acceptor/ServerSocketConfig.h cacheOpts.maxSSLCacheSize = 20480; cacheOpts.sslCacheFlushSize = 200; auto sslContext = std::make_shared<wangle::ServerSSLContext>(); if (!configureSSLContext(*sslContext, pemCertPath, pemKeyPath, pemCaPath)) { return nullptr; } sslContext->setServerECCurve("prime256v1"); #ifdef SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB // ServerSSLContext handles null sslContext->setupTicketManager(ticketKeySeeds.get_pointer(), cfg, nullptr); #endif sslContext->setupSessionCache( cfg, cacheOpts, nullptr, // external cache "async-server", // session context nullptr); // SSL Stats #ifdef SSL_CTRL_SET_MAX_SEND_FRAGMENT // reduce send fragment size SSL_CTX_set_max_send_fragment(sslContext->getSSLCtx(), 8000); #endif return sslContext; } std::shared_ptr<SSLContext> createClientSSLContext( folly::StringPiece pemCertPath, folly::StringPiece pemKeyPath, folly::StringPiece pemCaPath) { auto context = std::make_shared<ClientSSLContext>(ticketCache.get()); if (!configureSSLContext(*context, pemCertPath, pemKeyPath, pemCaPath)) { return nullptr; } return context; } } // anonymous std::shared_ptr<SSLContext> getSSLContext( folly::StringPiece pemCertPath, folly::StringPiece pemKeyPath, folly::StringPiece pemCaPath, folly::Optional<wangle::TLSTicketKeySeeds> ticketKeySeeds, bool clientContext) { static constexpr std::chrono::minutes kSslReloadInterval{30}; thread_local std::unordered_map<CertPaths, ContextInfo, CertPathsHasher> localContexts; CertPaths paths; paths.pemCertPath = pemCertPath; paths.pemKeyPath = pemKeyPath; paths.pemCaPath = pemCaPath; paths.isClient = clientContext; auto iter = localContexts.find(paths); if (localContexts.find(paths) == localContexts.end()) { // Copy strings. ContextInfo info; info.pemCertPath = pemCertPath.toString(); info.pemKeyPath = pemKeyPath.toString(); info.pemCaPath = pemCaPath.toString(); // Point all StringPiece's to our own strings. paths.pemCertPath = info.pemCertPath; paths.pemKeyPath = info.pemKeyPath; paths.pemCaPath = info.pemCaPath; iter = localContexts.insert(std::make_pair(paths, std::move(info))).first; } auto& contextInfo = iter->second; auto now = std::chrono::steady_clock::now(); if (contextInfo.context == nullptr || now - contextInfo.lastLoadTime > kSslReloadInterval) { auto updated = clientContext ? createClientSSLContext(pemCertPath, pemKeyPath, pemCaPath) : createServerSSLContext( pemCertPath, pemKeyPath, pemCaPath, std::move(ticketKeySeeds)); if (updated) { contextInfo.lastLoadTime = now; contextInfo.context = std::move(updated); } } return contextInfo.context; } } // memcache } // facebook <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/tab_contents/tab_contents_container.h" #include <utility> #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/tab_contents/native_tab_contents_container.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "ui/base/accessibility/accessible_view_state.h" using content::NavigationController; using content::RenderViewHost; using content::WebContents; //////////////////////////////////////////////////////////////////////////////// // TabContentsContainer, public: TabContentsContainer::TabContentsContainer() : native_container_(NULL), web_contents_(NULL) { set_id(VIEW_ID_TAB_CONTAINER); } TabContentsContainer::~TabContentsContainer() { if (web_contents_) RemoveObservers(); } void TabContentsContainer::ChangeWebContents(WebContents* contents) { if (web_contents_) { native_container_->DetachContents(web_contents_); web_contents_->WasHidden(); RemoveObservers(); } web_contents_ = contents; // When detaching the last tab of the browser ChangeWebContents is invoked // with NULL. Don't attempt to do anything in that case. if (web_contents_) { native_container_->AttachContents(web_contents_); AddObservers(); } } content::WebContents* TabContentsContainer::web_contents() { return web_contents_; } void TabContentsContainer::WebContentsFocused(WebContents* contents) { native_container_->WebContentsFocused(contents); } void TabContentsContainer::SetFastResize(bool fast_resize) { native_container_->SetFastResize(fast_resize); } //////////////////////////////////////////////////////////////////////////////// // TabContentsContainer, content::NotificationObserver implementation: void TabContentsContainer::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED) { std::pair<RenderViewHost*, RenderViewHost*>* switched_details = content::Details<std::pair<RenderViewHost*, RenderViewHost*> >( details).ptr(); RenderViewHostChanged(switched_details->first, switched_details->second); } else if (type == content::NOTIFICATION_WEB_CONTENTS_DESTROYED) { TabContentsDestroyed(content::Source<WebContents>(source).ptr()); } else { NOTREACHED(); } } //////////////////////////////////////////////////////////////////////////////// // TabContentsContainer, View overrides: void TabContentsContainer::Layout() { if (native_container_) { gfx::Size view_size(native_container_->GetView()->size()); native_container_->GetView()->SetBounds(0, 0, width(), height()); // SetBounds does nothing if the bounds haven't changed. We need to force // layout if the bounds haven't changed, but fast resize has. if (view_size.width() == width() && view_size.height() == height() && native_container_->FastResizeAtLastLayout() && !native_container_->GetFastResize()) { native_container_->GetView()->Layout(); } } } void TabContentsContainer::GetAccessibleState(ui::AccessibleViewState* state) { state->role = ui::AccessibilityTypes::ROLE_WINDOW; } #if defined(HAVE_XINPUT2) bool TabContentsContainer::OnMousePressed(const views::MouseEvent& event) { DCHECK(web_contents_); if (event.flags() & (ui::EF_LEFT_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON | ui::EF_MIDDLE_MOUSE_BUTTON)) { return false; } // It is necessary to look at the native event to determine what special // button was pressed. views::NativeEvent native_event = event.native_event(); if (!native_event) return false; int button = 0; switch (native_event->type) { case ButtonPress: { button = native_event->xbutton.button; break; } case GenericEvent: { XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(native_event->xcookie.data); button = xievent->detail; break; } default: break; } switch (button) { case 8: web_contents_->GetController().GoBack(); return true; case 9: web_contents_->GetController().GoForward(); return true; } return false; } #endif void TabContentsContainer::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (is_add && child == this) { native_container_ = NativeTabContentsContainer::CreateNativeContainer(this); AddChildView(native_container_->GetView()); } } //////////////////////////////////////////////////////////////////////////////// // TabContentsContainer, private: void TabContentsContainer::AddObservers() { // TabContents can change their RenderViewHost and hence the HWND that is // shown and getting focused. We need to keep track of that so we install // the focus subclass on the shown HWND so we intercept focus change events. registrar_.Add( this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED, content::Source<NavigationController>(&web_contents_->GetController())); registrar_.Add( this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED, content::Source<WebContents>(web_contents_)); } void TabContentsContainer::RemoveObservers() { registrar_.RemoveAll(); } void TabContentsContainer::RenderViewHostChanged(RenderViewHost* old_host, RenderViewHost* new_host) { native_container_->RenderViewHostChanged(old_host, new_host); } void TabContentsContainer::TabContentsDestroyed(WebContents* contents) { // Sometimes, a TabContents is destroyed before we know about it. This allows // us to clean up our state in case this happens. DCHECK(contents == web_contents_); ChangeWebContents(NULL); } <commit_msg>RenderWidgetHost::WasHidden is called twice on each tab switch on Aura.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/tab_contents/tab_contents_container.h" #include <utility> #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/tab_contents/native_tab_contents_container.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "ui/base/accessibility/accessible_view_state.h" using content::NavigationController; using content::RenderViewHost; using content::WebContents; //////////////////////////////////////////////////////////////////////////////// // TabContentsContainer, public: TabContentsContainer::TabContentsContainer() : native_container_(NULL), web_contents_(NULL) { set_id(VIEW_ID_TAB_CONTAINER); } TabContentsContainer::~TabContentsContainer() { if (web_contents_) RemoveObservers(); } void TabContentsContainer::ChangeWebContents(WebContents* contents) { if (web_contents_) { native_container_->DetachContents(web_contents_); RemoveObservers(); } web_contents_ = contents; // When detaching the last tab of the browser ChangeWebContents is invoked // with NULL. Don't attempt to do anything in that case. if (web_contents_) { native_container_->AttachContents(web_contents_); AddObservers(); } } content::WebContents* TabContentsContainer::web_contents() { return web_contents_; } void TabContentsContainer::WebContentsFocused(WebContents* contents) { native_container_->WebContentsFocused(contents); } void TabContentsContainer::SetFastResize(bool fast_resize) { native_container_->SetFastResize(fast_resize); } //////////////////////////////////////////////////////////////////////////////// // TabContentsContainer, content::NotificationObserver implementation: void TabContentsContainer::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED) { std::pair<RenderViewHost*, RenderViewHost*>* switched_details = content::Details<std::pair<RenderViewHost*, RenderViewHost*> >( details).ptr(); RenderViewHostChanged(switched_details->first, switched_details->second); } else if (type == content::NOTIFICATION_WEB_CONTENTS_DESTROYED) { TabContentsDestroyed(content::Source<WebContents>(source).ptr()); } else { NOTREACHED(); } } //////////////////////////////////////////////////////////////////////////////// // TabContentsContainer, View overrides: void TabContentsContainer::Layout() { if (native_container_) { gfx::Size view_size(native_container_->GetView()->size()); native_container_->GetView()->SetBounds(0, 0, width(), height()); // SetBounds does nothing if the bounds haven't changed. We need to force // layout if the bounds haven't changed, but fast resize has. if (view_size.width() == width() && view_size.height() == height() && native_container_->FastResizeAtLastLayout() && !native_container_->GetFastResize()) { native_container_->GetView()->Layout(); } } } void TabContentsContainer::GetAccessibleState(ui::AccessibleViewState* state) { state->role = ui::AccessibilityTypes::ROLE_WINDOW; } #if defined(HAVE_XINPUT2) bool TabContentsContainer::OnMousePressed(const views::MouseEvent& event) { DCHECK(web_contents_); if (event.flags() & (ui::EF_LEFT_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON | ui::EF_MIDDLE_MOUSE_BUTTON)) { return false; } // It is necessary to look at the native event to determine what special // button was pressed. views::NativeEvent native_event = event.native_event(); if (!native_event) return false; int button = 0; switch (native_event->type) { case ButtonPress: { button = native_event->xbutton.button; break; } case GenericEvent: { XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(native_event->xcookie.data); button = xievent->detail; break; } default: break; } switch (button) { case 8: web_contents_->GetController().GoBack(); return true; case 9: web_contents_->GetController().GoForward(); return true; } return false; } #endif void TabContentsContainer::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (is_add && child == this) { native_container_ = NativeTabContentsContainer::CreateNativeContainer(this); AddChildView(native_container_->GetView()); } } //////////////////////////////////////////////////////////////////////////////// // TabContentsContainer, private: void TabContentsContainer::AddObservers() { // TabContents can change their RenderViewHost and hence the HWND that is // shown and getting focused. We need to keep track of that so we install // the focus subclass on the shown HWND so we intercept focus change events. registrar_.Add( this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED, content::Source<NavigationController>(&web_contents_->GetController())); registrar_.Add( this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED, content::Source<WebContents>(web_contents_)); } void TabContentsContainer::RemoveObservers() { registrar_.RemoveAll(); } void TabContentsContainer::RenderViewHostChanged(RenderViewHost* old_host, RenderViewHost* new_host) { native_container_->RenderViewHostChanged(old_host, new_host); } void TabContentsContainer::TabContentsDestroyed(WebContents* contents) { // Sometimes, a TabContents is destroyed before we know about it. This allows // us to clean up our state in case this happens. DCHECK(contents == web_contents_); ChangeWebContents(NULL); } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-2008, 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$ */ ///////////////////////////////////////////////////////////// // // AliAnalysisTaskSE for the reconstruction of heavy flavor // decays, using the class AliAnalysisVertexingHF. // // Author: A.Dainese, [email protected] ///////////////////////////////////////////////////////////// #include <TROOT.h> #include <TSystem.h> #include <TClonesArray.h> #include <TList.h> #include <TString.h> #include "AliVEvent.h" #include "AliAODEvent.h" #include "AliESDEvent.h" #include "AliAnalysisVertexingHF.h" #include "AliAnalysisTaskSE.h" #include "AliAnalysisManager.h" #include "AliAnalysisTaskSEVertexingHF.h" #include "AliESDUtils.h" #include "AliAODHFUtil.h" ClassImp(AliAnalysisTaskSEVertexingHF) //________________________________________________________________________ AliAnalysisTaskSEVertexingHF::AliAnalysisTaskSEVertexingHF(): AliAnalysisTaskSE(), fVHF(0), fListOfCuts(0), fDeltaAODFileName("AliAOD.VertexingHF.root"), fVerticesHFTClArr(0), fD0toKpiTClArr(0), fJPSItoEleTClArr(0), fCharm3ProngTClArr(0), fCharm4ProngTClArr(0), fDstarTClArr(0), fCascadesTClArr(0), fLikeSign2ProngTClArr(0), fLikeSign3ProngTClArr(0), fHFUtilInfo(0) { // Default constructor } //________________________________________________________________________ AliAnalysisTaskSEVertexingHF::AliAnalysisTaskSEVertexingHF(const char *name): AliAnalysisTaskSE(name), fVHF(0), fListOfCuts(0), fDeltaAODFileName("AliAOD.VertexingHF.root"), fVerticesHFTClArr(0), fD0toKpiTClArr(0), fJPSItoEleTClArr(0), fCharm3ProngTClArr(0), fCharm4ProngTClArr(0), fDstarTClArr(0), fCascadesTClArr(0), fLikeSign2ProngTClArr(0), fLikeSign3ProngTClArr(0), fHFUtilInfo(0) { // Standard constructor DefineOutput(1,TList::Class()); // analysis cuts } //________________________________________________________________________ AliAnalysisTaskSEVertexingHF::~AliAnalysisTaskSEVertexingHF() { // Destructor if(fListOfCuts) { delete fListOfCuts; fListOfCuts=NULL; } } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::Init() { // Initialization // Instanciates vHF and loads its parameters if(fDebug > 1) printf("AnalysisTaskSEVertexingHF::Init() \n"); if(gROOT->LoadMacro("ConfigVertexingHF.C")) { printf("AnalysisTaskSEVertexingHF::Init() \n Using $ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C\n"); gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C"); } fVHF = (AliAnalysisVertexingHF*)gROOT->ProcessLine("ConfigVertexingHF()"); fVHF->PrintStatus(); // write the objects AliRDHFCuts to a list to store in the output fListOfCuts = fVHF->FillListOfCuts(); PostData(1,fListOfCuts); AliAnalysisManager::GetAnalysisManager()->RegisterExtraFile(fDeltaAODFileName.Data()); return; } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::UserCreateOutputObjects() { // Create the output container // if(fDebug > 1) printf("AnalysisTaskSEVertexingHF::UserCreateOutPutData() \n"); // Support both the case when the AOD + deltaAOD are produced in an ESD // analysis or if the deltaAOD is produced on an analysis on AOD's. (A.G. 27/04/09) if(!AliAnalysisManager::GetAnalysisManager()->GetOutputEventHandler()) { Fatal("UserCreateOutputObjects", "This task needs an AOD handler"); return; } TString filename = fDeltaAODFileName; // When running on standard AOD to produce deltas, IsStandardAOD is never set, // If AODEvent is NULL, new branches have to be added to the new file(s) (A.G. 15/01/10) if(!IsStandardAOD() && AODEvent()) filename = ""; if(!fVHF) { printf("AnalysisTaskSEVertexingHF::UserCreateOutPutData() \n ERROR! no fvHF!\n"); return; } fVerticesHFTClArr = new TClonesArray("AliAODVertex", 0); fVerticesHFTClArr->SetName("VerticesHF"); AddAODBranch("TClonesArray", &fVerticesHFTClArr, filename); if(fVHF->GetD0toKpi()) { fD0toKpiTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0); fD0toKpiTClArr->SetName("D0toKpi"); AddAODBranch("TClonesArray", &fD0toKpiTClArr, filename); } if(fVHF->GetJPSItoEle()) { fJPSItoEleTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0); fJPSItoEleTClArr->SetName("JPSItoEle"); AddAODBranch("TClonesArray", &fJPSItoEleTClArr, filename); } if(fVHF->Get3Prong()) { fCharm3ProngTClArr = new TClonesArray("AliAODRecoDecayHF3Prong", 0); fCharm3ProngTClArr->SetName("Charm3Prong"); AddAODBranch("TClonesArray", &fCharm3ProngTClArr, filename); } if(fVHF->Get4Prong()) { fCharm4ProngTClArr = new TClonesArray("AliAODRecoDecayHF4Prong", 0); fCharm4ProngTClArr->SetName("Charm4Prong"); AddAODBranch("TClonesArray", &fCharm4ProngTClArr, filename); } if(fVHF->GetDstar()) { fDstarTClArr = new TClonesArray("AliAODRecoCascadeHF", 0); fDstarTClArr->SetName("Dstar"); AddAODBranch("TClonesArray", &fDstarTClArr, filename); } if(fVHF->GetCascades()){ fCascadesTClArr = new TClonesArray("AliAODRecoCascadeHF", 0); fCascadesTClArr->SetName("CascadesHF"); AddAODBranch("TClonesArray", &fCascadesTClArr, filename); } if(fVHF->GetLikeSign()) { fLikeSign2ProngTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0); fLikeSign2ProngTClArr->SetName("LikeSign2Prong"); AddAODBranch("TClonesArray", &fLikeSign2ProngTClArr, filename); } if(fVHF->GetLikeSign() && fVHF->Get3Prong()) { fLikeSign3ProngTClArr = new TClonesArray("AliAODRecoDecayHF3Prong", 0); fLikeSign3ProngTClArr->SetName("LikeSign3Prong"); AddAODBranch("TClonesArray", &fLikeSign3ProngTClArr, filename); } //---Way to pass information temporarily not available in AOD--- // no if() { fHFUtilInfo = new AliAODHFUtil("fHFUtilInfoC"); fHFUtilInfo->SetName("fHFUtilInfo"); AddAODBranch( "AliAODHFUtil", &fHFUtilInfo, filename); // } //-------------------------------------------------------------- return; } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::UserExec(Option_t */*option*/) { // Execute analysis for current event: // heavy flavor vertexing AliVEvent *event = dynamic_cast<AliVEvent*> (InputEvent()); // In case there is an AOD handler writing a standard AOD, use the AOD // event in memory rather than the input (ESD) event. (A.G. 27/04/09) if (AODEvent() && IsStandardAOD()) event = dynamic_cast<AliVEvent*> (AODEvent()); // heavy flavor vertexing fVHF->FindCandidates(event, fVerticesHFTClArr, fD0toKpiTClArr, fJPSItoEleTClArr, fCharm3ProngTClArr, fCharm4ProngTClArr, fDstarTClArr, fCascadesTClArr, fLikeSign2ProngTClArr, fLikeSign3ProngTClArr); //---Way to pass information temporarily not available in AOD--- AliESDEvent *eventE = dynamic_cast<AliESDEvent*> (InputEvent()); if(eventE) { Float_t *vChCorr = new Float_t[64]; Float_t dummy; AliESDUtils::GetCorrV0(eventE,dummy,NULL,vChCorr); fHFUtilInfo->SetVZERO( vChCorr ); delete [] vChCorr; } //-------------------------------------------------------------- return; } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::Terminate(Option_t */*option*/) { // Terminate analysis // if(fDebug > 1) printf("AnalysisTaskSEVertexingHF: Terminate() \n"); } <commit_msg>Fix (Andrei)<commit_after>/************************************************************************** * Copyright(c) 1998-2008, 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$ */ ///////////////////////////////////////////////////////////// // // AliAnalysisTaskSE for the reconstruction of heavy flavor // decays, using the class AliAnalysisVertexingHF. // // Author: A.Dainese, [email protected] ///////////////////////////////////////////////////////////// #include <TROOT.h> #include <TSystem.h> #include <TClonesArray.h> #include <TList.h> #include <TString.h> #include "AliVEvent.h" #include "AliAODEvent.h" #include "AliAODHandler.h" #include "AliESDEvent.h" #include "AliAnalysisVertexingHF.h" #include "AliAnalysisTaskSE.h" #include "AliAnalysisManager.h" #include "AliAnalysisTaskSEVertexingHF.h" #include "AliESDUtils.h" #include "AliAODHFUtil.h" ClassImp(AliAnalysisTaskSEVertexingHF) //________________________________________________________________________ AliAnalysisTaskSEVertexingHF::AliAnalysisTaskSEVertexingHF(): AliAnalysisTaskSE(), fVHF(0), fListOfCuts(0), fDeltaAODFileName("AliAOD.VertexingHF.root"), fVerticesHFTClArr(0), fD0toKpiTClArr(0), fJPSItoEleTClArr(0), fCharm3ProngTClArr(0), fCharm4ProngTClArr(0), fDstarTClArr(0), fCascadesTClArr(0), fLikeSign2ProngTClArr(0), fLikeSign3ProngTClArr(0), fHFUtilInfo(0) { // Default constructor } //________________________________________________________________________ AliAnalysisTaskSEVertexingHF::AliAnalysisTaskSEVertexingHF(const char *name): AliAnalysisTaskSE(name), fVHF(0), fListOfCuts(0), fDeltaAODFileName("AliAOD.VertexingHF.root"), fVerticesHFTClArr(0), fD0toKpiTClArr(0), fJPSItoEleTClArr(0), fCharm3ProngTClArr(0), fCharm4ProngTClArr(0), fDstarTClArr(0), fCascadesTClArr(0), fLikeSign2ProngTClArr(0), fLikeSign3ProngTClArr(0), fHFUtilInfo(0) { // Standard constructor DefineOutput(1,TList::Class()); // analysis cuts } //________________________________________________________________________ AliAnalysisTaskSEVertexingHF::~AliAnalysisTaskSEVertexingHF() { // Destructor if(fListOfCuts) { delete fListOfCuts; fListOfCuts=NULL; } } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::Init() { // Initialization // Instanciates vHF and loads its parameters if(fDebug > 1) printf("AnalysisTaskSEVertexingHF::Init() \n"); if(gROOT->LoadMacro("ConfigVertexingHF.C")) { printf("AnalysisTaskSEVertexingHF::Init() \n Using $ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C\n"); gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C"); } fVHF = (AliAnalysisVertexingHF*)gROOT->ProcessLine("ConfigVertexingHF()"); fVHF->PrintStatus(); // write the objects AliRDHFCuts to a list to store in the output fListOfCuts = fVHF->FillListOfCuts(); PostData(1,fListOfCuts); AliAnalysisManager::GetAnalysisManager()->RegisterExtraFile(fDeltaAODFileName.Data()); return; } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::UserCreateOutputObjects() { // Create the output container // if(fDebug > 1) printf("AnalysisTaskSEVertexingHF::UserCreateOutPutData() \n"); // Support both the case when the AOD + deltaAOD are produced in an ESD // analysis or if the deltaAOD is produced on an analysis on AOD's. (A.G. 27/04/09) if(!AliAnalysisManager::GetAnalysisManager()->GetOutputEventHandler()) { Fatal("UserCreateOutputObjects", "This task needs an AOD handler"); return; } TString filename = fDeltaAODFileName; // When running on standard AOD to produce deltas, IsStandardAOD is never set, // If AODEvent is NULL, new branches have to be added to the new file(s) (A.G. 15/01/10) if(!IsStandardAOD() && AODEvent()) filename = ""; if(!fVHF) { printf("AnalysisTaskSEVertexingHF::UserCreateOutPutData() \n ERROR! no fvHF!\n"); return; } fVerticesHFTClArr = new TClonesArray("AliAODVertex", 0); fVerticesHFTClArr->SetName("VerticesHF"); AddAODBranch("TClonesArray", &fVerticesHFTClArr, filename); if(fVHF->GetD0toKpi()) { fD0toKpiTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0); fD0toKpiTClArr->SetName("D0toKpi"); AddAODBranch("TClonesArray", &fD0toKpiTClArr, filename); } if(fVHF->GetJPSItoEle()) { fJPSItoEleTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0); fJPSItoEleTClArr->SetName("JPSItoEle"); AddAODBranch("TClonesArray", &fJPSItoEleTClArr, filename); } if(fVHF->Get3Prong()) { fCharm3ProngTClArr = new TClonesArray("AliAODRecoDecayHF3Prong", 0); fCharm3ProngTClArr->SetName("Charm3Prong"); AddAODBranch("TClonesArray", &fCharm3ProngTClArr, filename); } if(fVHF->Get4Prong()) { fCharm4ProngTClArr = new TClonesArray("AliAODRecoDecayHF4Prong", 0); fCharm4ProngTClArr->SetName("Charm4Prong"); AddAODBranch("TClonesArray", &fCharm4ProngTClArr, filename); } if(fVHF->GetDstar()) { fDstarTClArr = new TClonesArray("AliAODRecoCascadeHF", 0); fDstarTClArr->SetName("Dstar"); AddAODBranch("TClonesArray", &fDstarTClArr, filename); } if(fVHF->GetCascades()){ fCascadesTClArr = new TClonesArray("AliAODRecoCascadeHF", 0); fCascadesTClArr->SetName("CascadesHF"); AddAODBranch("TClonesArray", &fCascadesTClArr, filename); } if(fVHF->GetLikeSign()) { fLikeSign2ProngTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0); fLikeSign2ProngTClArr->SetName("LikeSign2Prong"); AddAODBranch("TClonesArray", &fLikeSign2ProngTClArr, filename); } if(fVHF->GetLikeSign() && fVHF->Get3Prong()) { fLikeSign3ProngTClArr = new TClonesArray("AliAODRecoDecayHF3Prong", 0); fLikeSign3ProngTClArr->SetName("LikeSign3Prong"); AddAODBranch("TClonesArray", &fLikeSign3ProngTClArr, filename); } //---Way to pass information temporarily not available in AOD--- // no if() { fHFUtilInfo = new AliAODHFUtil("fHFUtilInfoC"); fHFUtilInfo->SetName("fHFUtilInfo"); AddAODBranch( "AliAODHFUtil", &fHFUtilInfo, filename); // } //-------------------------------------------------------------- return; } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::UserExec(Option_t */*option*/) { // Execute analysis for current event: // heavy flavor vertexing AliVEvent *event = dynamic_cast<AliVEvent*> (InputEvent()); // In case there is an AOD handler writing a standard AOD, use the AOD // event in memory rather than the input (ESD) event. (A.G. 27/04/09) if (AODEvent() && IsStandardAOD()) event = dynamic_cast<AliVEvent*> (AODEvent()); if (dynamic_cast<AliAODEvent*>(event)) { AliAODHandler *aodhandler = dynamic_cast<AliAODHandler*>(AliAnalysisManager::GetAnalysisManager()->GetOutputEventHandler()); if (aodhandler) aodhandler->SetFillExtension(kTRUE); } // heavy flavor vertexing fVHF->FindCandidates(event, fVerticesHFTClArr, fD0toKpiTClArr, fJPSItoEleTClArr, fCharm3ProngTClArr, fCharm4ProngTClArr, fDstarTClArr, fCascadesTClArr, fLikeSign2ProngTClArr, fLikeSign3ProngTClArr); //---Way to pass information temporarily not available in AOD--- AliESDEvent *eventE = dynamic_cast<AliESDEvent*> (InputEvent()); if(eventE) { Float_t *vChCorr = new Float_t[64]; Float_t dummy; AliESDUtils::GetCorrV0(eventE,dummy,NULL,vChCorr); fHFUtilInfo->SetVZERO( vChCorr ); delete [] vChCorr; } //-------------------------------------------------------------- return; } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::Terminate(Option_t */*option*/) { // Terminate analysis // if(fDebug > 1) printf("AnalysisTaskSEVertexingHF: Terminate() \n"); } <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Node.h" #include "Engine.h" #include "SceneManager.h" #include "Layer.h" #include "Animator.h" #include "Camera.h" #include "Utils.h" #include "MathUtils.h" namespace ouzel { Node::Node() { } Node::~Node() { } void Node::visit(const Matrix4& parentTransform, bool parentTransformDirty) { if (_visible) { if (parentTransformDirty) { _parentTransform = parentTransform; _transformDirty = true; } bool dirty = _transformDirty; if (dirty) { calculateTransform(); } LayerPtr layer = _layer.lock(); // check if _parent is _layer bool isRoot = !_parent.owner_before(_layer) && !_layer.owner_before(_parent); if (_children.empty()) { if (layer && (_globalOrder || isRoot) && checkVisibility()) { layer->addToDrawQueue(std::static_pointer_cast<Node>(shared_from_this())); } } else { lock(); std::stable_sort(_children.begin(), _children.end(), [](const NodePtr& a, const NodePtr& b) { return a->getZ() > b->getZ(); }); auto i = _children.begin(); NodePtr node; for (; i != _children.end(); ++i) { node = *i; if (!node->_remove) { if (node->getZ() < 0.0f) { node->visit(_transform, dirty); } else { break; } } } if (layer && (_globalOrder || isRoot) && checkVisibility()) { layer->addToDrawQueue(std::static_pointer_cast<Node>(shared_from_this())); } for (; i != _children.end(); ++i) { if (!node->_remove) { node = *i; node->visit(_transform, dirty); } } unlock(); } } } void Node::process() { if (_children.empty()) { draw(); } else { lock(); auto i = _children.begin(); NodePtr node; for (; i != _children.end(); ++i) { node = *i; if (node->getZ() < 0.0f) { if (!node->isGlobalOrder() && node->isVisible() && node->checkVisibility()) { node->draw(); } } else { break; } } draw(); for (; i != _children.end(); ++i) { node = *i; if (!node->isGlobalOrder() && node->isVisible() && node->checkVisibility()) { node->draw(); } } unlock(); } } void Node::draw() { if (_transformDirty) { calculateTransform(); } } bool Node::addChild(const NodePtr& node) { if (NodeContainer::addChild(node)) { node->addToLayer(_layer); if (_transformDirty) { calculateTransform(); } else { node->updateTransform(_transform); } return true; } else { return false; } } bool Node::removeFromParent() { if (NodeContainerPtr parent = _parent.lock()) { parent->removeChild(std::static_pointer_cast<Node>(shared_from_this())); return true; } return false; } void Node::setZ(float z) { _z = z; // Currently z does not affect transformation //_localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Node::setGlobalOrder(bool globalOrder) { _globalOrder = globalOrder; } void Node::setPosition(const Vector2& position) { _position = position; _localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Node::setRotation(float rotation) { _rotation = rotation; _localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Node::setScale(const Vector2& scale) { _scale = scale; _localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Node::setOpacity(float opacity) { _opacity = clamp(opacity, 0.0f, 1.0f); } void Node::setFlipX(bool flipX) { _flipX = flipX; _localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Node::setFlipY(bool flipY) { _flipY = flipY; _localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Node::setVisible(bool visible) { _visible = visible; } void Node::addToLayer(const LayerWeakPtr& layer) { _layer = layer; if (LayerPtr layer = _layer.lock()) { for (const NodePtr& child : _children) { child->addToLayer(layer); } } } void Node::removeFromLayer() { for (const NodePtr& child : _children) { child->removeFromLayer(); } _layer.reset(); } bool Node::pointOn(const Vector2& position) const { return _boundingBox.containPoint(convertWorldToLocal(position)); } bool Node::rectangleOverlaps(const Rectangle& rectangle) const { Matrix4 inverse = getInverseTransform(); Vector3 corners[4] = { Vector3(rectangle.left(), rectangle.bottom(), 0.0f), Vector3(rectangle.right(), rectangle.bottom(), 0.0f), Vector3(rectangle.right(), rectangle.top(), 0.0f), Vector3(rectangle.left(), rectangle.top(), 0.0f) }; uint8_t inCorners = 0; for (Vector3& corner : corners) { inverse.transformPoint(corner); if (corner.x >= _boundingBox.min.x && corner.x <= _boundingBox.max.x && corner.y >= _boundingBox.min.y && corner.y <= _boundingBox.max.y) { return true; } if (corner.x < _boundingBox.min.x && corner.y < _boundingBox.min.y) inCorners |= 0x01; if (corner.x > _boundingBox.max.x && corner.y < _boundingBox.min.y) inCorners |= 0x02; if (corner.x > _boundingBox.max.x && corner.y > _boundingBox.max.y) inCorners |= 0x04; if (corner.x < _boundingBox.min.x && corner.y > _boundingBox.max.y) inCorners |= 0x08; } // bounding box is bigger than rectangle if (inCorners == 0x0F) { return true; } Vector2 boundingBoxCorners[4] = { Vector2(_boundingBox.min), Vector2(_boundingBox.max.x, _boundingBox.min.y), Vector2(_boundingBox.max), Vector2(_boundingBox.min.x, _boundingBox.max.y) }; for (uint32_t current = 0; current < 4; ++current) { uint32_t next = (current == 3) ? 0 : current + 1; if (linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), boundingBoxCorners[0], boundingBoxCorners[1]) || // left linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), boundingBoxCorners[1], boundingBoxCorners[2]) || // top linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), boundingBoxCorners[2], boundingBoxCorners[3]) || // right linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), boundingBoxCorners[3], boundingBoxCorners[0])) // bottom { return true; } } return false; } const Matrix4& Node::getTransform() const { if (_transformDirty) { calculateTransform(); } return _transform; } const Matrix4& Node::getInverseTransform() const { if (_transformDirty) { calculateTransform(); } if (_inverseTransformDirty) { calculateInverseTransform(); } return _inverseTransform; } void Node::updateTransform(const Matrix4& parentTransform) { _parentTransform = parentTransform; _transformDirty = _inverseTransformDirty = true; } Vector2 Node::convertWorldToLocal(const Vector2& position) const { Vector3 localPosition = position; const Matrix4& inverseTransform = getInverseTransform(); inverseTransform.transformPoint(localPosition); return Vector2(localPosition.x, localPosition.y); } Vector2 Node::convertLocalToWorld(const Vector2& position) const { Vector3 worldPosition = position; const Matrix4& transform = getTransform(); transform.transformPoint(worldPosition); return Vector2(worldPosition.x, worldPosition.y); } bool Node::checkVisibility() const { if (const LayerPtr& layer = _layer.lock()) { if (_boundingBox.isEmpty()) { return true; } return Engine::getInstance()->getRenderer()->checkVisibility(getTransform(), _boundingBox, layer->getCamera()); } return false; } void Node::animate(const AnimatorPtr& animator) { _currentAnimator = animator; if (_currentAnimator) { _currentAnimator->start(std::static_pointer_cast<Node>(shared_from_this())); } } void Node::stopAnimation() { if (_currentAnimator) { _currentAnimator->stop(); _currentAnimator.reset(); } } void Node::calculateLocalTransform() const { Matrix4 translation; translation.translate(Vector3(_position.x, _position.y, 0.0f)); Matrix4 rotation; rotation.rotate(Vector3(0.0f, 0.0f, -1.0f), _rotation); Vector3 realScale = Vector3(_scale.x * (_flipX ? -1.0f : 1.0f), _scale.y * (_flipY ? -1.0f : 1.0f), 1.0f); Matrix4 scale; scale.scale(realScale); _localTransform = translation * rotation * scale; _localTransformDirty = false; } void Node::calculateTransform() const { if (_localTransformDirty) { calculateLocalTransform(); } _transform = _parentTransform * _localTransform; _transformDirty = false; for (const NodePtr& child : _children) { child->updateTransform(_transform); } } void Node::calculateInverseTransform() const { if (_transformDirty) { calculateTransform(); } _inverseTransform = _transform; _inverseTransform.invert(); _inverseTransformDirty = false; } } <commit_msg>Improve local transform calculation<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Node.h" #include "Engine.h" #include "SceneManager.h" #include "Layer.h" #include "Animator.h" #include "Camera.h" #include "Utils.h" #include "MathUtils.h" namespace ouzel { Node::Node() { } Node::~Node() { } void Node::visit(const Matrix4& parentTransform, bool parentTransformDirty) { if (_visible) { if (parentTransformDirty) { _parentTransform = parentTransform; _transformDirty = true; } bool dirty = _transformDirty; if (dirty) { calculateTransform(); } LayerPtr layer = _layer.lock(); // check if _parent is _layer bool isRoot = !_parent.owner_before(_layer) && !_layer.owner_before(_parent); if (_children.empty()) { if (layer && (_globalOrder || isRoot) && checkVisibility()) { layer->addToDrawQueue(std::static_pointer_cast<Node>(shared_from_this())); } } else { lock(); std::stable_sort(_children.begin(), _children.end(), [](const NodePtr& a, const NodePtr& b) { return a->getZ() > b->getZ(); }); auto i = _children.begin(); NodePtr node; for (; i != _children.end(); ++i) { node = *i; if (!node->_remove) { if (node->getZ() < 0.0f) { node->visit(_transform, dirty); } else { break; } } } if (layer && (_globalOrder || isRoot) && checkVisibility()) { layer->addToDrawQueue(std::static_pointer_cast<Node>(shared_from_this())); } for (; i != _children.end(); ++i) { if (!node->_remove) { node = *i; node->visit(_transform, dirty); } } unlock(); } } } void Node::process() { if (_children.empty()) { draw(); } else { lock(); auto i = _children.begin(); NodePtr node; for (; i != _children.end(); ++i) { node = *i; if (node->getZ() < 0.0f) { if (!node->isGlobalOrder() && node->isVisible() && node->checkVisibility()) { node->draw(); } } else { break; } } draw(); for (; i != _children.end(); ++i) { node = *i; if (!node->isGlobalOrder() && node->isVisible() && node->checkVisibility()) { node->draw(); } } unlock(); } } void Node::draw() { if (_transformDirty) { calculateTransform(); } } bool Node::addChild(const NodePtr& node) { if (NodeContainer::addChild(node)) { node->addToLayer(_layer); if (_transformDirty) { calculateTransform(); } else { node->updateTransform(_transform); } return true; } else { return false; } } bool Node::removeFromParent() { if (NodeContainerPtr parent = _parent.lock()) { parent->removeChild(std::static_pointer_cast<Node>(shared_from_this())); return true; } return false; } void Node::setZ(float z) { _z = z; // Currently z does not affect transformation //_localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Node::setGlobalOrder(bool globalOrder) { _globalOrder = globalOrder; } void Node::setPosition(const Vector2& position) { _position = position; _localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Node::setRotation(float rotation) { _rotation = rotation; _localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Node::setScale(const Vector2& scale) { _scale = scale; _localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Node::setOpacity(float opacity) { _opacity = clamp(opacity, 0.0f, 1.0f); } void Node::setFlipX(bool flipX) { _flipX = flipX; _localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Node::setFlipY(bool flipY) { _flipY = flipY; _localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Node::setVisible(bool visible) { _visible = visible; } void Node::addToLayer(const LayerWeakPtr& layer) { _layer = layer; if (LayerPtr layer = _layer.lock()) { for (const NodePtr& child : _children) { child->addToLayer(layer); } } } void Node::removeFromLayer() { for (const NodePtr& child : _children) { child->removeFromLayer(); } _layer.reset(); } bool Node::pointOn(const Vector2& position) const { return _boundingBox.containPoint(convertWorldToLocal(position)); } bool Node::rectangleOverlaps(const Rectangle& rectangle) const { Matrix4 inverse = getInverseTransform(); Vector3 corners[4] = { Vector3(rectangle.left(), rectangle.bottom(), 0.0f), Vector3(rectangle.right(), rectangle.bottom(), 0.0f), Vector3(rectangle.right(), rectangle.top(), 0.0f), Vector3(rectangle.left(), rectangle.top(), 0.0f) }; uint8_t inCorners = 0; for (Vector3& corner : corners) { inverse.transformPoint(corner); if (corner.x >= _boundingBox.min.x && corner.x <= _boundingBox.max.x && corner.y >= _boundingBox.min.y && corner.y <= _boundingBox.max.y) { return true; } if (corner.x < _boundingBox.min.x && corner.y < _boundingBox.min.y) inCorners |= 0x01; if (corner.x > _boundingBox.max.x && corner.y < _boundingBox.min.y) inCorners |= 0x02; if (corner.x > _boundingBox.max.x && corner.y > _boundingBox.max.y) inCorners |= 0x04; if (corner.x < _boundingBox.min.x && corner.y > _boundingBox.max.y) inCorners |= 0x08; } // bounding box is bigger than rectangle if (inCorners == 0x0F) { return true; } Vector2 boundingBoxCorners[4] = { Vector2(_boundingBox.min), Vector2(_boundingBox.max.x, _boundingBox.min.y), Vector2(_boundingBox.max), Vector2(_boundingBox.min.x, _boundingBox.max.y) }; for (uint32_t current = 0; current < 4; ++current) { uint32_t next = (current == 3) ? 0 : current + 1; if (linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), boundingBoxCorners[0], boundingBoxCorners[1]) || // left linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), boundingBoxCorners[1], boundingBoxCorners[2]) || // top linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), boundingBoxCorners[2], boundingBoxCorners[3]) || // right linesIntersect(Vector2(corners[current].x, corners[current].y), Vector2(corners[next].x, corners[next].y), boundingBoxCorners[3], boundingBoxCorners[0])) // bottom { return true; } } return false; } const Matrix4& Node::getTransform() const { if (_transformDirty) { calculateTransform(); } return _transform; } const Matrix4& Node::getInverseTransform() const { if (_transformDirty) { calculateTransform(); } if (_inverseTransformDirty) { calculateInverseTransform(); } return _inverseTransform; } void Node::updateTransform(const Matrix4& parentTransform) { _parentTransform = parentTransform; _transformDirty = _inverseTransformDirty = true; } Vector2 Node::convertWorldToLocal(const Vector2& position) const { Vector3 localPosition = position; const Matrix4& inverseTransform = getInverseTransform(); inverseTransform.transformPoint(localPosition); return Vector2(localPosition.x, localPosition.y); } Vector2 Node::convertLocalToWorld(const Vector2& position) const { Vector3 worldPosition = position; const Matrix4& transform = getTransform(); transform.transformPoint(worldPosition); return Vector2(worldPosition.x, worldPosition.y); } bool Node::checkVisibility() const { if (const LayerPtr& layer = _layer.lock()) { if (_boundingBox.isEmpty()) { return true; } return Engine::getInstance()->getRenderer()->checkVisibility(getTransform(), _boundingBox, layer->getCamera()); } return false; } void Node::animate(const AnimatorPtr& animator) { _currentAnimator = animator; if (_currentAnimator) { _currentAnimator->start(std::static_pointer_cast<Node>(shared_from_this())); } } void Node::stopAnimation() { if (_currentAnimator) { _currentAnimator->stop(); _currentAnimator.reset(); } } void Node::calculateLocalTransform() const { _localTransform = Matrix4::IDENTITY; _localTransform.translate(Vector3(_position.x, _position.y, 0.0f)); _localTransform.rotateZ(TAU - _rotation); Vector3 scale = Vector3(_scale.x * (_flipX ? -1.0f : 1.0f), _scale.y * (_flipY ? -1.0f : 1.0f), 1.0f); _localTransform.scale(scale); _localTransformDirty = false; } void Node::calculateTransform() const { if (_localTransformDirty) { calculateLocalTransform(); } _transform = _parentTransform * _localTransform; _transformDirty = false; for (const NodePtr& child : _children) { child->updateTransform(_transform); } } void Node::calculateInverseTransform() const { if (_transformDirty) { calculateTransform(); } _inverseTransform = _transform; _inverseTransform.invert(); _inverseTransformDirty = false; } } <|endoftext|>
<commit_before>// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "GetActiveElementCommandHandler.h" #include "errorcodes.h" #include "../Browser.h" #include "../Element.h" #include "../IECommandExecutor.h" namespace webdriver { GetActiveElementCommandHandler::GetActiveElementCommandHandler(void) { } GetActiveElementCommandHandler::~GetActiveElementCommandHandler(void) { } void GetActiveElementCommandHandler::ExecuteInternal( const IECommandExecutor& executor, const ParametersMap& command_parameters, Response* response) { BrowserHandle browser_wrapper; int status_code = executor.GetCurrentBrowser(&browser_wrapper); if (status_code != WD_SUCCESS) { response->SetErrorResponse(ERROR_NO_SUCH_WINDOW, "Unable to get browser"); return; } CComPtr<IHTMLDocument2> doc; browser_wrapper->GetDocument(&doc); if (!doc) { response->SetErrorResponse(ERROR_NO_SUCH_WINDOW, "Document is not found"); return; } CComPtr<IHTMLElement> element(NULL); HRESULT hr = doc->get_activeElement(&element); if (FAILED(hr)) { // For some contentEditable frames, the <body> element will be the // active element. However, to properly have focus, we must explicitly // set focus to the element. CComPtr<IHTMLBodyElement> body_element; HRESULT body_hr = element->QueryInterface<IHTMLBodyElement>(&body_element); if (body_element) { CComPtr<IHTMLElement2> body_element2; body_element->QueryInterface<IHTMLElement2>(&body_element2); body_element2->focus(); } } // If we don't have an element at this point, we should return a // null result, as that's what document.activeElement() returns. if (!element) { response->SetSuccessResponse(Json::Value::null); return; } if (element) { IECommandExecutor& mutable_executor = const_cast<IECommandExecutor&>(executor); ElementHandle element_wrapper; mutable_executor.AddManagedElement(element, &element_wrapper); response->SetSuccessResponse(element_wrapper->ConvertToJson()); } else { response->SetErrorResponse(ERROR_NO_SUCH_ELEMENT, "An unexpected error occurred getting the active element"); } } } // namespace webdriver <commit_msg>Updating get active element command in IE to handle missing body element (W3C compliance)<commit_after>// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "GetActiveElementCommandHandler.h" #include "errorcodes.h" #include "../Browser.h" #include "../Element.h" #include "../IECommandExecutor.h" namespace webdriver { GetActiveElementCommandHandler::GetActiveElementCommandHandler(void) { } GetActiveElementCommandHandler::~GetActiveElementCommandHandler(void) { } void GetActiveElementCommandHandler::ExecuteInternal( const IECommandExecutor& executor, const ParametersMap& command_parameters, Response* response) { BrowserHandle browser_wrapper; int status_code = executor.GetCurrentBrowser(&browser_wrapper); if (status_code != WD_SUCCESS) { response->SetErrorResponse(ERROR_NO_SUCH_WINDOW, "Unable to get browser"); return; } CComPtr<IHTMLDocument2> doc; browser_wrapper->GetDocument(&doc); if (!doc) { response->SetErrorResponse(ERROR_NO_SUCH_WINDOW, "Document is not found"); return; } CComPtr<IHTMLElement> element(NULL); HRESULT hr = doc->get_activeElement(&element); if (FAILED(hr)) { // For some contentEditable frames, the <body> element will be the // active element. However, to properly have focus, we must explicitly // set focus to the element. CComPtr<IHTMLBodyElement> body_element; HRESULT body_hr = element->QueryInterface<IHTMLBodyElement>(&body_element); if (body_element) { CComPtr<IHTMLElement2> body_element2; body_element->QueryInterface<IHTMLElement2>(&body_element2); body_element2->focus(); } } // If we don't have an element at this point, but the document // has a body element, we should return a null result, as that's // what document.activeElement() returns. However, if there is no // body element, throw no such element. if (!element) { CComPtr<IHTMLElement> body; hr = doc->get_body(&body); if (body) { response->SetSuccessResponse(Json::Value::null); } else { response->SetErrorResponse(ERROR_NO_SUCH_ELEMENT, "No active element found, and no body element present."); } return; } if (element) { IECommandExecutor& mutable_executor = const_cast<IECommandExecutor&>(executor); ElementHandle element_wrapper; mutable_executor.AddManagedElement(element, &element_wrapper); response->SetSuccessResponse(element_wrapper->ConvertToJson()); } else { response->SetErrorResponse(ERROR_NO_SUCH_ELEMENT, "An unexpected error occurred getting the active element"); } } } // namespace webdriver <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 noexpandtab: */ /******************************************************************************* * FShell 2 * Copyright 2009 Michael Tautschnig, [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /*! \file fshell2/main/fshell2.t.cpp * \brief TODO * * $Id$ * \author Michael Tautschnig <[email protected]> * \date Wed Apr 15 11:58:54 CEST 2009 */ #include <diagnostics/unittest.hpp> #include <fshell2/config/config.hpp> #include <fshell2/config/annotations.hpp> #include <fshell2/util/statistics.hpp> #include <fshell2/main/fshell2.hpp> #include <cerrno> #include <fstream> #ifdef __linux__ #include <unistd.h> #endif #ifdef __FreeBSD_kernel__ #include <unistd.h> #endif #ifdef __GNU__ #include <unistd.h> #endif #ifdef __MACH__ #include <unistd.h> #endif #include <fshell2/config/features.hpp> #ifdef FSHELL2_HAVE_LIBREADLINE # include <readline/readline.h> #else extern "C" { # include <linenoise/linenoise.h> } #define rl_instream linenoiseInStream #endif #include <util/config.h> #include <util/cmdline.h> #include <util/tempfile.h> #include <langapi/language_ui.h> #include <langapi/mode.h> #include <ansi-c/ansi_c_language.h> #define TEST_COMPONENT_NAME FShell2 #define TEST_COMPONENT_NAMESPACE fshell2 FSHELL2_NAMESPACE_BEGIN; /** @cond */ TEST_NAMESPACE_BEGIN; TEST_COMPONENT_TEST_NAMESPACE_BEGIN; /** @endcond */ using namespace ::diagnostics::unittest; //////////////////////////////////////////////////////////////////////////////// /** * @test A test of FShell2 * */ void test_single( Test_Data & data ) { ::register_language(new_ansi_c_language); ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l("FShell2", cmdline); ::optionst options; ::goto_functionst cfg; ::fshell2::FShell2 fshell(options, cfg); TEST_ASSERT(fshell.process_line(l, "QUIT")); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of FShell2 * */ void test_interactive( Test_Data & data ) { ::register_language(new_ansi_c_language); ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l("FShell2", cmdline); ::optionst options; ::goto_functionst cfg; ::std::ostringstream os; ::fshell2::FShell2 fshell(options, cfg); ::std::string const tempname_str(::get_temporary_file("tmp.query", "")); ::std::ofstream of(tempname_str.c_str()); TEST_CHECK(of.is_open()); of << "show sourcecode all" << ::std::endl << "#define bla blubb" << ::std::endl << "quit" << ::std::endl; of.close(); // open the input file FILE * in(fopen(tempname_str.c_str(), "r")); TEST_CHECK(0 == errno); // change the readline input to the file rl_instream = in; fshell.interactive(l); /* // print and check the output TEST_TRACE(os.str()); ::std::string data_name(::diagnostics::internal::to_string( "interactive_query_out_", sizeof(long) * 8, "bit")); TEST_ASSERT(data.compare(data_name, os.str())); */ // change back to stdin rl_instream = 0; fclose(in); ::unlink(tempname_str.c_str()); } ::std::string const tag1("Possibly feasible test goals:"); ::std::string const tag2("Test goals not fulfilled:"); ::std::string const tag3("Test cases removed by minimization:"); ::std::string const tag4("Test cases:"); #define QUERY(dataname, querystr) \ { \ ::fshell2::statistics::Statistics stats; \ TEST_ASSERT(!fshell.process_line(l, querystr, stats)); \ oss.str(""); \ stats.print(msg); \ ::std::istringstream is(oss.str()); \ oss.str(""); \ ::std::string line; \ while (!::std::getline(is, line).eof()) \ if (0 == line.compare(0, tag1.size(), tag1) || \ 0 == line.compare(0, tag2.size(), tag2) || \ 0 == line.compare(0, tag3.size(), tag3) || \ 0 == line.compare(0, tag4.size(), tag4)) \ oss << line << ::std::endl; \ TEST_ASSERT(data.compare(dataname ":" querystr, oss.str())); \ } DUMMY_FUNC void do_test_single2( Test_Data & data, bool const use_instrumentation ) { ::std::string const tempname_str(::get_temporary_file("tmp.src", ".c")); ::std::ofstream of(tempname_str.c_str()); TEST_CHECK(of.is_open()); of << "int main(int argc, char* argv[]) {" << ::std::endl << " int x=0;" << ::std::endl << "L0a: if (argc>2) {" << ::std::endl << " if (argc<27)" << ::std::endl << "L1: --x;" << ::std::endl << " else" << ::std::endl << " ++x;" << ::std::endl << " }" << ::std::endl << "L2:" << ::std::endl << " x--;" << ::std::endl << " x--;" << ::std::endl << " x--;" << ::std::endl << " x--;" << ::std::endl << " return 0;" << ::std::endl << "}" << ::std::endl; of.close(); ::register_language(new_ansi_c_language); ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l("FShell2", cmdline); ::optionst options; options.set_option("show-test-goals", true); options.set_option("statistics", true); options.set_option("use-instrumentation", use_instrumentation); options.set_option("sat-coverage-check", use_instrumentation); options.set_option("internal-coverage-check", !use_instrumentation); ::goto_functionst gf; ::fshell2::FShell2 fshell(options, gf); TEST_ASSERT(!fshell.process_line(l, ::diagnostics::internal::to_string("add sourcecode '", tempname_str, "'").c_str())); ::unlink(tempname_str.c_str()); ::std::ostringstream oss; ::stream_message_handlert mh(oss); ::messaget msg(mh); QUERY("query1", "cover edges(@basicblockentry)"); QUERY("query2", "cover edges(@basicblockentry) passing @func(main)*.@label(L1)->@label(L2).@func(main)*"); QUERY("query3", "cover edges(@basicblockentry) passing @func(main)*.@label(L2)->@label(L1).@func(main)*"); QUERY("query4", "cover edges(@conditionedge)->edges(@conditionedge)"); QUERY("query5", "cover edges(@basicblockentry). \"@func(main)*\" .edges(@basicblockentry)"); QUERY("query6", "cover paths(id,1)"); QUERY("query7", "cover @label(L2).{x>=0}"); QUERY("query8", "cover @label(L2).{x>0}"); QUERY("query9", "cover {x>0}.@label(L2)"); QUERY("query10", "cover nodes(id)"); QUERY("query11", "cover \"ID*\""); QUERY("query12", "cover ^ID$"); QUERY("query13", "cover \"ID*[email protected]*\" + \"ID*[email protected]*\""); QUERY("query14", "cover ({x==0}+{x!=0}).({argc<10}+{argc>=10}).ID.({x==0}+{x!=0}).({argc<10}+{argc>=10})"); QUERY("query15", "cover @label(L0a) -> @label(L1) + @label(L1) -> @label(L2)"); TEST_ASSERT(fshell.process_line(l, "QUIT")); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of FShell2 * */ void test_single2( Test_Data & data ) { do_test_single2(data, false); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of FShell2 * */ void test_single2_instrumentation( Test_Data & data ) { do_test_single2(data, true); } /** @cond */ TEST_COMPONENT_TEST_NAMESPACE_END; TEST_NAMESPACE_END; /** @endcond */ FSHELL2_NAMESPACE_END; TEST_SUITE_BEGIN; TEST_NORMAL_CASE( &test_single, LEVEL_PROD ); #ifndef __MINGW32__ // resetting rl_instream apparently doesn't work TEST_NORMAL_CASE( &test_interactive, LEVEL_PROD ); #endif TEST_NORMAL_CASE( &test_single2, LEVEL_PROD ); TEST_NORMAL_CASE( &test_single2_instrumentation, LEVEL_PROD ); TEST_SUITE_END; STREAM_TEST_SYSTEM_MAIN; <commit_msg>libedit on OS X makes test interactive - disable<commit_after>/* -*- Mode: C++; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 noexpandtab: */ /******************************************************************************* * FShell 2 * Copyright 2009 Michael Tautschnig, [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /*! \file fshell2/main/fshell2.t.cpp * \brief TODO * * $Id$ * \author Michael Tautschnig <[email protected]> * \date Wed Apr 15 11:58:54 CEST 2009 */ #include <diagnostics/unittest.hpp> #include <fshell2/config/config.hpp> #include <fshell2/config/annotations.hpp> #include <fshell2/util/statistics.hpp> #include <fshell2/main/fshell2.hpp> #include <cerrno> #include <fstream> #ifdef __linux__ #include <unistd.h> #endif #ifdef __FreeBSD_kernel__ #include <unistd.h> #endif #ifdef __GNU__ #include <unistd.h> #endif #ifdef __MACH__ #include <unistd.h> #endif #include <fshell2/config/features.hpp> #ifdef FSHELL2_HAVE_LIBREADLINE # include <readline/readline.h> #else extern "C" { # include <linenoise/linenoise.h> } #define rl_instream linenoiseInStream #endif #include <util/config.h> #include <util/cmdline.h> #include <util/tempfile.h> #include <langapi/language_ui.h> #include <langapi/mode.h> #include <ansi-c/ansi_c_language.h> #define TEST_COMPONENT_NAME FShell2 #define TEST_COMPONENT_NAMESPACE fshell2 FSHELL2_NAMESPACE_BEGIN; /** @cond */ TEST_NAMESPACE_BEGIN; TEST_COMPONENT_TEST_NAMESPACE_BEGIN; /** @endcond */ using namespace ::diagnostics::unittest; //////////////////////////////////////////////////////////////////////////////// /** * @test A test of FShell2 * */ void test_single( Test_Data & data ) { ::register_language(new_ansi_c_language); ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l("FShell2", cmdline); ::optionst options; ::goto_functionst cfg; ::fshell2::FShell2 fshell(options, cfg); TEST_ASSERT(fshell.process_line(l, "QUIT")); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of FShell2 * */ void test_interactive( Test_Data & data ) { ::register_language(new_ansi_c_language); ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l("FShell2", cmdline); ::optionst options; ::goto_functionst cfg; ::std::ostringstream os; ::fshell2::FShell2 fshell(options, cfg); ::std::string const tempname_str(::get_temporary_file("tmp.query", "")); ::std::ofstream of(tempname_str.c_str()); TEST_CHECK(of.is_open()); of << "show sourcecode all" << ::std::endl << "#define bla blubb" << ::std::endl << "quit" << ::std::endl; of.close(); // open the input file FILE * in(fopen(tempname_str.c_str(), "r")); TEST_CHECK(0 == errno); // change the readline input to the file rl_instream = in; fshell.interactive(l); /* // print and check the output TEST_TRACE(os.str()); ::std::string data_name(::diagnostics::internal::to_string( "interactive_query_out_", sizeof(long) * 8, "bit")); TEST_ASSERT(data.compare(data_name, os.str())); */ // change back to stdin rl_instream = 0; fclose(in); ::unlink(tempname_str.c_str()); } ::std::string const tag1("Possibly feasible test goals:"); ::std::string const tag2("Test goals not fulfilled:"); ::std::string const tag3("Test cases removed by minimization:"); ::std::string const tag4("Test cases:"); #define QUERY(dataname, querystr) \ { \ ::fshell2::statistics::Statistics stats; \ TEST_ASSERT(!fshell.process_line(l, querystr, stats)); \ oss.str(""); \ stats.print(msg); \ ::std::istringstream is(oss.str()); \ oss.str(""); \ ::std::string line; \ while (!::std::getline(is, line).eof()) \ if (0 == line.compare(0, tag1.size(), tag1) || \ 0 == line.compare(0, tag2.size(), tag2) || \ 0 == line.compare(0, tag3.size(), tag3) || \ 0 == line.compare(0, tag4.size(), tag4)) \ oss << line << ::std::endl; \ TEST_ASSERT(data.compare(dataname ":" querystr, oss.str())); \ } DUMMY_FUNC void do_test_single2( Test_Data & data, bool const use_instrumentation ) { ::std::string const tempname_str(::get_temporary_file("tmp.src", ".c")); ::std::ofstream of(tempname_str.c_str()); TEST_CHECK(of.is_open()); of << "int main(int argc, char* argv[]) {" << ::std::endl << " int x=0;" << ::std::endl << "L0a: if (argc>2) {" << ::std::endl << " if (argc<27)" << ::std::endl << "L1: --x;" << ::std::endl << " else" << ::std::endl << " ++x;" << ::std::endl << " }" << ::std::endl << "L2:" << ::std::endl << " x--;" << ::std::endl << " x--;" << ::std::endl << " x--;" << ::std::endl << " x--;" << ::std::endl << " return 0;" << ::std::endl << "}" << ::std::endl; of.close(); ::register_language(new_ansi_c_language); ::cmdlinet cmdline; ::config.set(cmdline); ::language_uit l("FShell2", cmdline); ::optionst options; options.set_option("show-test-goals", true); options.set_option("statistics", true); options.set_option("use-instrumentation", use_instrumentation); options.set_option("sat-coverage-check", use_instrumentation); options.set_option("internal-coverage-check", !use_instrumentation); ::goto_functionst gf; ::fshell2::FShell2 fshell(options, gf); TEST_ASSERT(!fshell.process_line(l, ::diagnostics::internal::to_string("add sourcecode '", tempname_str, "'").c_str())); ::unlink(tempname_str.c_str()); ::std::ostringstream oss; ::stream_message_handlert mh(oss); ::messaget msg(mh); QUERY("query1", "cover edges(@basicblockentry)"); QUERY("query2", "cover edges(@basicblockentry) passing @func(main)*.@label(L1)->@label(L2).@func(main)*"); QUERY("query3", "cover edges(@basicblockentry) passing @func(main)*.@label(L2)->@label(L1).@func(main)*"); QUERY("query4", "cover edges(@conditionedge)->edges(@conditionedge)"); QUERY("query5", "cover edges(@basicblockentry). \"@func(main)*\" .edges(@basicblockentry)"); QUERY("query6", "cover paths(id,1)"); QUERY("query7", "cover @label(L2).{x>=0}"); QUERY("query8", "cover @label(L2).{x>0}"); QUERY("query9", "cover {x>0}.@label(L2)"); QUERY("query10", "cover nodes(id)"); QUERY("query11", "cover \"ID*\""); QUERY("query12", "cover ^ID$"); QUERY("query13", "cover \"ID*[email protected]*\" + \"ID*[email protected]*\""); QUERY("query14", "cover ({x==0}+{x!=0}).({argc<10}+{argc>=10}).ID.({x==0}+{x!=0}).({argc<10}+{argc>=10})"); QUERY("query15", "cover @label(L0a) -> @label(L1) + @label(L1) -> @label(L2)"); TEST_ASSERT(fshell.process_line(l, "QUIT")); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of FShell2 * */ void test_single2( Test_Data & data ) { do_test_single2(data, false); } //////////////////////////////////////////////////////////////////////////////// /** * @test A test of FShell2 * */ void test_single2_instrumentation( Test_Data & data ) { do_test_single2(data, true); } /** @cond */ TEST_COMPONENT_TEST_NAMESPACE_END; TEST_NAMESPACE_END; /** @endcond */ FSHELL2_NAMESPACE_END; TEST_SUITE_BEGIN; TEST_NORMAL_CASE( &test_single, LEVEL_PROD ); #if !defined(__MINGW32__) && !defined(__MACH__) // resetting rl_instream apparently doesn't work TEST_NORMAL_CASE( &test_interactive, LEVEL_PROD ); #endif TEST_NORMAL_CASE( &test_single2, LEVEL_PROD ); TEST_NORMAL_CASE( &test_single2_instrumentation, LEVEL_PROD ); TEST_SUITE_END; STREAM_TEST_SYSTEM_MAIN; <|endoftext|>
<commit_before>//===-- llvm-dwarfdump.cpp - Debug info dumping utility for llvm ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that works like "dwarfdump". // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/Triple.h" #include "llvm/DebugInfo/DIContext.h" #include "llvm/DebugInfo/DWARF/DWARFContext.h" #include "llvm/Object/MachOUniversal.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Object/RelocVisitor.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cstring> #include <string> #include <system_error> using namespace llvm; using namespace object; static cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input object files or .dSYM bundles>"), cl::ZeroOrMore); static cl::opt<DIDumpType> DumpType( "debug-dump", cl::init(DIDT_All), cl::desc("Dump of debug sections:"), cl::values( clEnumValN(DIDT_All, "all", "Dump all debug sections"), clEnumValN(DIDT_Abbrev, "abbrev", ".debug_abbrev"), clEnumValN(DIDT_AbbrevDwo, "abbrev.dwo", ".debug_abbrev.dwo"), clEnumValN(DIDT_AppleNames, "apple_names", ".apple_names"), clEnumValN(DIDT_AppleTypes, "apple_types", ".apple_types"), clEnumValN(DIDT_AppleNamespaces, "apple_namespaces", ".apple_namespaces"), clEnumValN(DIDT_AppleObjC, "apple_objc", ".apple_objc"), clEnumValN(DIDT_Aranges, "aranges", ".debug_aranges"), clEnumValN(DIDT_Info, "info", ".debug_info"), clEnumValN(DIDT_InfoDwo, "info.dwo", ".debug_info.dwo"), clEnumValN(DIDT_Types, "types", ".debug_types"), clEnumValN(DIDT_TypesDwo, "types.dwo", ".debug_types.dwo"), clEnumValN(DIDT_Line, "line", ".debug_line"), clEnumValN(DIDT_LineDwo, "line.dwo", ".debug_line.dwo"), clEnumValN(DIDT_Loc, "loc", ".debug_loc"), clEnumValN(DIDT_LocDwo, "loc.dwo", ".debug_loc.dwo"), clEnumValN(DIDT_Frames, "frames", ".debug_frame"), clEnumValN(DIDT_Macro, "macro", ".debug_macinfo"), clEnumValN(DIDT_Ranges, "ranges", ".debug_ranges"), clEnumValN(DIDT_Pubnames, "pubnames", ".debug_pubnames"), clEnumValN(DIDT_Pubtypes, "pubtypes", ".debug_pubtypes"), clEnumValN(DIDT_GnuPubnames, "gnu_pubnames", ".debug_gnu_pubnames"), clEnumValN(DIDT_GnuPubtypes, "gnu_pubtypes", ".debug_gnu_pubtypes"), clEnumValN(DIDT_Str, "str", ".debug_str"), clEnumValN(DIDT_StrOffsets, "str_offsets", ".debug_str_offsets"), clEnumValN(DIDT_StrDwo, "str.dwo", ".debug_str.dwo"), clEnumValN(DIDT_StrOffsetsDwo, "str_offsets.dwo", ".debug_str_offsets.dwo"), clEnumValN(DIDT_CUIndex, "cu_index", ".debug_cu_index"), clEnumValN(DIDT_GdbIndex, "gdb_index", ".gdb_index"), clEnumValN(DIDT_TUIndex, "tu_index", ".debug_tu_index"))); static cl::opt<bool> SummarizeTypes("summarize-types", cl::desc("Abbreviate the description of type unit entries")); static cl::opt<bool> Verify("verify", cl::desc("Verify the DWARF debug info")); static cl::opt<bool> Quiet("quiet", cl::desc("Use with -verify to not emit to STDOUT.")); static cl::opt<bool> Brief("brief", cl::desc("Print fewer low-level details")); static void error(StringRef Filename, std::error_code EC) { if (!EC) return; errs() << Filename << ": " << EC.message() << "\n"; exit(1); } static void DumpObjectFile(ObjectFile &Obj, Twine Filename) { std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(Obj)); outs() << Filename.str() << ":\tfile format " << Obj.getFileFormatName() << "\n\n"; // Dump the complete DWARF structure. DIDumpOptions DumpOpts; DumpOpts.DumpType = DumpType; DumpOpts.SummarizeTypes = SummarizeTypes; DumpOpts.Brief = Brief; DICtx->dump(outs(), DumpOpts); } static void DumpInput(StringRef Filename) { ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr = MemoryBuffer::getFileOrSTDIN(Filename); error(Filename, BuffOrErr.getError()); std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get()); Expected<std::unique_ptr<Binary>> BinOrErr = object::createBinary(Buff->getMemBufferRef()); if (!BinOrErr) error(Filename, errorToErrorCode(BinOrErr.takeError())); if (auto *Obj = dyn_cast<ObjectFile>(BinOrErr->get())) DumpObjectFile(*Obj, Filename); else if (auto *Fat = dyn_cast<MachOUniversalBinary>(BinOrErr->get())) for (auto &ObjForArch : Fat->objects()) { auto MachOOrErr = ObjForArch.getAsObjectFile(); error(Filename, errorToErrorCode(MachOOrErr.takeError())); DumpObjectFile(**MachOOrErr, Filename + " (" + ObjForArch.getArchFlagName() + ")"); } } static bool VerifyObjectFile(ObjectFile &Obj, Twine Filename) { std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(Obj)); // Verify the DWARF and exit with non-zero exit status if verification // fails. raw_ostream &stream = Quiet ? nulls() : outs(); stream << "Verifying " << Filename.str() << ":\tfile format " << Obj.getFileFormatName() << "\n"; bool Result = DICtx->verify(stream, DumpType); if (Result) stream << "No errors.\n"; else stream << "Errors detected.\n"; return Result; } static bool VerifyInput(StringRef Filename) { ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr = MemoryBuffer::getFileOrSTDIN(Filename); error(Filename, BuffOrErr.getError()); std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get()); Expected<std::unique_ptr<Binary>> BinOrErr = object::createBinary(Buff->getMemBufferRef()); if (!BinOrErr) error(Filename, errorToErrorCode(BinOrErr.takeError())); bool Result = true; if (auto *Obj = dyn_cast<ObjectFile>(BinOrErr->get())) Result = VerifyObjectFile(*Obj, Filename); else if (auto *Fat = dyn_cast<MachOUniversalBinary>(BinOrErr->get())) for (auto &ObjForArch : Fat->objects()) { auto MachOOrErr = ObjForArch.getAsObjectFile(); error(Filename, errorToErrorCode(MachOOrErr.takeError())); if (!VerifyObjectFile(**MachOOrErr, Filename + " (" + ObjForArch.getArchFlagName() + ")")) Result = false; } return Result; } /// If the input path is a .dSYM bundle (as created by the dsymutil tool), /// replace it with individual entries for each of the object files inside the /// bundle otherwise return the input path. static std::vector<std::string> expandBundle(const std::string &InputPath) { std::vector<std::string> BundlePaths; SmallString<256> BundlePath(InputPath); // Manually open up the bundle to avoid introducing additional dependencies. if (sys::fs::is_directory(BundlePath) && sys::path::extension(BundlePath) == ".dSYM") { std::error_code EC; sys::path::append(BundlePath, "Contents", "Resources", "DWARF"); for (sys::fs::directory_iterator Dir(BundlePath, EC), DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { const std::string &Path = Dir->path(); sys::fs::file_status Status; EC = sys::fs::status(Path, Status); error(Path, EC); switch (Status.type()) { case sys::fs::file_type::regular_file: case sys::fs::file_type::symlink_file: case sys::fs::file_type::type_unknown: BundlePaths.push_back(Path); break; default: /*ignore*/; } } error(BundlePath, EC); } if (!BundlePaths.size()) BundlePaths.push_back(InputPath); return BundlePaths; } int main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(argv[0]); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm dwarf dumper\n"); // Defaults to a.out if no filenames specified. if (InputFilenames.size() == 0) InputFilenames.push_back("a.out"); // Expand any .dSYM bundles to the individual object files contained therein. std::vector<std::string> Objects; for (const auto &F : InputFilenames) { auto Objs = expandBundle(F); Objects.insert(Objects.end(), Objs.begin(), Objs.end()); } if (Verify) { // If we encountered errors during verify, exit with a non-zero exit status. if (!std::all_of(Objects.begin(), Objects.end(), VerifyInput)) exit(1); } else { std::for_each(Objects.begin(), Objects.end(), DumpInput); } return EXIT_SUCCESS; } <commit_msg>[DWARF] Added a blank line in llvm-dwarfdump to test commit access.<commit_after>//===-- llvm-dwarfdump.cpp - Debug info dumping utility for llvm ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that works like "dwarfdump". // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/Triple.h" #include "llvm/DebugInfo/DIContext.h" #include "llvm/DebugInfo/DWARF/DWARFContext.h" #include "llvm/Object/MachOUniversal.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Object/RelocVisitor.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cstring> #include <string> #include <system_error> using namespace llvm; using namespace object; static cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input object files or .dSYM bundles>"), cl::ZeroOrMore); static cl::opt<DIDumpType> DumpType( "debug-dump", cl::init(DIDT_All), cl::desc("Dump of debug sections:"), cl::values( clEnumValN(DIDT_All, "all", "Dump all debug sections"), clEnumValN(DIDT_Abbrev, "abbrev", ".debug_abbrev"), clEnumValN(DIDT_AbbrevDwo, "abbrev.dwo", ".debug_abbrev.dwo"), clEnumValN(DIDT_AppleNames, "apple_names", ".apple_names"), clEnumValN(DIDT_AppleTypes, "apple_types", ".apple_types"), clEnumValN(DIDT_AppleNamespaces, "apple_namespaces", ".apple_namespaces"), clEnumValN(DIDT_AppleObjC, "apple_objc", ".apple_objc"), clEnumValN(DIDT_Aranges, "aranges", ".debug_aranges"), clEnumValN(DIDT_Info, "info", ".debug_info"), clEnumValN(DIDT_InfoDwo, "info.dwo", ".debug_info.dwo"), clEnumValN(DIDT_Types, "types", ".debug_types"), clEnumValN(DIDT_TypesDwo, "types.dwo", ".debug_types.dwo"), clEnumValN(DIDT_Line, "line", ".debug_line"), clEnumValN(DIDT_LineDwo, "line.dwo", ".debug_line.dwo"), clEnumValN(DIDT_Loc, "loc", ".debug_loc"), clEnumValN(DIDT_LocDwo, "loc.dwo", ".debug_loc.dwo"), clEnumValN(DIDT_Frames, "frames", ".debug_frame"), clEnumValN(DIDT_Macro, "macro", ".debug_macinfo"), clEnumValN(DIDT_Ranges, "ranges", ".debug_ranges"), clEnumValN(DIDT_Pubnames, "pubnames", ".debug_pubnames"), clEnumValN(DIDT_Pubtypes, "pubtypes", ".debug_pubtypes"), clEnumValN(DIDT_GnuPubnames, "gnu_pubnames", ".debug_gnu_pubnames"), clEnumValN(DIDT_GnuPubtypes, "gnu_pubtypes", ".debug_gnu_pubtypes"), clEnumValN(DIDT_Str, "str", ".debug_str"), clEnumValN(DIDT_StrOffsets, "str_offsets", ".debug_str_offsets"), clEnumValN(DIDT_StrDwo, "str.dwo", ".debug_str.dwo"), clEnumValN(DIDT_StrOffsetsDwo, "str_offsets.dwo", ".debug_str_offsets.dwo"), clEnumValN(DIDT_CUIndex, "cu_index", ".debug_cu_index"), clEnumValN(DIDT_GdbIndex, "gdb_index", ".gdb_index"), clEnumValN(DIDT_TUIndex, "tu_index", ".debug_tu_index"))); static cl::opt<bool> SummarizeTypes("summarize-types", cl::desc("Abbreviate the description of type unit entries")); static cl::opt<bool> Verify("verify", cl::desc("Verify the DWARF debug info")); static cl::opt<bool> Quiet("quiet", cl::desc("Use with -verify to not emit to STDOUT.")); static cl::opt<bool> Brief("brief", cl::desc("Print fewer low-level details")); static void error(StringRef Filename, std::error_code EC) { if (!EC) return; errs() << Filename << ": " << EC.message() << "\n"; exit(1); } static void DumpObjectFile(ObjectFile &Obj, Twine Filename) { std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(Obj)); outs() << Filename.str() << ":\tfile format " << Obj.getFileFormatName() << "\n\n"; // Dump the complete DWARF structure. DIDumpOptions DumpOpts; DumpOpts.DumpType = DumpType; DumpOpts.SummarizeTypes = SummarizeTypes; DumpOpts.Brief = Brief; DICtx->dump(outs(), DumpOpts); } static void DumpInput(StringRef Filename) { ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr = MemoryBuffer::getFileOrSTDIN(Filename); error(Filename, BuffOrErr.getError()); std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get()); Expected<std::unique_ptr<Binary>> BinOrErr = object::createBinary(Buff->getMemBufferRef()); if (!BinOrErr) error(Filename, errorToErrorCode(BinOrErr.takeError())); if (auto *Obj = dyn_cast<ObjectFile>(BinOrErr->get())) DumpObjectFile(*Obj, Filename); else if (auto *Fat = dyn_cast<MachOUniversalBinary>(BinOrErr->get())) for (auto &ObjForArch : Fat->objects()) { auto MachOOrErr = ObjForArch.getAsObjectFile(); error(Filename, errorToErrorCode(MachOOrErr.takeError())); DumpObjectFile(**MachOOrErr, Filename + " (" + ObjForArch.getArchFlagName() + ")"); } } static bool VerifyObjectFile(ObjectFile &Obj, Twine Filename) { std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(Obj)); // Verify the DWARF and exit with non-zero exit status if verification // fails. raw_ostream &stream = Quiet ? nulls() : outs(); stream << "Verifying " << Filename.str() << ":\tfile format " << Obj.getFileFormatName() << "\n"; bool Result = DICtx->verify(stream, DumpType); if (Result) stream << "No errors.\n"; else stream << "Errors detected.\n"; return Result; } static bool VerifyInput(StringRef Filename) { ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr = MemoryBuffer::getFileOrSTDIN(Filename); error(Filename, BuffOrErr.getError()); std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get()); Expected<std::unique_ptr<Binary>> BinOrErr = object::createBinary(Buff->getMemBufferRef()); if (!BinOrErr) error(Filename, errorToErrorCode(BinOrErr.takeError())); bool Result = true; if (auto *Obj = dyn_cast<ObjectFile>(BinOrErr->get())) Result = VerifyObjectFile(*Obj, Filename); else if (auto *Fat = dyn_cast<MachOUniversalBinary>(BinOrErr->get())) for (auto &ObjForArch : Fat->objects()) { auto MachOOrErr = ObjForArch.getAsObjectFile(); error(Filename, errorToErrorCode(MachOOrErr.takeError())); if (!VerifyObjectFile(**MachOOrErr, Filename + " (" + ObjForArch.getArchFlagName() + ")")) Result = false; } return Result; } /// If the input path is a .dSYM bundle (as created by the dsymutil tool), /// replace it with individual entries for each of the object files inside the /// bundle otherwise return the input path. static std::vector<std::string> expandBundle(const std::string &InputPath) { std::vector<std::string> BundlePaths; SmallString<256> BundlePath(InputPath); // Manually open up the bundle to avoid introducing additional dependencies. if (sys::fs::is_directory(BundlePath) && sys::path::extension(BundlePath) == ".dSYM") { std::error_code EC; sys::path::append(BundlePath, "Contents", "Resources", "DWARF"); for (sys::fs::directory_iterator Dir(BundlePath, EC), DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { const std::string &Path = Dir->path(); sys::fs::file_status Status; EC = sys::fs::status(Path, Status); error(Path, EC); switch (Status.type()) { case sys::fs::file_type::regular_file: case sys::fs::file_type::symlink_file: case sys::fs::file_type::type_unknown: BundlePaths.push_back(Path); break; default: /*ignore*/; } } error(BundlePath, EC); } if (!BundlePaths.size()) BundlePaths.push_back(InputPath); return BundlePaths; } int main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(argv[0]); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm dwarf dumper\n"); // Defaults to a.out if no filenames specified. if (InputFilenames.size() == 0) InputFilenames.push_back("a.out"); // Expand any .dSYM bundles to the individual object files contained therein. std::vector<std::string> Objects; for (const auto &F : InputFilenames) { auto Objs = expandBundle(F); Objects.insert(Objects.end(), Objs.begin(), Objs.end()); } if (Verify) { // If we encountered errors during verify, exit with a non-zero exit status. if (!std::all_of(Objects.begin(), Objects.end(), VerifyInput)) exit(1); } else { std::for_each(Objects.begin(), Objects.end(), DumpInput); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* Copyright (C) 2012 cloudbase.io This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. 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; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "CBHelperSearchCondition.h" namespace Cloudbase { const std::string CBHelperSearchCondition::CBConditionOperator_ToString[] = { "", "$lt", "$lte", "$gt", "$gte", "$all", "$exists", "$mod", "$ne", "$in", "$nin", "$size", "$type", "$within", "$near" }; const std::string CBHelperSearchCondition::CBConditionLink_ToString[] = { "$and", "$or", "$nor" }; CBHelperSearchCondition::CBHelperSearchCondition() { this->baseInit(); } CBHelperSearchCondition::CBHelperSearchCondition(std::string field, std::string value, CBConditionOperator op) { this->baseInit(); this->field_ = field; this->value_ = value; this->conditionOperator_ = op; } CBHelperSearchCondition::CBHelperSearchCondition(double SWLat, double SWLng, double NELat, double NELng) { this->baseInit(); this->field_ = "cb_location"; this->value_ = "[ [ "; this->value_ += SWLat; this->value_ += ", "; this->value_ += SWLng; this->value_ += "], [ "; this->value_ += NELat; this->value_ += ", "; this->value_ += NELng; this->value_ += "] ] "; this->conditionOperator_ = CBOperatorWithin; } CBHelperSearchCondition::CBHelperSearchCondition(double lat, double lng, double maxDistance) { this->baseInit(); this->field_ = "cb_location"; this->value_ = "{ \"$near\" : [ "; this->value_ += lat; this->value_ += ", "; this->value_ += lng; this->value_ += "], \"$maxDistance\" : "; this->value_ += maxDistance; this->value_ += " }"; this->conditionOperator_ = CBOperatorNear; } void CBHelperSearchCondition::setConditionLink(CBConditionLink link) { this->contidionLink_ = link; } void CBHelperSearchCondition::addCondition(CBHelperSearchCondition* newCond) { this->conditions_.insert(this->conditions_.begin(), newCond); } void CBHelperSearchCondition::baseInit() { this->field_ = ""; this->value_ = ""; this->limit = -1; this->commandType = CBDataAggregationMatch; } void CBHelperSearchCondition::addSortField(std::string fieldName, CBSortDirection dir) { std::string sortField = "{ \""; sortField += fieldName + "\" : "; sortField += dir + " }"; this->sortFields_.insert(this->sortFields_.begin(), sortField); } std::string CBHelperSearchCondition::serializeAggregateConditions() { return this->serialize(this, true); } std::string CBHelperSearchCondition::serialize() { std::string output = ""; if (!this->sortFields_.empty()) { output += "\"cb_sort_key\" : ["; for (int i = 0; i < (int)this->sortFields_.size(); i++) { output += this->sortFields_[i]; if (i < (int)this->sortFields_.size() - 1) output += ", "; } output += " ], "; } if (this->limit > 0) { output += "\"cb_limit\" : " + this->limit; output += ", "; } output += "\"cb_search_key\" : { "; output += this->serialize(this, true); output += " } "; return output; } std::string CBHelperSearchCondition::serialize(CBHelperSearchCondition* cond, bool isTop) { std::string output = "{ "; if (cond->field_ == "") { if (!cond->conditions_.empty()) { int prevLink = -1; std::string curCond = ""; for (int i = 0; i < (int)cond->conditions_.size(); i++) { CBHelperSearchCondition* curGroup = cond->conditions_[i]; if (prevLink != -1 && prevLink != curGroup->contidionLink_) { std::string linkStr = cond->CBConditionLink_ToString[prevLink]; output += "\"" + linkStr + "\" : " + curCond + ", "; curCond = ""; } curCond = curGroup->serialize(curGroup, false); prevLink = curGroup->contidionLink_; if (i == (int)cond->conditions_.size() - 1) { //[output setValue:curObject forKey:CBConditionLink_Tostd::string[prevLink]]; std::string linkStr = cond->CBConditionLink_ToString[prevLink]; output += "\"" + linkStr + "\" : " + curCond; } } } } else { std::string op = cond->CBConditionOperator_ToString[cond->conditionOperator_]; switch (cond->conditionOperator_) { case CBOperatorEqual: output += "\"" + cond->field_ + "\""; output += " : \"" + cond->value_ + "\""; break; case CBOperatorAll: case CBOperatorExists: case CBOperatorNe: case CBOperatorIn: case CBOperatorNin: case CBOperatorSize: case CBOperatorType: output += "\"" + cond->field_ + "\""; output += " : { \"" + op + "\" : \"" + cond->value_ + "\" } "; //[cond setValue:conditionsGroup.value forKey:CBConditionOperator_Tostd::string[conditionsGroup.CBOperator]]; //[output setValue:cond forKey:conditionsGroup.field]; break; case CBOperatorMod: output += "\"" + cond->field_ + "\""; output += " : { \"" + op + "\" : [ " + cond->value_ + ", 1 ] } "; break; case CBOperatorWithin: output += "\"" + cond->field_ + "\""; output += " : { \"" + op + "\" : { \"$box\" : " + cond->value_ + " } } "; break; case CBOperatorNear: output += "\"" + cond->field_ + "\""; output += " : " + cond->value_; break; default: break; } } output += " }"; return output; } } <commit_msg>Fixed issue with search condition serialization<commit_after>/* Copyright (C) 2012 cloudbase.io This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. 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; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "CBHelperSearchCondition.h" namespace Cloudbase { const std::string CBHelperSearchCondition::CBConditionOperator_ToString[] = { "", "$lt", "$lte", "$gt", "$gte", "$all", "$exists", "$mod", "$ne", "$in", "$nin", "$size", "$type", "$within", "$near" }; const std::string CBHelperSearchCondition::CBConditionLink_ToString[] = { "$and", "$or", "$nor" }; CBHelperSearchCondition::CBHelperSearchCondition() { this->baseInit(); } CBHelperSearchCondition::CBHelperSearchCondition(std::string field, std::string value, CBConditionOperator op) { this->baseInit(); this->field_ = field; this->value_ = value; this->conditionOperator_ = op; } CBHelperSearchCondition::CBHelperSearchCondition(double SWLat, double SWLng, double NELat, double NELng) { this->baseInit(); this->field_ = "cb_location"; this->value_ = "[ [ "; this->value_ += SWLat; this->value_ += ", "; this->value_ += SWLng; this->value_ += "], [ "; this->value_ += NELat; this->value_ += ", "; this->value_ += NELng; this->value_ += "] ] "; this->conditionOperator_ = CBOperatorWithin; } CBHelperSearchCondition::CBHelperSearchCondition(double lat, double lng, double maxDistance) { this->baseInit(); this->field_ = "cb_location"; this->value_ = "{ \"$near\" : [ "; this->value_ += lat; this->value_ += ", "; this->value_ += lng; this->value_ += "], \"$maxDistance\" : "; this->value_ += maxDistance; this->value_ += " }"; this->conditionOperator_ = CBOperatorNear; } void CBHelperSearchCondition::setConditionLink(CBConditionLink link) { this->contidionLink_ = link; } void CBHelperSearchCondition::addCondition(CBHelperSearchCondition* newCond) { this->conditions_.insert(this->conditions_.begin(), newCond); } void CBHelperSearchCondition::baseInit() { this->field_ = ""; this->value_ = ""; this->limit = -1; this->commandType = CBDataAggregationMatch; } void CBHelperSearchCondition::addSortField(std::string fieldName, CBSortDirection dir) { std::string sortField = "{ \""; sortField += fieldName + "\" : "; sortField += dir + " }"; this->sortFields_.insert(this->sortFields_.begin(), sortField); } std::string CBHelperSearchCondition::serializeAggregateConditions() { return this->serialize(this, true); } std::string CBHelperSearchCondition::serialize() { std::string output = ""; if (!this->sortFields_.empty()) { output += "\"cb_sort_key\" : ["; for (int i = 0; i < (int)this->sortFields_.size(); i++) { output += this->sortFields_[i]; if (i < (int)this->sortFields_.size() - 1) output += ", "; } output += " ], "; } if (this->limit > 0) { output += "\"cb_limit\" : " + this->limit; output += ", "; } output += "\"cb_search_key\" : { "; output += this->serialize(this, true); output += " } "; return output; } std::string CBHelperSearchCondition::serialize(CBHelperSearchCondition* cond, bool isTop) { std::string output = "{ "; if (cond->field_ == "") { if (!cond->conditions_.empty()) { int prevLink = -1; std::string curCond = ""; for (int i = 0; i < (int)cond->conditions_.size(); i++) { CBHelperSearchCondition* curGroup = cond->conditions_[i]; if (prevLink != -1 && prevLink != curGroup->contidionLink_) { std::string linkStr = cond->CBConditionLink_ToString[prevLink]; output += "\"" + linkStr + "\" : " + curCond + ", "; curCond = ""; } curCond = curGroup->serialize(curGroup, false); prevLink = curGroup->contidionLink_; if (i == (int)cond->conditions_.size() - 1) { //[output setValue:curObject forKey:CBConditionLink_Tostd::string[prevLink]]; std::string linkStr = cond->CBConditionLink_ToString[prevLink]; output += "\"" + linkStr + "\" : " + curCond; } } } } else { std::string op = cond->CBConditionOperator_ToString[cond->conditionOperator_]; switch (cond->conditionOperator_) { case CBOperatorEqual: output += "\"" + cond->field_ + "\""; output += " : \"" + cond->value_ + "\""; break; case CBOperatorAll: case CBOperatorExists: case CBOperatorNe: case CBOperatorIn: case CBOperatorBigger: case CBOperatorBiggerOrEqual: case CBOperatorLess: case CBOperatorLessOrEqual: case CBOperatorNin: case CBOperatorSize: case CBOperatorType: output += "\"" + cond->field_ + "\""; output += " : { \"" + op + "\" : \"" + cond->value_ + "\" } "; //[cond setValue:conditionsGroup.value forKey:CBConditionOperator_Tostd::string[conditionsGroup.CBOperator]]; //[output setValue:cond forKey:conditionsGroup.field]; break; case CBOperatorMod: output += "\"" + cond->field_ + "\""; output += " : { \"" + op + "\" : [ " + cond->value_ + ", 1 ] } "; break; case CBOperatorWithin: output += "\"" + cond->field_ + "\""; output += " : { \"" + op + "\" : { \"$box\" : " + cond->value_ + " } } "; break; case CBOperatorNear: output += "\"" + cond->field_ + "\""; output += " : " + cond->value_; break; default: break; } } output += " }"; return output; } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/url_constants.h" #include "content/browser/tab_contents/navigation_details.h" #include "content/browser/tab_contents/tab_contents.h" namespace { const char kSharedWorkerTestPage[] = "files/workers/workers_ui_shared_worker.html"; const char kSharedWorkerJs[] = "files/workers/workers_ui_shared_worker.js"; class WorkersUITest : public InProcessBrowserTest { public: WorkersUITest() { set_show_window(true); EnableDOMAutomation(); } private: DISALLOW_COPY_AND_ASSIGN(WorkersUITest); }; IN_PROC_BROWSER_TEST_F(WorkersUITest, SharedWorkersList) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL(kSharedWorkerTestPage); ui_test_utils::NavigateToURL(browser(), url); ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(chrome::kChromeUIWorkersURL), NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); TabContents* tab_contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(tab_contents != NULL); std::string result; ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( tab_contents->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + document.getElementsByTagName('td')[1].textContent);", &result)); ASSERT_TRUE(result.find(kSharedWorkerJs) != std::string::npos); } } // namespace <commit_msg>Mark WorkersUITest.SharedWorkersLis as failing on Mac OS X<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/url_constants.h" #include "content/browser/tab_contents/navigation_details.h" #include "content/browser/tab_contents/tab_contents.h" namespace { const char kSharedWorkerTestPage[] = "files/workers/workers_ui_shared_worker.html"; const char kSharedWorkerJs[] = "files/workers/workers_ui_shared_worker.js"; class WorkersUITest : public InProcessBrowserTest { public: WorkersUITest() { set_show_window(true); EnableDOMAutomation(); } private: DISALLOW_COPY_AND_ASSIGN(WorkersUITest); }; // The test fails on Mac OS X, see crbug.com/89583 #if defined(OS_MACOSX) #define MAYBE_SharedWorkersList FAILS_SharedWorkersList #else #define MAYBE_SharedWorkersList SharedWorkersList #endif IN_PROC_BROWSER_TEST_F(WorkersUITest, MAYBE_SharedWorkersList) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL(kSharedWorkerTestPage); ui_test_utils::NavigateToURL(browser(), url); ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(chrome::kChromeUIWorkersURL), NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); TabContents* tab_contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(tab_contents != NULL); std::string result; ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( tab_contents->render_view_host(), L"", L"window.domAutomationController.send(" L"'' + document.getElementsByTagName('td')[1].textContent);", &result)); ASSERT_TRUE(result.find(kSharedWorkerJs) != std::string::npos); } } // namespace <|endoftext|>
<commit_before>/* * Copyright (C) 2019 pengjian.uestc @ gmail.com */ /* * 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 "redis/service.hh" #include "redis/keyspace_utils.hh" #include "redis/server.hh" #include "db/config.hh" #include "log.hh" #include "auth/common.hh" #include "database.hh" static logging::logger slogger("redis_service"); redis_service::redis_service() { } redis_service::~redis_service() { } future<> redis_service::listen(distributed<auth::service>& auth_service, db::config& cfg) { if (_server) { return make_ready_future<>(); } auto server = make_shared<distributed<redis_transport::redis_server>>(); _server = server; auto make_timeout_config = [] (db::config& cfg) { timeout_config tc; tc.read_timeout = cfg.read_request_timeout_in_ms() * 1ms; tc.write_timeout = cfg.write_request_timeout_in_ms() * 1ms; tc.range_read_timeout = cfg.range_request_timeout_in_ms() * 1ms; tc.counter_write_timeout = cfg.counter_write_request_timeout_in_ms() * 1ms; tc.truncate_timeout = cfg.truncate_request_timeout_in_ms() * 1ms; tc.cas_timeout = cfg.cas_contention_timeout_in_ms() * 1ms; tc.other_timeout = cfg.request_timeout_in_ms() * 1ms; return tc; }; auto addr = cfg.rpc_address(); auto preferred = cfg.rpc_interface_prefer_ipv6() ? std::make_optional(net::inet_address::family::INET6) : std::nullopt; auto family = cfg.enable_ipv6_dns_lookup() || preferred ? std::nullopt : std::make_optional(net::inet_address::family::INET); auto ceo = cfg.client_encryption_options(); auto keepalive = cfg.rpc_keepalive(); redis_transport::redis_server_config redis_cfg; redis_cfg._timeout_config = make_timeout_config(cfg); redis_cfg._read_consistency_level = make_consistency_level(cfg.redis_read_consistency_level()); redis_cfg._write_consistency_level = make_consistency_level(cfg.redis_write_consistency_level()); redis_cfg._max_request_size = memory::stats().total_memory() / 10; redis_cfg._total_redis_db_count = cfg.redis_database_count(); return gms::inet_address::lookup(addr, family, preferred).then([this, server, addr, &cfg, keepalive, ceo = std::move(ceo), redis_cfg, &auth_service] (seastar::net::inet_address ip) { return server->start(std::ref(service::get_storage_proxy()), std::ref(_query_processor), std::ref(auth_service), redis_cfg).then([server, &cfg, addr, ip, ceo, keepalive]() { auto f = make_ready_future(); struct listen_cfg { socket_address addr; std::shared_ptr<seastar::tls::credentials_builder> cred; }; std::vector<listen_cfg> configs; if (cfg.redis_port()) { configs.emplace_back(listen_cfg { {socket_address{ip, cfg.redis_port()}} }); } // main should have made sure values are clean and neatish if (ceo.at("enabled") == "true") { auto cred = std::make_shared<seastar::tls::credentials_builder>(); cred->set_dh_level(seastar::tls::dh_params::level::MEDIUM); cred->set_priority_string(db::config::default_tls_priority); if (ceo.count("priority_string")) { cred->set_priority_string(ceo.at("priority_string")); } if (ceo.count("require_client_auth") && ceo.at("require_client_auth") == "true") { cred->set_client_auth(seastar::tls::client_auth::REQUIRE); } f = cred->set_x509_key_file(ceo.at("certificate"), ceo.at("keyfile"), seastar::tls::x509_crt_format::PEM); if (ceo.count("truststore")) { f = f.then([cred, f = ceo.at("truststore")] { return cred->set_x509_trust_file(f, seastar::tls::x509_crt_format::PEM); }); } slogger.info("Enabling encrypted REDIS connections between client and server"); if (cfg.redis_ssl_port() && cfg.redis_ssl_port() != cfg.redis_port()) { configs.emplace_back(listen_cfg{{ip, cfg.redis_ssl_port()}, std::move(cred)}); } else { configs.back().cred = std::move(cred); } } return f.then([server, configs = std::move(configs), keepalive] { return parallel_for_each(configs, [server, keepalive](const listen_cfg & cfg) { return server->invoke_on_all(&redis_transport::redis_server::listen, cfg.addr, cfg.cred, keepalive).then([cfg] { slogger.info("Starting listening for REDIS clients on {} ({})", cfg.addr, cfg.cred ? "encrypted" : "unencrypted"); }); }); }); }); }); } future<> redis_service::init(distributed<service::storage_proxy>& proxy, distributed<database>& db, distributed<auth::service>& auth_service, db::config& cfg) { // 1. Create keyspace/tables used by redis API if not exists. // 2. Initialize the redis query processor. // 3. Listen on the redis transport port. return redis::maybe_create_keyspace(cfg).then([this, &proxy, &db] { auto& proxy = service::get_storage_proxy(); return _query_processor.start(std::ref(proxy), std::ref(db)); }).then([this] { return _query_processor.invoke_on_all([] (auto& processor) { return processor.start(); }); }).then([this, &cfg, &auth_service] { return listen(auth_service, cfg); }); } future<> redis_service::stop() { // If the redis protocol disable, the redis_service::init is not // invoked at all. Do nothing if `_server is null. if (_server) { return _server->stop().then([this] { return _query_processor.stop(); }); } return make_ready_future<>(); } <commit_msg>redis: remove redundant code<commit_after>/* * Copyright (C) 2019 pengjian.uestc @ gmail.com */ /* * 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 "redis/service.hh" #include "redis/keyspace_utils.hh" #include "redis/server.hh" #include "db/config.hh" #include "log.hh" #include "auth/common.hh" #include "database.hh" static logging::logger slogger("redis_service"); redis_service::redis_service() { } redis_service::~redis_service() { } future<> redis_service::listen(distributed<auth::service>& auth_service, db::config& cfg) { if (_server) { return make_ready_future<>(); } auto server = make_shared<distributed<redis_transport::redis_server>>(); _server = server; auto make_timeout_config = [] (db::config& cfg) { timeout_config tc; tc.read_timeout = cfg.read_request_timeout_in_ms() * 1ms; tc.write_timeout = cfg.write_request_timeout_in_ms() * 1ms; tc.range_read_timeout = cfg.range_request_timeout_in_ms() * 1ms; tc.counter_write_timeout = cfg.counter_write_request_timeout_in_ms() * 1ms; tc.truncate_timeout = cfg.truncate_request_timeout_in_ms() * 1ms; tc.cas_timeout = cfg.cas_contention_timeout_in_ms() * 1ms; tc.other_timeout = cfg.request_timeout_in_ms() * 1ms; return tc; }; auto addr = cfg.rpc_address(); auto preferred = cfg.rpc_interface_prefer_ipv6() ? std::make_optional(net::inet_address::family::INET6) : std::nullopt; auto family = cfg.enable_ipv6_dns_lookup() || preferred ? std::nullopt : std::make_optional(net::inet_address::family::INET); auto ceo = cfg.client_encryption_options(); auto keepalive = cfg.rpc_keepalive(); redis_transport::redis_server_config redis_cfg; redis_cfg._timeout_config = make_timeout_config(cfg); redis_cfg._read_consistency_level = make_consistency_level(cfg.redis_read_consistency_level()); redis_cfg._write_consistency_level = make_consistency_level(cfg.redis_write_consistency_level()); redis_cfg._max_request_size = memory::stats().total_memory() / 10; redis_cfg._total_redis_db_count = cfg.redis_database_count(); return gms::inet_address::lookup(addr, family, preferred).then([this, server, addr, &cfg, keepalive, ceo = std::move(ceo), redis_cfg, &auth_service] (seastar::net::inet_address ip) { return server->start(std::ref(service::get_storage_proxy()), std::ref(_query_processor), std::ref(auth_service), redis_cfg).then([server, &cfg, addr, ip, ceo, keepalive]() { auto f = make_ready_future(); struct listen_cfg { socket_address addr; std::shared_ptr<seastar::tls::credentials_builder> cred; }; std::vector<listen_cfg> configs; if (cfg.redis_port()) { configs.emplace_back(listen_cfg { {socket_address{ip, cfg.redis_port()}} }); } // main should have made sure values are clean and neatish if (ceo.at("enabled") == "true") { auto cred = std::make_shared<seastar::tls::credentials_builder>(); cred->set_dh_level(seastar::tls::dh_params::level::MEDIUM); cred->set_priority_string(db::config::default_tls_priority); if (ceo.count("priority_string")) { cred->set_priority_string(ceo.at("priority_string")); } if (ceo.count("require_client_auth") && ceo.at("require_client_auth") == "true") { cred->set_client_auth(seastar::tls::client_auth::REQUIRE); } f = cred->set_x509_key_file(ceo.at("certificate"), ceo.at("keyfile"), seastar::tls::x509_crt_format::PEM); if (ceo.count("truststore")) { f = f.then([cred, f = ceo.at("truststore")] { return cred->set_x509_trust_file(f, seastar::tls::x509_crt_format::PEM); }); } slogger.info("Enabling encrypted REDIS connections between client and server"); if (cfg.redis_ssl_port() && cfg.redis_ssl_port() != cfg.redis_port()) { configs.emplace_back(listen_cfg{{ip, cfg.redis_ssl_port()}, std::move(cred)}); } else { configs.back().cred = std::move(cred); } } return f.then([server, configs = std::move(configs), keepalive] { return parallel_for_each(configs, [server, keepalive](const listen_cfg & cfg) { return server->invoke_on_all(&redis_transport::redis_server::listen, cfg.addr, cfg.cred, keepalive).then([cfg] { slogger.info("Starting listening for REDIS clients on {} ({})", cfg.addr, cfg.cred ? "encrypted" : "unencrypted"); }); }); }); }); }); } future<> redis_service::init(distributed<service::storage_proxy>& proxy, distributed<database>& db, distributed<auth::service>& auth_service, db::config& cfg) { // 1. Create keyspace/tables used by redis API if not exists. // 2. Initialize the redis query processor. // 3. Listen on the redis transport port. return redis::maybe_create_keyspace(cfg).then([this, &proxy, &db] { return _query_processor.start(std::ref(proxy), std::ref(db)); }).then([this] { return _query_processor.invoke_on_all([] (auto& processor) { return processor.start(); }); }).then([this, &cfg, &auth_service] { return listen(auth_service, cfg); }); } future<> redis_service::stop() { // If the redis protocol disable, the redis_service::init is not // invoked at all. Do nothing if `_server is null. if (_server) { return _server->stop().then([this] { return _query_processor.stop(); }); } return make_ready_future<>(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup // 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 <stingraykit/io/PipeReader.h> namespace stingray { PipeReader::PipeReader(const IPipePtr& pipe) : _pipe(pipe) { } u8 PipeReader::ReadByte(const ICancellationToken& token) { u8 result; if (Read(ByteData(&result, sizeof(result)), token) != sizeof(result)) { STINGRAYKIT_CHECK(!token, "Abnormal behaviour!"); STINGRAYKIT_THROW(OperationCancelledException()); } return result; } std::string PipeReader::ReadLine(const ICancellationToken& token) { std::string result; try { for (u8 byte = ReadByte(token); ; byte = ReadByte(token)) { if (byte == '\n') return result; if (byte == '\r') { const u8 next = ReadByte(token); if (next == '\n') return result; STINGRAYKIT_THROW(NotSupportedException()); } result.push_back(byte); } } catch (const PipeClosedException&) { if (result.empty()) throw; } return result; } } <commit_msg>PipeReader: add nullptr check<commit_after>// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup // 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 <stingraykit/io/PipeReader.h> namespace stingray { PipeReader::PipeReader(const IPipePtr& pipe) : _pipe(STINGRAYKIT_REQUIRE_NOT_NULL(pipe)) { } u8 PipeReader::ReadByte(const ICancellationToken& token) { u8 result; if (Read(ByteData(&result, sizeof(result)), token) != sizeof(result)) { STINGRAYKIT_CHECK(!token, "Abnormal behaviour!"); STINGRAYKIT_THROW(OperationCancelledException()); } return result; } std::string PipeReader::ReadLine(const ICancellationToken& token) { std::string result; try { for (u8 byte = ReadByte(token); ; byte = ReadByte(token)) { if (byte == '\n') return result; if (byte == '\r') { const u8 next = ReadByte(token); if (next == '\n') return result; STINGRAYKIT_THROW(NotSupportedException()); } result.push_back(byte); } } catch (const PipeClosedException&) { if (result.empty()) throw; } return result; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2003-2011 Victor Semionov * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of the contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <windows.h> #include <gl/gl.h> #include <gl/glu.h> #ifdef _MSC_VER #define _USE_MATH_DEFINES #endif #include <math.h> #include <gl/glext.h> #include "Settings.h" #include "Loader.h" #include "VideoBase.h" #include "Window.h" #include "Error.h" #include "GamePlay.h" #include "StarMap.h" //resource stuff #define STARMAP_RESOURCE CSettings::DataFile #define STARMAP_FILE "STARS.TXT" //sphere radius #define STARMAP_RADIUS 100.0 //num random stars #define NUM_RANDOM_STARS_BASE 8192 #define NUM_RANDOM_STARS ((int)((float)NUM_RANDOM_STARS_BASE*CVideoBase::GetOptGeoDetail())) //random star size and color #define MIN_INTENSITY 0.6f //also affects colorfulness of stars, when generated randomly #define MIN_MAG 3.5 #define MAX_MAG 7.5 //real-star color levels #define YELLOW_LEVEL 0.6f #define BLUE_LEVEL 0.5f #define COLOR_INDEX_SCALE 0.25f #define BRIGHT_SCALE true #define MIN_BRIGHT 0.75f #define BRIGHT_INDEX_SCALE 0.125f //magnitude-size conversion #define STAR_SIZE(star_mag) (0.75+(7.0-star_mag)/2.5) //point size macros #define POINT_SIZE_AT_H600 1.25 #define SQRT_QUAD_ATTEN_INV (STARMAP_RADIUS) #define QUAD_ATTEN_INV (SQRT_QUAD_ATTEN_INV*SQRT_QUAD_ATTEN_INV) #define QUAD_ATTEN (1.0/QUAD_ATTEN_INV) #define STAR_DIST(star_size) (CVideoBase::GetExtPointParams()? \ (SQRT_QUAD_ATTEN_INV/star_size): \ STARMAP_RADIUS) CStarMap::CStarMap() { Init(); } CStarMap::~CStarMap() { Free(); } bool CStarMap::Load() { Free(); if (LoadStars()) { PrepColor(); } else { CError::LogError(WARNING_CODE,"Failed to load stars, trying to generate randomly."); Free(); if (CGamePlay::UserAbortedLoad()) { CError::LogError(ERROR_CODE,"Starmap load aborted by user."); return false; } CGamePlay::UpdateSplash("generating... "); if (!GenStars()) { CError::LogError(WARNING_CODE,"Failed to generate random stars."); Free(); return false; } } PrepData(); point_size=(float)(POINT_SIZE_AT_H600*((double)CWindow::GetHeight()/600.0)); // twinkle=CVideoBase::GetOptStarTwinkle(); twinkle=false; //no twinkle effect yet InitGL(); if (!twinkle) { object = glGenLists(1); if (object==0) { CError::LogError(WARNING_CODE,"Internal OpenGL error - starmap display list not recorded."); Free(); return false; } glNewList(object,GL_COMPILE); { DrawStars(); } glEndList(); } return true; } void CStarMap::Free() { if (glIsList(object)) glDeleteLists(object,1); if (stars) { free(stars); } Init(); } void CStarMap::Draw() { if (!twinkle) { glCallList(object); } else { DrawStars(); } } void CStarMap::Init() { object=0; twinkle=false; stars=NULL; num_stars=0; point_size=1.0f; } bool CStarMap::LoadStars() { //////////////// #define FreeLines() \ { \ for (int l=0;l<numlines;l++)\ free(textlines[l]); \ free(textlines); \ textlines=NULL; \ numlines=0; \ } //////////////// #define AbortParse() \ { \ FreeLines(); \ return false; \ } //////////////// #define VA_NUM 6 #define VA_FMT "%lf %lf | %f | %f %f %f" #define VA_ARGS \ &stars[i].Dec, \ &stars[i].RA, \ &stars[i].Mag, \ &stars[i].B_V, \ &stars[i].U_B, \ &stars[i].R_I ///////////////////// char **textlines=NULL; int numlines=0; int lineindex; int i; CLoader loader; if (!loader.WithResource(STARMAP_RESOURCE)) { CError::LogError(WARNING_CODE,"Unable to open starmap file - missing or invalid resource."); return false; } if (!loader.LoadText(STARMAP_FILE,&textlines,&numlines)) { CError::LogError(WARNING_CODE,"Unable to load starmap data - file missing from resource or internal loader subsystem error."); return false; } if (textlines==NULL) { CError::LogError(WARNING_CODE,"Unable to load starmap - internal loader subsystem error."); return false; } if (numlines==0) { CError::LogError(WARNING_CODE,"Unable to load starmap - empty data file."); return false; } { lineindex=0; while (sscanf(textlines[lineindex],"%d",&num_stars)!=1 || textlines[lineindex][0]=='/') { lineindex++; if (lineindex>=numlines) { CError::LogError(WARNING_CODE,"Unable to load star data - unexpected end of file."); AbortParse(); } } stars=(stardata_s*)malloc(num_stars*sizeof(stardata_s)); if (!stars) { CError::LogError(WARNING_CODE,"Unable to load stars - memory allocation failed."); AbortParse(); } ZeroMemory(stars,num_stars*sizeof(stardata_s)); for (i=0;i<num_stars;i++) { lineindex++; while (sscanf(textlines[lineindex],VA_FMT,VA_ARGS)!=VA_NUM || textlines[lineindex][0]=='/') { lineindex++; if (lineindex>=numlines) { CError::LogError(WARNING_CODE,"Unable to load star data - unexpected end of file."); AbortParse(); } } } } FreeLines(); return true; } bool CStarMap::GenStars() { int i; num_stars=NUM_RANDOM_STARS; stars=(stardata_s*)malloc(num_stars*sizeof(stardata_s)); if (!stars) { CError::LogError(WARNING_CODE,"Unable to generate star data - memory allocation failed."); return false; } const float mi=MIN_INTENSITY; const float ri=(1.0f-MIN_INTENSITY); for (i=0;i<num_stars;i++) { double Z=((double)(rand()%(2*16384+1))/16384.0)-1.0; stars[i].Dec=acos(Z)*(180.0/M_PI); stars[i].RA=(double)(rand()%(360*64))/64.0; stars[i].Mag=(float)(MIN_MAG+(double)(rand()%(int)((MAX_MAG-MIN_MAG)*100.0+1.0))/100.0); stars[i].color[0]=mi+(float)(rand()%256)*(ri/255.0f); stars[i].color[1]=mi+(float)(rand()%256)*(ri/255.0f); stars[i].color[2]=mi+(float)(rand()%256)*(ri/255.0f); } return true; } void CStarMap::PrepColor() { float r,g,b; float f; int i; for (i=0;i<num_stars;i++) { stardata_s *star=&stars[i]; // init components r=g=YELLOW_LEVEL; b=BLUE_LEVEL; // diff color b+=star->B_V*COLOR_INDEX_SCALE; // maximize brightness f=1.0f/max(max(r,g),b); r*=f; g*=f; b*=f; // diff brightness (optional) if (BRIGHT_SCALE) { f=MIN_BRIGHT+(float)fabs(star->R_I)*BRIGHT_INDEX_SCALE; f=min(f,1.0f); r*=f; g*=f; b*=f; } // apply color star->color[0]=r; star->color[1]=g; star->color[2]=b; } } void CStarMap::PrepData() { int i; for (i=0;i<num_stars;i++) { double theta=stars[i].Dec*(M_PI/180.0); double phi=stars[i].RA*(M_PI/180.0); double Ctheta=cos(theta); double Stheta=sin(theta); double Cphi=cos(phi); double Sphi=sin(phi); double size=STAR_SIZE(stars[i].Mag); // size correction if (CVideoBase::GetExtPointParams()) size/=1.6; stars[i].size=(float)size; stars[i].pos[0]=(float)(STAR_DIST(size)*Cphi*Stheta); stars[i].pos[1]=(float)(STAR_DIST(size)*Sphi*Stheta); stars[i].pos[2]=(float)(STAR_DIST(size)*Ctheta); } } void CStarMap::InitGL() { glPointSize(point_size); bool autosize=CVideoBase::GetExtPointParams(); if (autosize) { PFNGLPOINTPARAMETERFARBPROC glPointParameterfARB = NULL; PFNGLPOINTPARAMETERFVARBPROC glPointParameterfvARB = NULL; glPointParameterfARB=(PFNGLPOINTPARAMETERFARBPROC)wglGetProcAddress("glPointParameterfARB"); glPointParameterfvARB=(PFNGLPOINTPARAMETERFVARBPROC)wglGetProcAddress("glPointParameterfvARB"); if (glPointParameterfvARB!=NULL) { GLfloat DistAttenFactors[3] = {0.0f, 0.0f, (float)QUAD_ATTEN}; glPointParameterfvARB(GL_POINT_DISTANCE_ATTENUATION_ARB,DistAttenFactors); } } } void CStarMap::DrawStars() { int i; int lastsize10=(int)(point_size*10.0f); bool autosize=CVideoBase::GetExtPointParams(); glPushAttrib(GL_ENABLE_BIT); glDisable(GL_DEPTH_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glDisable(GL_CULL_FACE); glEnable(GL_POINT_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE); { glBegin(GL_POINTS); { for (i=0;i<num_stars;i++) { if (!autosize) { int size10=(int)(stars[i].size*10.0f); if (size10!=lastsize10) { glEnd(); glPointSize(stars[i].size*point_size); glBegin(GL_POINTS); lastsize10=size10; } } glColor3fv((GLfloat*)&stars[i].color); glVertex3fv((GLfloat*)&stars[i].pos); } } glEnd(); } glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glPopAttrib(); } <commit_msg>Decreased generated star magnitude. Exported a hard-coded constant as a macro.<commit_after>/* * Copyright (C) 2003-2011 Victor Semionov * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of the contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <windows.h> #include <gl/gl.h> #include <gl/glu.h> #ifdef _MSC_VER #define _USE_MATH_DEFINES #endif #include <math.h> #include <gl/glext.h> #include "Settings.h" #include "Loader.h" #include "VideoBase.h" #include "Window.h" #include "Error.h" #include "GamePlay.h" #include "StarMap.h" //resource stuff #define STARMAP_RESOURCE CSettings::DataFile #define STARMAP_FILE "STARS.TXT" //sphere radius #define STARMAP_RADIUS 100.0 //num random stars #define NUM_RANDOM_STARS_BASE 8192 #define NUM_RANDOM_STARS ((int)((float)NUM_RANDOM_STARS_BASE*CVideoBase::GetOptGeoDetail())) //random star size and color #define MIN_INTENSITY 0.6f //also affects colorfulness of stars, when generated randomly #define MIN_MAG 4.75 #define MAX_MAG 7.9 //real-star color levels #define YELLOW_LEVEL 0.6f #define BLUE_LEVEL 0.5f #define COLOR_INDEX_SCALE 0.25f #define BRIGHT_SCALE true #define MIN_BRIGHT 0.75f #define BRIGHT_INDEX_SCALE 0.125f //magnitude-size conversion #define STAR_SIZE(star_mag) (0.75+(7.0-star_mag)/2.5) //point size macros #define POINT_SIZE_AT_H600 1.25 #define SQRT_QUAD_ATTEN_INV (STARMAP_RADIUS) #define QUAD_ATTEN_INV (SQRT_QUAD_ATTEN_INV*SQRT_QUAD_ATTEN_INV) #define QUAD_ATTEN (1.0/QUAD_ATTEN_INV) #define STAR_DIST(star_size) (CVideoBase::GetExtPointParams()? \ (SQRT_QUAD_ATTEN_INV/star_size): \ STARMAP_RADIUS) #define AUTO_SIZE_COEF 0.625 CStarMap::CStarMap() { Init(); } CStarMap::~CStarMap() { Free(); } bool CStarMap::Load() { Free(); if (LoadStars()) { PrepColor(); } else { CError::LogError(WARNING_CODE,"Failed to load stars, trying to generate randomly."); Free(); if (CGamePlay::UserAbortedLoad()) { CError::LogError(ERROR_CODE,"Starmap load aborted by user."); return false; } CGamePlay::UpdateSplash("generating... "); if (!GenStars()) { CError::LogError(WARNING_CODE,"Failed to generate random stars."); Free(); return false; } } PrepData(); point_size=(float)(POINT_SIZE_AT_H600*((double)CWindow::GetHeight()/600.0)); // twinkle=CVideoBase::GetOptStarTwinkle(); twinkle=false; //no twinkle effect yet InitGL(); if (!twinkle) { object = glGenLists(1); if (object==0) { CError::LogError(WARNING_CODE,"Internal OpenGL error - starmap display list not recorded."); Free(); return false; } glNewList(object,GL_COMPILE); { DrawStars(); } glEndList(); } return true; } void CStarMap::Free() { if (glIsList(object)) glDeleteLists(object,1); if (stars) { free(stars); } Init(); } void CStarMap::Draw() { if (!twinkle) { glCallList(object); } else { DrawStars(); } } void CStarMap::Init() { object=0; twinkle=false; stars=NULL; num_stars=0; point_size=1.0f; } bool CStarMap::LoadStars() { //////////////// #define FreeLines() \ { \ for (int l=0;l<numlines;l++)\ free(textlines[l]); \ free(textlines); \ textlines=NULL; \ numlines=0; \ } //////////////// #define AbortParse() \ { \ FreeLines(); \ return false; \ } //////////////// #define VA_NUM 6 #define VA_FMT "%lf %lf | %f | %f %f %f" #define VA_ARGS \ &stars[i].Dec, \ &stars[i].RA, \ &stars[i].Mag, \ &stars[i].B_V, \ &stars[i].U_B, \ &stars[i].R_I ///////////////////// char **textlines=NULL; int numlines=0; int lineindex; int i; CLoader loader; if (!loader.WithResource(STARMAP_RESOURCE)) { CError::LogError(WARNING_CODE,"Unable to open starmap file - missing or invalid resource."); return false; } if (!loader.LoadText(STARMAP_FILE,&textlines,&numlines)) { CError::LogError(WARNING_CODE,"Unable to load starmap data - file missing from resource or internal loader subsystem error."); return false; } if (textlines==NULL) { CError::LogError(WARNING_CODE,"Unable to load starmap - internal loader subsystem error."); return false; } if (numlines==0) { CError::LogError(WARNING_CODE,"Unable to load starmap - empty data file."); return false; } { lineindex=0; while (sscanf(textlines[lineindex],"%d",&num_stars)!=1 || textlines[lineindex][0]=='/') { lineindex++; if (lineindex>=numlines) { CError::LogError(WARNING_CODE,"Unable to load star data - unexpected end of file."); AbortParse(); } } stars=(stardata_s*)malloc(num_stars*sizeof(stardata_s)); if (!stars) { CError::LogError(WARNING_CODE,"Unable to load stars - memory allocation failed."); AbortParse(); } ZeroMemory(stars,num_stars*sizeof(stardata_s)); for (i=0;i<num_stars;i++) { lineindex++; while (sscanf(textlines[lineindex],VA_FMT,VA_ARGS)!=VA_NUM || textlines[lineindex][0]=='/') { lineindex++; if (lineindex>=numlines) { CError::LogError(WARNING_CODE,"Unable to load star data - unexpected end of file."); AbortParse(); } } } } FreeLines(); return true; } bool CStarMap::GenStars() { int i; num_stars=NUM_RANDOM_STARS; stars=(stardata_s*)malloc(num_stars*sizeof(stardata_s)); if (!stars) { CError::LogError(WARNING_CODE,"Unable to generate star data - memory allocation failed."); return false; } const float mi=MIN_INTENSITY; const float ri=(1.0f-MIN_INTENSITY); for (i=0;i<num_stars;i++) { double Z=((double)(rand()%(2*16384+1))/16384.0)-1.0; stars[i].Dec=acos(Z)*(180.0/M_PI); stars[i].RA=(double)(rand()%(360*64))/64.0; stars[i].Mag=(float)(MIN_MAG+(double)(rand()%(int)((MAX_MAG-MIN_MAG)*100.0+1.0))/100.0); stars[i].color[0]=mi+(float)(rand()%256)*(ri/255.0f); stars[i].color[1]=mi+(float)(rand()%256)*(ri/255.0f); stars[i].color[2]=mi+(float)(rand()%256)*(ri/255.0f); } return true; } void CStarMap::PrepColor() { float r,g,b; float f; int i; for (i=0;i<num_stars;i++) { stardata_s *star=&stars[i]; // init components r=g=YELLOW_LEVEL; b=BLUE_LEVEL; // diff color b+=star->B_V*COLOR_INDEX_SCALE; // maximize brightness f=1.0f/max(max(r,g),b); r*=f; g*=f; b*=f; // diff brightness (optional) if (BRIGHT_SCALE) { f=MIN_BRIGHT+(float)fabs(star->R_I)*BRIGHT_INDEX_SCALE; f=min(f,1.0f); r*=f; g*=f; b*=f; } // apply color star->color[0]=r; star->color[1]=g; star->color[2]=b; } } void CStarMap::PrepData() { int i; for (i=0;i<num_stars;i++) { double theta=stars[i].Dec*(M_PI/180.0); double phi=stars[i].RA*(M_PI/180.0); double Ctheta=cos(theta); double Stheta=sin(theta); double Cphi=cos(phi); double Sphi=sin(phi); double size=STAR_SIZE(stars[i].Mag); // size correction if (CVideoBase::GetExtPointParams()) size*=AUTO_SIZE_COEF; stars[i].size=(float)size; stars[i].pos[0]=(float)(STAR_DIST(size)*Cphi*Stheta); stars[i].pos[1]=(float)(STAR_DIST(size)*Sphi*Stheta); stars[i].pos[2]=(float)(STAR_DIST(size)*Ctheta); } } void CStarMap::InitGL() { glPointSize(point_size); bool autosize=CVideoBase::GetExtPointParams(); if (autosize) { PFNGLPOINTPARAMETERFARBPROC glPointParameterfARB = NULL; PFNGLPOINTPARAMETERFVARBPROC glPointParameterfvARB = NULL; glPointParameterfARB=(PFNGLPOINTPARAMETERFARBPROC)wglGetProcAddress("glPointParameterfARB"); glPointParameterfvARB=(PFNGLPOINTPARAMETERFVARBPROC)wglGetProcAddress("glPointParameterfvARB"); if (glPointParameterfvARB!=NULL) { GLfloat DistAttenFactors[3] = {0.0f, 0.0f, (float)QUAD_ATTEN}; glPointParameterfvARB(GL_POINT_DISTANCE_ATTENUATION_ARB,DistAttenFactors); } } } void CStarMap::DrawStars() { int i; int lastsize10=(int)(point_size*10.0f); bool autosize=CVideoBase::GetExtPointParams(); glPushAttrib(GL_ENABLE_BIT); glDisable(GL_DEPTH_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glDisable(GL_CULL_FACE); glEnable(GL_POINT_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE); { glBegin(GL_POINTS); { for (i=0;i<num_stars;i++) { if (!autosize) { int size10=(int)(stars[i].size*10.0f); if (size10!=lastsize10) { glEnd(); glPointSize(stars[i].size*point_size); glBegin(GL_POINTS); lastsize10=size10; } } glColor3fv((GLfloat*)&stars[i].color); glVertex3fv((GLfloat*)&stars[i].pos); } } glEnd(); } glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glPopAttrib(); } <|endoftext|>
<commit_before>#include "Stepper.h" #include "core_pins.h" #include <math.h> #include <algorithm> #include <HardwareSerial.h> Stepper::Stepper(const int stepPin, const int dirPin, bool reverseDir, bool stepsActiveLow) : current(0), v_pullIn(vPullIn_default), vMax(vMaxDefault), /*v(vDefault),*/ a(aDefault), position(0) { pinMode(stepPin, OUTPUT); pinMode(dirPin, OUTPUT); //================================================================================================== // We use bitBanding to set/reset the step and dir pins. // // Step Pin ---------------------------------------------------------------------------------------- // Calculate adresses of bitbanded pin-set and pin-clear registers uint32_t pinRegAddr = (uint32_t)digital_pin_to_info_PGM[stepPin].reg; //GPIO_PDOR uint32_t* pinSetReg = (uint32_t*)(pinRegAddr + 4 * 32); //GPIO_PSOR = GPIO_PDOR + 4 uint32_t* pinClearReg = (uint32_t*)(pinRegAddr + 8 * 32); //GPIO_PCOR = GPIO_PDOR + 8 // Assign registers according to step option if (stepsActiveLow) { stepPinActiveReg = pinClearReg; stepPinInactiveReg = pinSetReg; } else { stepPinActiveReg = pinSetReg; stepPinInactiveReg = pinClearReg; } clearStepPin(); // set step pin to inactive state // Dir pin ----------------------------------------------------------------------------------------- // Calculate adresses of bitbanded pin-set and pin-clear registers pinRegAddr = (uint32_t)digital_pin_to_info_PGM[dirPin].reg; //GPIO_PDOR pinSetReg = (uint32_t*)(pinRegAddr + 4 * 32); //GPIO_PSOR = GPIO_PDOR + 4 pinClearReg = (uint32_t*)(pinRegAddr + 8 * 32); //GPIO_PCOR = GPIO_PDOR + 8 // Assign registers according to DIR option if (reverseDir) { dirPinCwReg = pinClearReg; dirPinCcwReg = pinSetReg; } else { dirPinCwReg = pinSetReg; dirPinCcwReg = pinClearReg; } } void Stepper::SetTargetAbs(int target) { position += dirCw *current; // update position from last move; current = 0; int delta = target - position; if (delta >= 0) { dirCw = 1; target = delta; *dirPinCwReg = 1; } else { dirCw = -1; target = -delta; *dirPinCcwReg = 1; } } void Stepper::SetTargetRel(int delta) { position += dirCw *current; // update position from last move; current = 0; if (delta >= 0) { dirCw = 1; target = delta; *dirPinCwReg = 1; } else { dirCw = -1; target = -delta; *dirPinCcwReg = 1; } } <commit_msg>Update Stepper.cpp<commit_after>#include "Stepper.h" #include "core_pins.h" #include <math.h> #include <algorithm> #include <HardwareSerial.h> Stepper::Stepper(const int stepPin, const int dirPin, bool reverseDir, bool stepsActiveLow) : current(0), v_pullIn(vPullIn_default), vMax(vMaxDefault), /*v(vDefault),*/ a(aDefault), position(0) { pinMode(stepPin, OUTPUT); pinMode(dirPin, OUTPUT); // We use bitBanding to set/reset the step and dir pins. // // Step Pin ---------------------------------------------------------------------------------------- // Calculate adresses of bitbanded pin-set and pin-clear registers uint32_t pinRegAddr = (uint32_t)digital_pin_to_info_PGM[stepPin].reg; //GPIO_PDOR uint32_t* pinSetReg = (uint32_t*)(pinRegAddr + 4 * 32); //GPIO_PSOR = GPIO_PDOR + 4 uint32_t* pinClearReg = (uint32_t*)(pinRegAddr + 8 * 32); //GPIO_PCOR = GPIO_PDOR + 8 // Assign registers according to step option if (stepsActiveLow) { stepPinActiveReg = pinClearReg; stepPinInactiveReg = pinSetReg; } else { stepPinActiveReg = pinSetReg; stepPinInactiveReg = pinClearReg; } clearStepPin(); // set step pin to inactive state // Dir pin ----------------------------------------------------------------------------------------- // Calculate adresses of bitbanded pin-set and pin-clear registers pinRegAddr = (uint32_t)digital_pin_to_info_PGM[dirPin].reg; //GPIO_PDOR pinSetReg = (uint32_t*)(pinRegAddr + 4 * 32); //GPIO_PSOR = GPIO_PDOR + 4 pinClearReg = (uint32_t*)(pinRegAddr + 8 * 32); //GPIO_PCOR = GPIO_PDOR + 8 // Assign registers according to DIR option if (reverseDir) { dirPinCwReg = pinClearReg; dirPinCcwReg = pinSetReg; } else { dirPinCwReg = pinSetReg; dirPinCcwReg = pinClearReg; } } void Stepper::SetTargetAbs(int target) { position += dirCw *current; // update position from last move; current = 0; int delta = target - position; if (delta >= 0) { dirCw = 1; target = delta; *dirPinCwReg = 1; } else { dirCw = -1; target = -delta; *dirPinCcwReg = 1; } } void Stepper::SetTargetRel(int delta) { position += dirCw *current; // update position from last move; current = 0; if (delta >= 0) { dirCw = 1; target = delta; *dirPinCwReg = 1; } else { dirCw = -1; target = -delta; *dirPinCcwReg = 1; } } <|endoftext|>
<commit_before>#ifdef WIN32 #include <windows.h> #endif #include "base.h" #include <iostream> using namespace std; GLint width = 400, height = 400; GLfloat ortho2D_minX = -400.0f, ortho2D_maxX = 400.0f, ortho2D_minY = -400.0f, ortho2D_maxY = 400.0f; Point p1, p2; BBox box; GLfloat radiusMajor = 120.0f, radiusMinor = 40.0f; int ZOOM = 100; float r = 0.0f, g = 1.0f, b = 0.0f; bool isMouseOK = false; void display() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluOrtho2D(ortho2D_minX, ortho2D_maxX, ortho2D_minY, ortho2D_maxY); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Eixo X e Y. DrawXYAxes(); glColor3f(0.0, 0.0, 0.0); glLineWidth(1.2f); // Circulo maior. DrawCircle(p1.X, p1.Y, radiusMajor, 250); // BBox circulo maior. glColor3f(r, g, b); glLineWidth(1.0f); DrawRectangle(box.minX, box.maxX, box.minY, box.maxY); glColor3f(0.0, 0.0, 0.0); // Circulo menor. DrawCircle(p2.X, p2.Y, radiusMinor, 250); // Ponto no centro do circulo menor. glPointSize(4.0f); glBegin(GL_POINTS); glVertex2f(p2.X, p2.Y); glEnd(); glutSwapBuffers(); } void changeBBoxColor(float d) { if (d > (radiusMajor * radiusMajor) - 5) { r = 1.0f; g = 0.0f; b = 0.0f; } else { r = 0.0f; g = 1.0f; b = 0.0f; } } bool isInside() { double d = euclideanDistance(p1.X, p1.Y, p2.X, p2.Y); changeBBoxColor(d); return d <= radiusMajor * radiusMajor; } void initialize() { glDisable(GL_TEXTURE_2D); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_LIGHTING); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Circulo maior. p1.X = 150; p1.Y = 150; // Circulo menor. p2.X = 150; p2.Y = 150; box.minX = p1.X + calculateX(315, radiusMajor); box.maxX = p1.X + calculateX(225, radiusMajor); box.minY = p1.Y + calculateY(225, radiusMajor); box.maxY = p1.Y + calculateY(135, radiusMajor); } void zoom_in() { ZOOM = ZOOM + 5 * 100 / 400; } void zoom_out() { ZOOM = ZOOM - 5 * 100 / 400; } void keyboard(unsigned char key, int mousePositionX, int mousePositionY) { switch (key) { case KEY_ESCAPE: exit(0); break; case 'I': case 'i': if (ZOOM < 180) // Inverte { ortho2D_minX += 5.0f; ortho2D_maxX -= 5.0f; ortho2D_minY += 5.0f; ortho2D_maxY -= 5.0f; zoom_in(); cout << "ZOOM: " << ZOOM << "%%\n"; glutPostRedisplay(); } break; case 'O': case 'o': if (ZOOM > 0) { ortho2D_minX -= 5.0f; ortho2D_maxX += 5.0f; ortho2D_minY -= 5.0f; ortho2D_maxY += 5.0f; zoom_out(); cout << "ZOOM: " << ZOOM << "%%\n"; glutPostRedisplay(); } break; case 'E': case 'e': p2.X--; if (!isInside()) { p2.X += 2; } glutPostRedisplay(); break; case 'D': case 'd': p2.X++; if (!isInside()) { p2.X -= 2; } glutPostRedisplay(); break; case 'C': case 'c': p2.Y++; if (!isInside()) { p2.Y -= 2; } glutPostRedisplay(); break; case 'B': case 'b': p2.Y--; if (!isInside()) { p2.Y += 2; } glutPostRedisplay(); break; default: cout << "Invalid key pressed: " << key << "\n"; break; } } void mouse(int button, int state, int x, int y) { isMouseOK = false; // Release mouse button. if (button == 0 && state == GLUT_UP) { p2.X = 150; p2.Y = 150; r = 0.0f; g = 1.0f; b = 0.0f; glutPostRedisplay(); } else if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { float dx = (x * 2) - width, dy = (y * -2) + height; double d = euclideanDistance(p2.X, p2.Y, dx, dy); isMouseOK = d <= radiusMinor * radiusMinor; } } void motion(int x, int y) { if (!isMouseOK) return; float oldX = p2.X, oldY = p2.Y; p2.X = (x * 2) - width; p2.Y = (y * -2) + height; if (!isInside()) { p2.X = oldX; p2.Y = oldY; } glutPostRedisplay(); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowPosition(300, 250); glutInitWindowSize(width, height); glutCreateWindow("N2 - Exercicio 6"); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutMouseFunc(mouse); glutMotionFunc(motion); initialize(); glutMainLoop(); return 0; } <commit_msg>Use bbox to check mouse position.<commit_after>#ifdef WIN32 #include <windows.h> #endif #include "base.h" #include <iostream> using namespace std; GLint width = 400, height = 400; GLfloat ortho2D_minX = -400.0f, ortho2D_maxX = 400.0f, ortho2D_minY = -400.0f, ortho2D_maxY = 400.0f; Point p1, p2; BBox box; GLfloat radiusMajor = 120.0f, radiusMinor = 40.0f; int ZOOM = 100; // BBox color. float r = 0.0f, g = 1.0f, b = 0.0f; bool isMouseOK = false; void display() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluOrtho2D(ortho2D_minX, ortho2D_maxX, ortho2D_minY, ortho2D_maxY); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Eixo X e Y. DrawXYAxes(); glColor3f(0.0, 0.0, 0.0); glLineWidth(1.2f); // Circulo maior. DrawCircle(p1.X, p1.Y, radiusMajor, 250); // BBox circulo maior. glColor3f(r, g, b); glLineWidth(1.0f); DrawRectangle(box.minX, box.maxX, box.minY, box.maxY); glColor3f(0.0, 0.0, 0.0); // Circulo menor. DrawCircle(p2.X, p2.Y, radiusMinor, 250); // Ponto no centro do circulo menor. glPointSize(4.0f); glBegin(GL_POINTS); glVertex2f(p2.X, p2.Y); glEnd(); glutSwapBuffers(); } bool isInside() { if (p2.X < box.minX && p2.X > box.maxX && p2.Y > box.minY && p2.Y < box.maxY) { r = 0.0f; g = 1.0f; b = 0.0f; return true; } double d = euclideanDistance(p1.X, p1.Y, p2.X, p2.Y); bool outRadius = d <= radiusMajor * radiusMajor; // Fora da BBox e Dentro do raio. if (outRadius) { r = 1.0f; g = 1.0f; b = 0.0f; } else { r = 1.0f; g = 0.0f; b = 0.0f; } return outRadius; } void initialize() { glDisable(GL_TEXTURE_2D); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_LIGHTING); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Circulo maior. p1.X = 150; p1.Y = 150; // Circulo menor. p2.X = 150; p2.Y = 150; box.minX = p1.X + calculateX(315, radiusMajor); box.maxX = p1.X + calculateX(225, radiusMajor); box.minY = p1.Y + calculateY(225, radiusMajor); box.maxY = p1.Y + calculateY(135, radiusMajor); } void zoom_in() { ZOOM = ZOOM + 5 * 100 / 400; } void zoom_out() { ZOOM = ZOOM - 5 * 100 / 400; } void keyboard(unsigned char key, int mousePositionX, int mousePositionY) { switch (key) { case KEY_ESCAPE: exit(0); break; case 'I': case 'i': if (ZOOM < 180) // Inverte { ortho2D_minX += 5.0f; ortho2D_maxX -= 5.0f; ortho2D_minY += 5.0f; ortho2D_maxY -= 5.0f; zoom_in(); cout << "ZOOM: " << ZOOM << "%%\n"; glutPostRedisplay(); } break; case 'O': case 'o': if (ZOOM > 0) { ortho2D_minX -= 5.0f; ortho2D_maxX += 5.0f; ortho2D_minY -= 5.0f; ortho2D_maxY += 5.0f; zoom_out(); cout << "ZOOM: " << ZOOM << "%%\n"; glutPostRedisplay(); } break; case 'E': case 'e': p2.X--; if (!isInside()) { p2.X += 2; } glutPostRedisplay(); break; case 'D': case 'd': p2.X++; if (!isInside()) { p2.X -= 2; } glutPostRedisplay(); break; case 'C': case 'c': p2.Y++; if (!isInside()) { p2.Y -= 2; } glutPostRedisplay(); break; case 'B': case 'b': p2.Y--; if (!isInside()) { p2.Y += 2; } glutPostRedisplay(); break; default: cout << "Invalid key pressed: " << key << "\n"; break; } } void mouse(int button, int state, int x, int y) { isMouseOK = false; // Release mouse button. if (/*button == 0 && */state == GLUT_UP) { p2.X = 150; p2.Y = 150; r = 0.0f; g = 1.0f; b = 0.0f; glutPostRedisplay(); } else if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { isMouseOK = true; } } void motion(int x, int y) { if (!isMouseOK) return; float oldX = p2.X, oldY = p2.Y; p2.X = (x * 2) - width; p2.Y = (y * -2) + height; if (!isInside()) { p2.X = oldX; p2.Y = oldY; } glutPostRedisplay(); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowPosition(300, 250); glutInitWindowSize(width, height); glutCreateWindow("N2 - Exercicio 6"); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutMouseFunc(mouse); glutMotionFunc(motion); initialize(); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>#include "Engine.h" #include "Game.h" #include "ObjectDummy.h" #include "BodyRigid.h" #include "BodyDummy.h" #ifdef MEMORY_INFO #define new new(__FILE__, __LINE__) #endif // MEMORY_INFO using namespace MathLib; /* */ #define ACTOR_BASE_IFPS (1.0f / 60.0f) #define ACTOR_BASE_CLAMP 89.9f #define ACTOR_BASE_COLLISIONS 4 /* */ CActorBase::CActorBase() { m_vUp = vec3(0.0f, 0.0f, 1.0f); m_pObject = new CObjectDummy(); m_pDummy = new CBodyDummy(); m_pShape = new CShapeCapsule(1.0f, 1.0f); m_nFlush = 0; m_vPosition = Vec3_zero; m_vVelocity = Vec3_zero; m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ for (int i = 0; i < NUM_STATES; i++) { m_pStates[i] = 0; m_pTimes[i] = 0.0f; } m_pDummy->SetEnabled(1); m_pObject->SetBody(NULL); m_pObject->SetBody(m_pDummy); m_pShape->SetBody(NULL); m_pShape->SetBody(m_pDummy); m_pObject->SetWorldTransform(Get_Body_Transform()); m_pShape->SetRestitution(0.0f); m_pShape->SetCollisionMask(2); SetEnabled(1); SetViewDirection(vec3(0.0f,1.0f,0.0f)); SetCollision(1); SetCollisionRadius(0.3f); SetCollisionHeight(1.0f); SetFriction(2.0f); SetMinVelocity(2.0f); SetMaxVelocity(4.0f); SetAcceleration(8.0f); SetDamping(8.0f); SetJumping(1.5f); SetGround(0); SetCeiling(0); } CActorBase::~CActorBase() { m_pDummy->SetObject(NULL); delete m_pObject; delete m_pDummy; }<commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "Engine.h" #include "Game.h" #include "ObjectDummy.h" #include "BodyRigid.h" #include "BodyDummy.h" #include "Physics.h" #include "ShapeCapsule.h" #include "ActorBase.h" #include "Visualizer.h" #include "sys/SysControl.h" #ifdef MEMORY_INFO #define new new(__FILE__, __LINE__) #endif // MEMORY_INFO using namespace MathLib; /* */ #define ACTOR_BASE_IFPS (1.0f / 60.0f) #define ACTOR_BASE_CLAMP 89.9f #define ACTOR_BASE_COLLISIONS 4 /* */ CActorBase::CActorBase() { m_vUp = vec3(0.0f, 0.0f, 1.0f); m_pObject = new CObjectDummy(); m_pDummy = new CBodyDummy(); m_pShape = new CShapeCapsule(1.0f, 1.0f); m_nFlush = 0; m_vPosition = Vec3_zero; m_vVelocity = Vec3_zero; m_fPhiAngle = 0.0f; //б άƽϵУֱYķX֮ļн m_fThetaAngle = 0.0f; //λǣ뵱ǰ˳ʱ߹ĽǶ for (int i = 0; i < NUM_STATES; i++) { m_pStates[i] = 0; m_pTimes[i] = 0.0f; } m_pDummy->SetEnabled(1); m_pObject->SetBody(NULL); m_pObject->SetBody(m_pDummy); m_pShape->SetBody(NULL); m_pShape->SetBody(m_pDummy); m_pObject->SetWorldTransform(Get_Body_Transform()); m_pShape->SetRestitution(0.0f); m_pShape->SetCollisionMask(2); SetEnabled(1); SetViewDirection(vec3(0.0f,1.0f,0.0f)); SetCollision(1); SetCollisionRadius(0.3f); SetCollisionHeight(1.0f); SetFriction(2.0f); SetMinVelocity(2.0f); SetMaxVelocity(4.0f); SetAcceleration(8.0f); SetDamping(8.0f); SetJumping(1.5f); SetGround(0); SetCeiling(0); } CActorBase::~CActorBase() { m_pDummy->SetObject(NULL); delete m_pObject; delete m_pDummy; }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dockingareadefaultacceptor.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-03-01 19:35:29 $ * * 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): _______________________________________ * * ************************************************************************/ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_HELPER_DOCKINGAREADEFAULTACCEPTOR_HXX_ #include <helper/dockingareadefaultacceptor.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_ #include <threadhelp/resetableguard.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_AWT_XDEVICE_HPP_ #include <com/sun/star/awt/XDevice.hpp> #endif #ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_ #include <com/sun/star/awt/PosSize.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XLAYOUTCONSTRAINS_HPP_ #include <com/sun/star/awt/XLayoutConstrains.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ using namespace ::com::sun::star::container ; using namespace ::com::sun::star::frame ; using namespace ::com::sun::star::lang ; using namespace ::com::sun::star::uno ; using namespace ::cppu ; using namespace ::osl ; using namespace ::rtl ; //_________________________________________________________________________________________________________________ // non exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // non exported definitions //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // declarations //_________________________________________________________________________________________________________________ //***************************************************************************************************************** // constructor //***************************************************************************************************************** DockingAreaDefaultAcceptor::DockingAreaDefaultAcceptor( const Reference< XFrame >& xOwner ) // Init baseclasses first : OWeakObject ( ) // Init member , m_xOwner ( xOwner ) { } //***************************************************************************************************************** // destructor //***************************************************************************************************************** DockingAreaDefaultAcceptor::~DockingAreaDefaultAcceptor() { } //***************************************************************************************************************** // XInterface, XTypeProvider //***************************************************************************************************************** DEFINE_XINTERFACE_2( DockingAreaDefaultAcceptor , OWeakObject , DIRECT_INTERFACE(XTypeProvider ) , DIRECT_INTERFACE(::com::sun::star::ui::XDockingAreaAcceptor ) ) DEFINE_XTYPEPROVIDER_2( DockingAreaDefaultAcceptor , XTypeProvider , ::com::sun::star::ui::XDockingAreaAcceptor ) //***************************************************************************************************************** // XDockingAreaAcceptor //***************************************************************************************************************** css::uno::Reference< css::awt::XWindow > SAL_CALL DockingAreaDefaultAcceptor::getContainerWindow() throw (css::uno::RuntimeException) { // Ready for multithreading ResetableGuard aGuard( m_aLock ); // Try to "lock" the frame for access to taskscontainer. Reference< XFrame > xFrame( m_xOwner.get(), UNO_QUERY ); Reference< css::awt::XWindow > xContainerWindow( xFrame->getContainerWindow() ); return xContainerWindow; } sal_Bool SAL_CALL DockingAreaDefaultAcceptor::requestDockingAreaSpace( const css::awt::Rectangle& RequestedSpace ) throw (css::uno::RuntimeException) { // Ready for multithreading ResetableGuard aGuard( m_aLock ); // Try to "lock" the frame for access to taskscontainer. Reference< XFrame > xFrame( m_xOwner.get(), UNO_QUERY ); if ( xFrame.is() == sal_True ) { Reference< css::awt::XWindow > xContainerWindow( xFrame->getContainerWindow() ); Reference< css::awt::XWindow > xComponentWindow( xFrame->getComponentWindow() ); if (( xContainerWindow.is() == sal_True ) && ( xComponentWindow.is() == sal_True ) ) { css::uno::Reference< css::awt::XDevice > xDevice( xContainerWindow, css::uno::UNO_QUERY ); // Convert relativ size to output size. css::awt::Rectangle aRectangle = xContainerWindow->getPosSize(); css::awt::DeviceInfo aInfo = xDevice->getInfo(); css::awt::Size aSize ( aRectangle.Width - aInfo.LeftInset - aInfo.RightInset , aRectangle.Height - aInfo.TopInset - aInfo.BottomInset ); // client size of container window // css::uno::Reference< css::awt::XLayoutConstrains > xLayoutContrains( xComponentWindow, css::uno::UNO_QUERY ); css::awt::Size aMinSize( 0, 0 ); // = xLayoutContrains->getMinimumSize(); // Check if request border space would decrease component window size below minimum size if ((( aSize.Width - RequestedSpace.X - RequestedSpace.Width ) < aMinSize.Width ) || (( aSize.Height - RequestedSpace.Y - RequestedSpace.Height ) < aMinSize.Height ) ) return sal_False; return sal_True; } } return sal_False; } void SAL_CALL DockingAreaDefaultAcceptor::setDockingAreaSpace( const css::awt::Rectangle& BorderSpace ) throw (css::uno::RuntimeException) { // Ready for multithreading ResetableGuard aGuard( m_aLock ); // Try to "lock" the frame for access to taskscontainer. Reference< XFrame > xFrame( m_xOwner.get(), UNO_QUERY ); if ( xFrame.is() == sal_True ) { Reference< css::awt::XWindow > xContainerWindow( xFrame->getContainerWindow() ); Reference< css::awt::XWindow > xComponentWindow( xFrame->getComponentWindow() ); if (( xContainerWindow.is() == sal_True ) && ( xComponentWindow.is() == sal_True ) ) { css::uno::Reference< css::awt::XDevice > xDevice( xContainerWindow, css::uno::UNO_QUERY ); // Convert relativ size to output size. css::awt::Rectangle aRectangle = xContainerWindow->getPosSize(); css::awt::DeviceInfo aInfo = xDevice->getInfo(); css::awt::Size aSize ( aRectangle.Width - aInfo.LeftInset - aInfo.RightInset , aRectangle.Height - aInfo.TopInset - aInfo.BottomInset ); // client size of container window // css::uno::Reference< css::awt::XLayoutConstrains > xLayoutContrains( xComponentWindow, css::uno::UNO_QUERY ); css::awt::Size aMinSize( 0, 0 );// = xLayoutContrains->getMinimumSize(); // Check if request border space would decrease component window size below minimum size sal_Int32 nWidth = aSize.Width - BorderSpace.X - BorderSpace.Width; sal_Int32 nHeight = aSize.Height - BorderSpace.Y - BorderSpace.Height; if (( nWidth > aMinSize.Width ) && ( nHeight > aMinSize.Height )) { // Resize our component window. xComponentWindow->setPosSize( BorderSpace.X, BorderSpace.Y, nWidth, nHeight, css::awt::PosSize::POSSIZE ); } } } } } // namespace framework <commit_msg>INTEGRATION: CWS ooo19126 (1.3.128); FILE MERGED 2005/09/05 13:06:21 rt 1.3.128.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dockingareadefaultacceptor.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:23:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_HELPER_DOCKINGAREADEFAULTACCEPTOR_HXX_ #include <helper/dockingareadefaultacceptor.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_ #include <threadhelp/resetableguard.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_AWT_XDEVICE_HPP_ #include <com/sun/star/awt/XDevice.hpp> #endif #ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_ #include <com/sun/star/awt/PosSize.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XLAYOUTCONSTRAINS_HPP_ #include <com/sun/star/awt/XLayoutConstrains.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ using namespace ::com::sun::star::container ; using namespace ::com::sun::star::frame ; using namespace ::com::sun::star::lang ; using namespace ::com::sun::star::uno ; using namespace ::cppu ; using namespace ::osl ; using namespace ::rtl ; //_________________________________________________________________________________________________________________ // non exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // non exported definitions //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // declarations //_________________________________________________________________________________________________________________ //***************************************************************************************************************** // constructor //***************************************************************************************************************** DockingAreaDefaultAcceptor::DockingAreaDefaultAcceptor( const Reference< XFrame >& xOwner ) // Init baseclasses first : OWeakObject ( ) // Init member , m_xOwner ( xOwner ) { } //***************************************************************************************************************** // destructor //***************************************************************************************************************** DockingAreaDefaultAcceptor::~DockingAreaDefaultAcceptor() { } //***************************************************************************************************************** // XInterface, XTypeProvider //***************************************************************************************************************** DEFINE_XINTERFACE_2( DockingAreaDefaultAcceptor , OWeakObject , DIRECT_INTERFACE(XTypeProvider ) , DIRECT_INTERFACE(::com::sun::star::ui::XDockingAreaAcceptor ) ) DEFINE_XTYPEPROVIDER_2( DockingAreaDefaultAcceptor , XTypeProvider , ::com::sun::star::ui::XDockingAreaAcceptor ) //***************************************************************************************************************** // XDockingAreaAcceptor //***************************************************************************************************************** css::uno::Reference< css::awt::XWindow > SAL_CALL DockingAreaDefaultAcceptor::getContainerWindow() throw (css::uno::RuntimeException) { // Ready for multithreading ResetableGuard aGuard( m_aLock ); // Try to "lock" the frame for access to taskscontainer. Reference< XFrame > xFrame( m_xOwner.get(), UNO_QUERY ); Reference< css::awt::XWindow > xContainerWindow( xFrame->getContainerWindow() ); return xContainerWindow; } sal_Bool SAL_CALL DockingAreaDefaultAcceptor::requestDockingAreaSpace( const css::awt::Rectangle& RequestedSpace ) throw (css::uno::RuntimeException) { // Ready for multithreading ResetableGuard aGuard( m_aLock ); // Try to "lock" the frame for access to taskscontainer. Reference< XFrame > xFrame( m_xOwner.get(), UNO_QUERY ); if ( xFrame.is() == sal_True ) { Reference< css::awt::XWindow > xContainerWindow( xFrame->getContainerWindow() ); Reference< css::awt::XWindow > xComponentWindow( xFrame->getComponentWindow() ); if (( xContainerWindow.is() == sal_True ) && ( xComponentWindow.is() == sal_True ) ) { css::uno::Reference< css::awt::XDevice > xDevice( xContainerWindow, css::uno::UNO_QUERY ); // Convert relativ size to output size. css::awt::Rectangle aRectangle = xContainerWindow->getPosSize(); css::awt::DeviceInfo aInfo = xDevice->getInfo(); css::awt::Size aSize ( aRectangle.Width - aInfo.LeftInset - aInfo.RightInset , aRectangle.Height - aInfo.TopInset - aInfo.BottomInset ); // client size of container window // css::uno::Reference< css::awt::XLayoutConstrains > xLayoutContrains( xComponentWindow, css::uno::UNO_QUERY ); css::awt::Size aMinSize( 0, 0 ); // = xLayoutContrains->getMinimumSize(); // Check if request border space would decrease component window size below minimum size if ((( aSize.Width - RequestedSpace.X - RequestedSpace.Width ) < aMinSize.Width ) || (( aSize.Height - RequestedSpace.Y - RequestedSpace.Height ) < aMinSize.Height ) ) return sal_False; return sal_True; } } return sal_False; } void SAL_CALL DockingAreaDefaultAcceptor::setDockingAreaSpace( const css::awt::Rectangle& BorderSpace ) throw (css::uno::RuntimeException) { // Ready for multithreading ResetableGuard aGuard( m_aLock ); // Try to "lock" the frame for access to taskscontainer. Reference< XFrame > xFrame( m_xOwner.get(), UNO_QUERY ); if ( xFrame.is() == sal_True ) { Reference< css::awt::XWindow > xContainerWindow( xFrame->getContainerWindow() ); Reference< css::awt::XWindow > xComponentWindow( xFrame->getComponentWindow() ); if (( xContainerWindow.is() == sal_True ) && ( xComponentWindow.is() == sal_True ) ) { css::uno::Reference< css::awt::XDevice > xDevice( xContainerWindow, css::uno::UNO_QUERY ); // Convert relativ size to output size. css::awt::Rectangle aRectangle = xContainerWindow->getPosSize(); css::awt::DeviceInfo aInfo = xDevice->getInfo(); css::awt::Size aSize ( aRectangle.Width - aInfo.LeftInset - aInfo.RightInset , aRectangle.Height - aInfo.TopInset - aInfo.BottomInset ); // client size of container window // css::uno::Reference< css::awt::XLayoutConstrains > xLayoutContrains( xComponentWindow, css::uno::UNO_QUERY ); css::awt::Size aMinSize( 0, 0 );// = xLayoutContrains->getMinimumSize(); // Check if request border space would decrease component window size below minimum size sal_Int32 nWidth = aSize.Width - BorderSpace.X - BorderSpace.Width; sal_Int32 nHeight = aSize.Height - BorderSpace.Y - BorderSpace.Height; if (( nWidth > aMinSize.Width ) && ( nHeight > aMinSize.Height )) { // Resize our component window. xComponentWindow->setPosSize( BorderSpace.X, BorderSpace.Y, nWidth, nHeight, css::awt::PosSize::POSSIZE ); } } } } } // namespace framework <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** 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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QGraphicsScene> #include <QGraphicsSceneMouseEvent> #include <QPainter> #include <QStyleOption> #include "edge.h" #include "node.h" #include "graphwidget.h" Node::Node(GraphWidget *graphWidget) : graph(graphWidget) { setFlag(ItemIsMovable); setCacheMode(DeviceCoordinateCache); setZValue(1); } void Node::addEdge(Edge *edge) { edgeList << edge; edge->adjust(); } QList<Edge *> Node::edges() const { return edgeList; } void Node::calculateForces() { if (!scene() || scene()->mouseGrabberItem() == this) { newPos = pos(); return; } // Sum up all forces pushing this item away qreal xvel = 0; qreal yvel = 0; foreach (QGraphicsItem *item, scene()->items()) { Node *node = qgraphicsitem_cast<Node *>(item); if (!node) continue; QLineF line(mapFromItem(node, 0, 0), QPointF(0, 0)); qreal dx = line.dx(); qreal dy = line.dy(); double l = 2.0 * (dx * dx + dy * dy); if (l > 0) { xvel += (dx * 150.0) / l; yvel += (dy * 150.0) / l; } } // Now subtract all forces pulling items together double weight = (edgeList.size() + 1) * 10; foreach (Edge *edge, edgeList) { QPointF pos; if (edge->sourceNode() == this) pos = mapFromItem(edge->destNode(), 0, 0); else pos = mapFromItem(edge->sourceNode(), 0, 0); xvel += pos.x() / weight; yvel += pos.y() / weight; } if (qAbs(xvel) < 0.1 && qAbs(yvel) < 0.1) xvel = yvel = 0; QRectF sceneRect = scene()->sceneRect(); newPos = pos() + QPointF(xvel, yvel); newPos.setX(qMin(qMax(newPos.x(), sceneRect.left() + 10), sceneRect.right() - 10)); newPos.setY(qMin(qMax(newPos.y(), sceneRect.top() + 10), sceneRect.bottom() - 10)); } bool Node::advance() { if (newPos == pos()) return false; setPos(newPos); return true; } QRectF Node::boundingRect() const { qreal adjust = 2; return QRectF(-10 - adjust, -10 - adjust, 23 + adjust, 23 + adjust); } QPainterPath Node::shape() const { QPainterPath path; path.addEllipse(-10, -10, 20, 20); return path; } void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) { painter->setPen(Qt::NoPen); painter->setBrush(Qt::darkGray); painter->drawEllipse(-7, -7, 20, 20); QRadialGradient gradient(-3, -3, 10); if (option->state & QStyle::State_Sunken) { gradient.setCenter(3, 3); gradient.setFocalPoint(3, 3); gradient.setColorAt(1, QColor(Qt::yellow).light(120)); gradient.setColorAt(0, QColor(Qt::darkYellow).light(120)); } else { gradient.setColorAt(0, Qt::yellow); gradient.setColorAt(1, Qt::darkYellow); } painter->setBrush(gradient); painter->setPen(QPen(Qt::black, 0)); painter->drawEllipse(-10, -10, 20, 20); } QVariant Node::itemChange(GraphicsItemChange change, const QVariant &value) { switch (change) { case ItemPositionHasChanged: foreach (Edge *edge, edgeList) edge->adjust(); graph->itemMoved(); break; default: break; }; return QGraphicsItem::itemChange(change, value); } void Node::mousePressEvent(QGraphicsSceneMouseEvent *event) { update(); QGraphicsItem::mousePressEvent(event); } void Node::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { update(); QGraphicsItem::mouseReleaseEvent(event); } <commit_msg>Paint arrow on top of node, not underneath it<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** 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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QGraphicsScene> #include <QGraphicsSceneMouseEvent> #include <QPainter> #include <QStyleOption> #include "edge.h" #include "node.h" #include "graphwidget.h" Node::Node(GraphWidget *graphWidget) : graph(graphWidget) { setFlag(ItemIsMovable); setCacheMode(DeviceCoordinateCache); setZValue(-1); } void Node::addEdge(Edge *edge) { edgeList << edge; edge->adjust(); } QList<Edge *> Node::edges() const { return edgeList; } void Node::calculateForces() { if (!scene() || scene()->mouseGrabberItem() == this) { newPos = pos(); return; } // Sum up all forces pushing this item away qreal xvel = 0; qreal yvel = 0; foreach (QGraphicsItem *item, scene()->items()) { Node *node = qgraphicsitem_cast<Node *>(item); if (!node) continue; QLineF line(mapFromItem(node, 0, 0), QPointF(0, 0)); qreal dx = line.dx(); qreal dy = line.dy(); double l = 2.0 * (dx * dx + dy * dy); if (l > 0) { xvel += (dx * 150.0) / l; yvel += (dy * 150.0) / l; } } // Now subtract all forces pulling items together double weight = (edgeList.size() + 1) * 10; foreach (Edge *edge, edgeList) { QPointF pos; if (edge->sourceNode() == this) pos = mapFromItem(edge->destNode(), 0, 0); else pos = mapFromItem(edge->sourceNode(), 0, 0); xvel += pos.x() / weight; yvel += pos.y() / weight; } if (qAbs(xvel) < 0.1 && qAbs(yvel) < 0.1) xvel = yvel = 0; QRectF sceneRect = scene()->sceneRect(); newPos = pos() + QPointF(xvel, yvel); newPos.setX(qMin(qMax(newPos.x(), sceneRect.left() + 10), sceneRect.right() - 10)); newPos.setY(qMin(qMax(newPos.y(), sceneRect.top() + 10), sceneRect.bottom() - 10)); } bool Node::advance() { if (newPos == pos()) return false; setPos(newPos); return true; } QRectF Node::boundingRect() const { qreal adjust = 2; return QRectF(-10 - adjust, -10 - adjust, 23 + adjust, 23 + adjust); } QPainterPath Node::shape() const { QPainterPath path; path.addEllipse(-10, -10, 20, 20); return path; } void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) { painter->setPen(Qt::NoPen); painter->setBrush(Qt::darkGray); painter->drawEllipse(-7, -7, 20, 20); QRadialGradient gradient(-3, -3, 10); if (option->state & QStyle::State_Sunken) { gradient.setCenter(3, 3); gradient.setFocalPoint(3, 3); gradient.setColorAt(1, QColor(Qt::yellow).light(120)); gradient.setColorAt(0, QColor(Qt::darkYellow).light(120)); } else { gradient.setColorAt(0, Qt::yellow); gradient.setColorAt(1, Qt::darkYellow); } painter->setBrush(gradient); painter->setPen(QPen(Qt::black, 0)); painter->drawEllipse(-10, -10, 20, 20); } QVariant Node::itemChange(GraphicsItemChange change, const QVariant &value) { switch (change) { case ItemPositionHasChanged: foreach (Edge *edge, edgeList) edge->adjust(); graph->itemMoved(); break; default: break; }; return QGraphicsItem::itemChange(change, value); } void Node::mousePressEvent(QGraphicsSceneMouseEvent *event) { update(); QGraphicsItem::mousePressEvent(event); } void Node::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { update(); QGraphicsItem::mouseReleaseEvent(event); } <|endoftext|>
<commit_before>#include "OSGWidget.hh" #include <osg/Camera> #include <osg/Geode> #include <osg/Shape> #include <osg/ShapeDrawable> #include <osgGA/EventQueue> #include <osgGA/TrackballManipulator> #include <osgViewer/View> #include <osgViewer/ViewerEventHandlers> #include <stdexcept> OSGWidget::OSGWidget( QWidget* parent, const QGLWidget* shareWidget, Qt::WindowFlags f ) : QGLWidget( parent, shareWidget, f ), graphicsWindow_( new osgViewer::GraphicsWindowEmbedded( this->x(), this->y(), this->width(), this->height() ) ), viewer_( new osgViewer::CompositeViewer ) { osg::Sphere* sphere = new osg::Sphere( osg::Vec3( 0.f, 0.f, 0.f ), 0.25f ); osg::ShapeDrawable* sd = new osg::ShapeDrawable( sphere ); sd->setColor( osg::Vec4( 1.f, 0.f, 0.f, 1.f ) ); osg::Geode* geode = new osg::Geode; geode->addDrawable( sd ); osg::Camera* camera = new osg::Camera; camera->setViewport( 0, 0, this->width(), this->height() ); camera->setClearColor( osg::Vec4( 0.f, 0.f, 1.f, 1.f ) ); camera->setProjectionMatrixAsFrustum( -1.0, 1.0, -1.0, 1.0, -1.0, 1.0 ); camera->setGraphicsContext( graphicsWindow_ ); osgViewer::View* view = new osgViewer::View; view->setCamera( camera ); view->setSceneData( geode ); view->addEventHandler( new osgViewer::StatsHandler ); view->setCameraManipulator( new osgGA::TrackballManipulator ); viewer_->addView( view ); viewer_->setThreadingModel( osgViewer::CompositeViewer::SingleThreaded ); } OSGWidget::~OSGWidget() { } void OSGWidget::paintGL() { viewer_->frame(); } void OSGWidget::resizeGL( int width, int height ) { this->getEventQueue()->windowResize( this->x(), this->y(), width, height ); graphicsWindow_->resized( this->x(), this->y(), width, height ); } void OSGWidget::keyPressEvent( QKeyEvent* event ) { QString keyString = event->text(); const char* keyData = keyString.toAscii().data(); this->getEventQueue()->keyPress( osgGA::GUIEventAdapter::KeySymbol( *keyData ) ); } void OSGWidget::keyReleaseEvent( QKeyEvent* event ) { QString keyString = event->text(); const char* keyData = keyString.toAscii().data(); this->getEventQueue()->keyRelease( osgGA::GUIEventAdapter::KeySymbol( *keyData ) ); } void OSGWidget::mouseMoveEvent( QMouseEvent* event ) { this->getEventQueue()->mouseMotion( static_cast<float>( event->x() ), static_cast<float>( event->y() ) ); } void OSGWidget::mousePressEvent( QMouseEvent* event ) { // 1 = left mouse button // 2 = middle mouse button // 3 = right mouse button unsigned int button = 0; switch( event->button() ) { case Qt::LeftButton: button = 1; break; case Qt::MiddleButton: button = 2; break; case Qt::RightButton: button = 3; break; default: break; } this->getEventQueue()->mouseButtonPress( static_cast<float>( event->x() ), static_cast<float>( event->y() ), button ); } void OSGWidget::mouseReleaseEvent(QMouseEvent* event) { // 1 = left mouse button // 2 = middle mouse button // 3 = right mouse button unsigned int button = 0; switch( event->button() ) { case Qt::LeftButton: button = 1; break; case Qt::MiddleButton: button = 2; break; case Qt::RightButton: button = 3; break; default: break; } this->getEventQueue()->mouseButtonRelease( static_cast<float>( event->x() ), static_cast<float>( event->y() ), button ); } bool OSGWidget::event( QEvent* event ) { bool handled = QGLWidget::event( event ); // This ensures that the OSG widget is always going to be repainted after the // user performed some interaction. Doing this in the event handler ensures // that we don't forget about some event and prevents duplicate code. switch( event->type() ) { case QEvent::KeyPress: case QEvent::KeyRelease: case QEvent::MouseButtonDblClick: case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseMove: this->repaint(); break; default: break; } return( handled ); } osgGA::EventQueue* OSGWidget::getEventQueue() const { osgGA::EventQueue* eventQueue = graphicsWindow_->getEventQueue(); if( eventQueue ) return( eventQueue ); else throw( std::runtime_error( "Unable to obtain valid event queue") ); } <commit_msg>Attempting to trace scene problems<commit_after>#include "OSGWidget.hh" #include <osg/Camera> #include <osg/Geode> #include <osg/Shape> #include <osg/ShapeDrawable> #include <osgGA/EventQueue> #include <osgGA/TrackballManipulator> #include <osgViewer/View> #include <osgViewer/ViewerEventHandlers> #include <stdexcept> #include <vector> #include <QDebug> OSGWidget::OSGWidget( QWidget* parent, const QGLWidget* shareWidget, Qt::WindowFlags f ) : QGLWidget( parent, shareWidget, f ), graphicsWindow_( new osgViewer::GraphicsWindowEmbedded( this->x(), this->y(), this->width(), this->height() ) ), viewer_( new osgViewer::CompositeViewer ) { osg::Sphere* sphere = new osg::Sphere( osg::Vec3( 0.f, 0.f, 0.f ), 0.25f ); osg::ShapeDrawable* sd = new osg::ShapeDrawable( sphere ); sd->setColor( osg::Vec4( 1.f, 0.f, 0.f, 1.f ) ); osg::Geode* geode = new osg::Geode; geode->addDrawable( sd ); osg::Camera* camera = new osg::Camera; camera->setViewport( 0, 0, this->width(), this->height() ); camera->setClearColor( osg::Vec4( 0.f, 0.f, 1.f, 1.f ) ); camera->setProjectionMatrixAsFrustum( -1.0, 1.0, -1.0, 1.0, -1.0, 1.0 ); camera->setGraphicsContext( graphicsWindow_ ); osgViewer::View* view = new osgViewer::View; view->setCamera( camera ); view->setSceneData( geode ); view->addEventHandler( new osgViewer::StatsHandler ); view->setCameraManipulator( new osgGA::TrackballManipulator ); viewer_->addView( view ); viewer_->setThreadingModel( osgViewer::CompositeViewer::SingleThreaded ); } OSGWidget::~OSGWidget() { } void OSGWidget::paintGL() { viewer_->frame(); } void OSGWidget::resizeGL( int width, int height ) { qDebug() << __PRETTY_FUNCTION__ << ":" << "width =" << width << "height =" << height; std::vector<osg::Camera*> cameras; viewer_->getCameras( cameras ); for( std::size_t i = 0; i < cameras.size(); i++ ) { cameras.at( i )->setViewport( 0, 0, width, height ); } this->getEventQueue()->windowResize( this->x(), this->y(), width, height ); graphicsWindow_->resized( this->x(), this->y(), width, height ); } void OSGWidget::keyPressEvent( QKeyEvent* event ) { QString keyString = event->text(); const char* keyData = keyString.toAscii().data(); this->getEventQueue()->keyPress( osgGA::GUIEventAdapter::KeySymbol( *keyData ) ); } void OSGWidget::keyReleaseEvent( QKeyEvent* event ) { QString keyString = event->text(); const char* keyData = keyString.toAscii().data(); this->getEventQueue()->keyRelease( osgGA::GUIEventAdapter::KeySymbol( *keyData ) ); } void OSGWidget::mouseMoveEvent( QMouseEvent* event ) { this->getEventQueue()->mouseMotion( static_cast<float>( event->x() ), static_cast<float>( event->y() ) ); } void OSGWidget::mousePressEvent( QMouseEvent* event ) { // 1 = left mouse button // 2 = middle mouse button // 3 = right mouse button unsigned int button = 0; switch( event->button() ) { case Qt::LeftButton: button = 1; break; case Qt::MiddleButton: button = 2; break; case Qt::RightButton: button = 3; break; default: break; } this->getEventQueue()->mouseButtonPress( static_cast<float>( event->x() ), static_cast<float>( event->y() ), button ); } void OSGWidget::mouseReleaseEvent(QMouseEvent* event) { // 1 = left mouse button // 2 = middle mouse button // 3 = right mouse button unsigned int button = 0; switch( event->button() ) { case Qt::LeftButton: button = 1; break; case Qt::MiddleButton: button = 2; break; case Qt::RightButton: button = 3; break; default: break; } this->getEventQueue()->mouseButtonRelease( static_cast<float>( event->x() ), static_cast<float>( event->y() ), button ); } bool OSGWidget::event( QEvent* event ) { bool handled = QGLWidget::event( event ); // This ensures that the OSG widget is always going to be repainted after the // user performed some interaction. Doing this in the event handler ensures // that we don't forget about some event and prevents duplicate code. switch( event->type() ) { case QEvent::KeyPress: case QEvent::KeyRelease: case QEvent::MouseButtonDblClick: case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseMove: this->repaint(); break; default: break; } return( handled ); } osgGA::EventQueue* OSGWidget::getEventQueue() const { osgGA::EventQueue* eventQueue = graphicsWindow_->getEventQueue(); if( eventQueue ) return( eventQueue ); else throw( std::runtime_error( "Unable to obtain valid event queue") ); } <|endoftext|>
<commit_before><commit_msg>Drop test that require tmp with exec rights.<commit_after><|endoftext|>
<commit_before>/* OpenDeck platform firmware v1.2 Last revision date: 2014-11-18 Author: Igor Petrovic */ #include "OpenDeck.h" #include "MIDI.h" #include "Ownduino.h" //velocity for on and off events #define MIDI_NOTE_ON_VELOCITY 127 #define MIDI_NOTE_OFF_VELOCITY 0 //MIDI callback handlers void getNoteOnData(uint8_t channel, uint8_t note, uint8_t velocity) { openDeck.storeReceivedNoteOn(channel, note, velocity); } void getSysExData(uint8_t *sysExArray, uint8_t size) { openDeck.processSysEx(sysExArray, size); } //OpenDeck callback handlers void sendButtonData(uint8_t buttonNote, bool buttonState, uint8_t channel) { switch (buttonState) { case false: //button released if (openDeck.standardNoteOffEnabled()) MIDI.sendNoteOff(buttonNote, MIDI_NOTE_OFF_VELOCITY, channel); else MIDI.sendNoteOn(buttonNote, MIDI_NOTE_OFF_VELOCITY, channel); break; case true: //button pressed MIDI.sendNoteOn(buttonNote, MIDI_NOTE_ON_VELOCITY, channel); break; } } void sendPotCCData(uint8_t ccNumber, uint8_t ccValue, uint8_t channel) { MIDI.sendControlChange(ccNumber, ccValue, channel); } void sendPotNoteOnData(uint8_t note, uint8_t channel) { MIDI.sendNoteOn(note, MIDI_NOTE_ON_VELOCITY, channel); } void sendPotNoteOffData(uint8_t note, uint8_t channel) { if (openDeck.standardNoteOffEnabled()) MIDI.sendNoteOff(note, MIDI_NOTE_OFF_VELOCITY, channel); else MIDI.sendNoteOn(note, MIDI_NOTE_OFF_VELOCITY, channel); } void sendSysExData(uint8_t *sysExArray, uint8_t size) { MIDI.sendSysEx(size, sysExArray, false); } //configure opendeck library void setOpenDeckHandlers() { openDeck.setHandleButtonSend(sendButtonData); openDeck.setHandlePotCC(sendPotCCData); openDeck.setHandlePotNoteOn(sendPotNoteOnData); openDeck.setHandlePotNoteOff(sendPotNoteOffData); openDeck.setHandleSysExSend(sendSysExData); } //set MIDI handlers void setMIDIhandlers() { MIDI.setHandleNoteOn(getNoteOnData); MIDI.setHandleSystemExclusive(getSysExData); } //main void setup() { //initialize openDeck library openDeck.init(); setOpenDeckHandlers(); setMIDIhandlers(); //read incoming MIDI messages on specified channel MIDI.begin(openDeck.getInputMIDIchannel(), openDeck.runningStatusEnabled()); Serial.begin(38400); openDeck.allLEDsOn(); } void loop() { //process buttons and LEDs openDeck.processMatrix(); //constantly check for incoming MIDI messages MIDI.read(); //check if there is any received note to process openDeck.checkReceivedNoteOn(); //read pots one analogue input at the time openDeck.readPots(); }<commit_msg>remove allLEDsOn from setup (debug leftover)<commit_after>/* OpenDeck platform firmware v1.2 Last revision date: 2014-11-18 Author: Igor Petrovic */ #include "OpenDeck.h" #include "MIDI.h" #include "Ownduino.h" //velocity for on and off events #define MIDI_NOTE_ON_VELOCITY 127 #define MIDI_NOTE_OFF_VELOCITY 0 //MIDI callback handlers void getNoteOnData(uint8_t channel, uint8_t note, uint8_t velocity) { openDeck.storeReceivedNoteOn(channel, note, velocity); } void getSysExData(uint8_t *sysExArray, uint8_t size) { openDeck.processSysEx(sysExArray, size); } //OpenDeck callback handlers void sendButtonData(uint8_t buttonNote, bool buttonState, uint8_t channel) { switch (buttonState) { case false: //button released if (openDeck.standardNoteOffEnabled()) MIDI.sendNoteOff(buttonNote, MIDI_NOTE_OFF_VELOCITY, channel); else MIDI.sendNoteOn(buttonNote, MIDI_NOTE_OFF_VELOCITY, channel); break; case true: //button pressed MIDI.sendNoteOn(buttonNote, MIDI_NOTE_ON_VELOCITY, channel); break; } } void sendPotCCData(uint8_t ccNumber, uint8_t ccValue, uint8_t channel) { MIDI.sendControlChange(ccNumber, ccValue, channel); } void sendPotNoteOnData(uint8_t note, uint8_t channel) { MIDI.sendNoteOn(note, MIDI_NOTE_ON_VELOCITY, channel); } void sendPotNoteOffData(uint8_t note, uint8_t channel) { if (openDeck.standardNoteOffEnabled()) MIDI.sendNoteOff(note, MIDI_NOTE_OFF_VELOCITY, channel); else MIDI.sendNoteOn(note, MIDI_NOTE_OFF_VELOCITY, channel); } void sendSysExData(uint8_t *sysExArray, uint8_t size) { MIDI.sendSysEx(size, sysExArray, false); } //configure opendeck library void setOpenDeckHandlers() { openDeck.setHandleButtonSend(sendButtonData); openDeck.setHandlePotCC(sendPotCCData); openDeck.setHandlePotNoteOn(sendPotNoteOnData); openDeck.setHandlePotNoteOff(sendPotNoteOffData); openDeck.setHandleSysExSend(sendSysExData); } //set MIDI handlers void setMIDIhandlers() { MIDI.setHandleNoteOn(getNoteOnData); MIDI.setHandleSystemExclusive(getSysExData); } //main void setup() { //initialize openDeck library openDeck.init(); setOpenDeckHandlers(); setMIDIhandlers(); //read incoming MIDI messages on specified channel MIDI.begin(openDeck.getInputMIDIchannel(), openDeck.runningStatusEnabled()); Serial.begin(38400); } void loop() { //process buttons and LEDs openDeck.processMatrix(); //constantly check for incoming MIDI messages MIDI.read(); //check if there is any received note to process openDeck.checkReceivedNoteOn(); //read pots one analogue input at the time openDeck.readPots(); }<|endoftext|>
<commit_before>// // Created by mathias on 6/9/16. // #include "flightControl/blindFlight.h" #include "OpenCv/CV_Handler.h" #define NUM_THREADS 4 #define LOOP_RATE (50) void *controlThread(void *thread_arg); void *buttonThread(void *thread_arg); void *cvThread(void *thread_arg); void *navdataThread(void *thread_Arg); bool started = false; FlightController *controller; CV_Handler *cvHandler; Nav *navdata; struct thread_data { int argc; char **argv; }; struct thread_data td[NUM_THREADS]; int main(int argc, char **argv){ td[0].argc = argc; td[0].argv = argv; ros::init(argc, argv, "blindFlight"); ros::NodeHandle n; controller = new FlightController(LOOP_RATE, n); cvHandler = new CV_Handler(); navdata = new Nav(n); pthread_t threads[NUM_THREADS]; pthread_create(&threads[0], NULL, buttonThread, &td[0]); pthread_create(&threads[1], NULL, cvThread, &td[1]); pthread_create(&threads[2], NULL, navdataThread, &td[2]); ros::spin(); pthread_exit(NULL); } void *controlThread(void *thread_arg){ controller->run(navdata, cvHandler); started = false; pthread_exit(NULL); } void *navdataThread(void *thread_arg){ navdata->run(); pthread_exit(NULL); } void *buttonThread(void *thread_arg) { struct thread_data *thread_data; thread_data = (struct thread_data *) thread_arg; // Creating Control panel QApplication a(thread_data->argc, thread_data->argv); ControlPanel w; w.show(); a.exec(); pthread_exit(NULL); } void *cvThread(void *thread_arg) { cvHandler->run(); pthread_exit(NULL); } void blindFlight::abortProgram(void) { ROS_INFO("MANUEL ABORT!"); controller->land(); } void blindFlight::resetProgram(void) { ROS_INFO("MANUEL RESET!"); controller->reset(); } void blindFlight::startProgram(void) { if (!started) { ROS_INFO("STARTING!"); pthread_t thread; pthread_create(&thread, NULL, controlThread, &td[0]); started = true; } }<commit_msg>Removed stupid include<commit_after>// // Created by mathias on 6/9/16. // #include <QApplication> #include "OpenCv/CV_Handler.h" #include "flightControl/FlightController.h" #include "GUI/ControlPanel/controlpanel.h" #define NUM_THREADS 4 #define LOOP_RATE (50) void *controlThread(void *thread_arg); void *buttonThread(void *thread_arg); void *cvThread(void *thread_arg); void *navdataThread(void *thread_Arg); bool started = false; FlightController *controller; CV_Handler *cvHandler; Nav *navdata; struct thread_data { int argc; char **argv; }; struct thread_data td[NUM_THREADS]; int main(int argc, char **argv){ td[0].argc = argc; td[0].argv = argv; ros::init(argc, argv, "blindFlight"); ros::NodeHandle n; controller = new FlightController(LOOP_RATE, n); cvHandler = new CV_Handler(); navdata = new Nav(n); pthread_t threads[NUM_THREADS]; pthread_create(&threads[0], NULL, buttonThread, &td[0]); pthread_create(&threads[1], NULL, cvThread, &td[1]); pthread_create(&threads[2], NULL, navdataThread, &td[2]); ros::spin(); pthread_exit(NULL); } void *controlThread(void *thread_arg){ controller->run(navdata, cvHandler); started = false; pthread_exit(NULL); } void *navdataThread(void *thread_arg){ navdata->run(); pthread_exit(NULL); } void *buttonThread(void *thread_arg) { struct thread_data *thread_data; thread_data = (struct thread_data *) thread_arg; // Creating Control panel QApplication a(thread_data->argc, thread_data->argv); ControlPanel w; w.show(); a.exec(); pthread_exit(NULL); } void *cvThread(void *thread_arg) { cvHandler->run(); pthread_exit(NULL); } void blindFlight::abortProgram(void) { ROS_INFO("MANUEL ABORT!"); controller->land(); } void blindFlight::resetProgram(void) { ROS_INFO("MANUEL RESET!"); controller->reset(); } void blindFlight::startProgram(void) { if (!started) { ROS_INFO("STARTING!"); pthread_t thread; pthread_create(&thread, NULL, controlThread, &td[0]); started = true; } }<|endoftext|>
<commit_before>// Copyright(c) 2015-present, Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) #ifndef SPDLOG_COMPILED_LIB #error Please define SPDLOG_COMPILED_LIB to compile this file. #endif #include "spdlog/spdlog-inl.h" #include "spdlog/common-inl.h" #include "spdlog/details/backtracer-inl.h" #include "spdlog/details/registry-inl.h" #include "spdlog/details/os-inl.h" #include "spdlog/details/pattern_formatter-inl.h" #include "spdlog/details/log_msg-inl.h" #include "spdlog/details/log_msg_buffer-inl.h" #include "spdlog/logger-inl.h" #include "spdlog/sinks/sink-inl.h" // template instantiate logger with sinks init list template spdlog::logger::logger(std::string name, sinks_init_list::iterator begin, sinks_init_list::iterator end); <commit_msg>Update spdlog.cpp<commit_after>// Copyright(c) 2015-present, Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) #ifndef SPDLOG_COMPILED_LIB #error Please define SPDLOG_COMPILED_LIB to compile this file. #endif #include "spdlog/spdlog-inl.h" #include "spdlog/common-inl.h" #include "spdlog/details/backtracer-inl.h" #include "spdlog/details/registry-inl.h" #include "spdlog/details/os-inl.h" #include "spdlog/details/pattern_formatter-inl.h" #include "spdlog/details/log_msg-inl.h" #include "spdlog/details/log_msg_buffer-inl.h" #include "spdlog/logger-inl.h" #include "spdlog/sinks/sink-inl.h" // template instantiate logger constructor with sinks init list template spdlog::logger::logger(std::string name, sinks_init_list::iterator begin, sinks_init_list::iterator end); <|endoftext|>
<commit_before>// // StaticAnalyser.cpp // Clock Signal // // Created by Thomas Harte on 23/08/2016. // Copyright © 2016 Thomas Harte. All rights reserved. // #include "StaticAnalyser.hpp" #include <cstdlib> // Analysers #include "Acorn/StaticAnalyser.hpp" #include "AmstradCPC/StaticAnalyser.hpp" #include "Atari/StaticAnalyser.hpp" #include "Commodore/StaticAnalyser.hpp" #include "Oric/StaticAnalyser.hpp" #include "ZX8081/StaticAnalyser.hpp" // Cartridges #include "../Storage/Cartridge/Formats/BinaryDump.hpp" #include "../Storage/Cartridge/Formats/PRG.hpp" // Disks #include "../Storage/Disk/Formats/AcornADF.hpp" #include "../Storage/Disk/Formats/CPCDSK.hpp" #include "../Storage/Disk/Formats/D64.hpp" #include "../Storage/Disk/Formats/G64.hpp" #include "../Storage/Disk/Formats/HFE.hpp" #include "../Storage/Disk/Formats/OricMFMDSK.hpp" #include "../Storage/Disk/Formats/SSD.hpp" // Tapes #include "../Storage/Tape/Formats/CommodoreTAP.hpp" #include "../Storage/Tape/Formats/CSW.hpp" #include "../Storage/Tape/Formats/OricTAP.hpp" #include "../Storage/Tape/Formats/TapePRG.hpp" #include "../Storage/Tape/Formats/TapeUEF.hpp" #include "../Storage/Tape/Formats/TZX.hpp" #include "../Storage/Tape/Formats/ZX80O81P.hpp" // Target Platform Types #include "../Storage/TargetPlatforms.hpp" using namespace StaticAnalyser; static Media GetMediaAndPlatforms(const char *file_name, TargetPlatform::IntType &potential_platforms) { // Get the extension, if any; it will be assumed that extensions are reliable, so an extension is a broad-phase // test as to file format. const char *mixed_case_extension = strrchr(file_name, '.'); char *lowercase_extension = nullptr; if(mixed_case_extension) { lowercase_extension = strdup(mixed_case_extension+1); char *parser = lowercase_extension; while(*parser) { *parser = (char)tolower(*parser); parser++; } } Media result; #define Insert(list, class, platforms) \ list.emplace_back(new Storage::class(file_name));\ potential_platforms |= platforms;\ #define TryInsert(list, class, platforms) \ try {\ Insert(list, class, platforms) \ } catch(...) {} #define Format(extension, list, class, platforms) \ if(!strcmp(lowercase_extension, extension)) { \ TryInsert(list, class, platforms) \ } if(lowercase_extension) { Format("80", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // 80 Format("81", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // 81 Format("a26", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Atari2600) // A26 Format("adf", result.disks, Disk::AcornADF, TargetPlatform::Acorn) // ADF Format("bin", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Atari2600) // BIN Format("cdt", result.tapes, Tape::TZX, TargetPlatform::AmstradCPC) // CDT Format("csw", result.tapes, Tape::CSW, TargetPlatform::AllTape) // CSW Format("d64", result.disks, Disk::D64, TargetPlatform::Commodore) // D64 Format("dsd", result.disks, Disk::SSD, TargetPlatform::Acorn) // DSD Format("dsk", result.disks, Disk::CPCDSK, TargetPlatform::AmstradCPC) // DSK (Amstrad CPC) Format("dsk", result.disks, Disk::OricMFMDSK, TargetPlatform::Oric) // DSK (Oric) Format("g64", result.disks, Disk::G64, TargetPlatform::Commodore) // G64 Format("hfe", result.disks, Disk::HFE, TargetPlatform::AmstradCPC) // HFE (TODO: plus other target platforms) Format("o", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // O Format("p", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // P Format("p81", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // P81 // PRG if(!strcmp(lowercase_extension, "prg")) { // try instantiating as a ROM; failing that accept as a tape try { Insert(result.cartridges, Cartridge::PRG, TargetPlatform::Commodore) } catch(...) { try { Insert(result.tapes, Tape::PRG, TargetPlatform::Commodore) } catch(...) {} } } Format("rom", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Acorn) // ROM Format("ssd", result.disks, Disk::SSD, TargetPlatform::Acorn) // SSD Format("tap", result.tapes, Tape::CommodoreTAP, TargetPlatform::Commodore) // TAP (Commodore) Format("tap", result.tapes, Tape::OricTAP, TargetPlatform::Oric) // TAP (Oric) Format("tzx", result.tapes, Tape::TZX, TargetPlatform::ZX8081) // TZX Format("uef", result.tapes, Tape::UEF, TargetPlatform::Acorn) // UEF (tape) #undef Format #undef Insert #undef TryInsert free(lowercase_extension); } return result; } Media StaticAnalyser::GetMedia(const char *file_name) { TargetPlatform::IntType throwaway; return GetMediaAndPlatforms(file_name, throwaway); } std::list<Target> StaticAnalyser::GetTargets(const char *file_name) { std::list<Target> targets; // Collect all disks, tapes and ROMs as can be extrapolated from this file, forming the // union of all platforms this file might be a target for. TargetPlatform::IntType potential_platforms = 0; Media media = GetMediaAndPlatforms(file_name, potential_platforms); // Hand off to platform-specific determination of whether these things are actually compatible and, // if so, how to load them. if(potential_platforms & TargetPlatform::Acorn) Acorn::AddTargets(media, targets); if(potential_platforms & TargetPlatform::AmstradCPC) AmstradCPC::AddTargets(media, targets); if(potential_platforms & TargetPlatform::Atari2600) Atari::AddTargets(media, targets); if(potential_platforms & TargetPlatform::Commodore) Commodore::AddTargets(media, targets); if(potential_platforms & TargetPlatform::Oric) Oric::AddTargets(media, targets); if(potential_platforms & TargetPlatform::ZX8081) ZX8081::AddTargets(media, targets); // Reset any tapes to their initial position for(auto target : targets) { for(auto tape : media.tapes) { tape->reset(); } } return targets; } <commit_msg>Uses file containers' type distinguishers where available, and supplies potential insight to the ZX80/81 analyser as now required.<commit_after>// // StaticAnalyser.cpp // Clock Signal // // Created by Thomas Harte on 23/08/2016. // Copyright © 2016 Thomas Harte. All rights reserved. // #include "StaticAnalyser.hpp" #include <cstdlib> // Analysers #include "Acorn/StaticAnalyser.hpp" #include "AmstradCPC/StaticAnalyser.hpp" #include "Atari/StaticAnalyser.hpp" #include "Commodore/StaticAnalyser.hpp" #include "Oric/StaticAnalyser.hpp" #include "ZX8081/StaticAnalyser.hpp" // Cartridges #include "../Storage/Cartridge/Formats/BinaryDump.hpp" #include "../Storage/Cartridge/Formats/PRG.hpp" // Disks #include "../Storage/Disk/Formats/AcornADF.hpp" #include "../Storage/Disk/Formats/CPCDSK.hpp" #include "../Storage/Disk/Formats/D64.hpp" #include "../Storage/Disk/Formats/G64.hpp" #include "../Storage/Disk/Formats/HFE.hpp" #include "../Storage/Disk/Formats/OricMFMDSK.hpp" #include "../Storage/Disk/Formats/SSD.hpp" // Tapes #include "../Storage/Tape/Formats/CommodoreTAP.hpp" #include "../Storage/Tape/Formats/CSW.hpp" #include "../Storage/Tape/Formats/OricTAP.hpp" #include "../Storage/Tape/Formats/TapePRG.hpp" #include "../Storage/Tape/Formats/TapeUEF.hpp" #include "../Storage/Tape/Formats/TZX.hpp" #include "../Storage/Tape/Formats/ZX80O81P.hpp" // Target Platform Types #include "../Storage/TargetPlatforms.hpp" using namespace StaticAnalyser; static Media GetMediaAndPlatforms(const char *file_name, TargetPlatform::IntType &potential_platforms) { // Get the extension, if any; it will be assumed that extensions are reliable, so an extension is a broad-phase // test as to file format. const char *mixed_case_extension = strrchr(file_name, '.'); char *lowercase_extension = nullptr; if(mixed_case_extension) { lowercase_extension = strdup(mixed_case_extension+1); char *parser = lowercase_extension; while(*parser) { *parser = (char)tolower(*parser); parser++; } } Media result; #define Insert(list, class, platforms) \ list.emplace_back(new Storage::class(file_name));\ potential_platforms |= platforms;\ TargetPlatform::TypeDistinguisher *distinguisher = dynamic_cast<TargetPlatform::TypeDistinguisher *>(list.back().get());\ if(distinguisher) potential_platforms &= distinguisher->target_platform_type(); #define TryInsert(list, class, platforms) \ try {\ Insert(list, class, platforms) \ } catch(...) {} #define Format(extension, list, class, platforms) \ if(!strcmp(lowercase_extension, extension)) { \ TryInsert(list, class, platforms) \ } if(lowercase_extension) { Format("80", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // 80 Format("81", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // 81 Format("a26", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Atari2600) // A26 Format("adf", result.disks, Disk::AcornADF, TargetPlatform::Acorn) // ADF Format("bin", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Atari2600) // BIN Format("cdt", result.tapes, Tape::TZX, TargetPlatform::AmstradCPC) // CDT Format("csw", result.tapes, Tape::CSW, TargetPlatform::AllTape) // CSW Format("d64", result.disks, Disk::D64, TargetPlatform::Commodore) // D64 Format("dsd", result.disks, Disk::SSD, TargetPlatform::Acorn) // DSD Format("dsk", result.disks, Disk::CPCDSK, TargetPlatform::AmstradCPC) // DSK (Amstrad CPC) Format("dsk", result.disks, Disk::OricMFMDSK, TargetPlatform::Oric) // DSK (Oric) Format("g64", result.disks, Disk::G64, TargetPlatform::Commodore) // G64 Format("hfe", result.disks, Disk::HFE, TargetPlatform::AmstradCPC) // HFE (TODO: plus other target platforms) Format("o", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // O Format("p", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // P Format("p81", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // P81 // PRG if(!strcmp(lowercase_extension, "prg")) { // try instantiating as a ROM; failing that accept as a tape try { Insert(result.cartridges, Cartridge::PRG, TargetPlatform::Commodore) } catch(...) { try { Insert(result.tapes, Tape::PRG, TargetPlatform::Commodore) } catch(...) {} } } Format("rom", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Acorn) // ROM Format("ssd", result.disks, Disk::SSD, TargetPlatform::Acorn) // SSD Format("tap", result.tapes, Tape::CommodoreTAP, TargetPlatform::Commodore) // TAP (Commodore) Format("tap", result.tapes, Tape::OricTAP, TargetPlatform::Oric) // TAP (Oric) Format("tzx", result.tapes, Tape::TZX, TargetPlatform::ZX8081) // TZX Format("uef", result.tapes, Tape::UEF, TargetPlatform::Acorn) // UEF (tape) #undef Format #undef Insert #undef TryInsert // Filter potential platforms as per file preferences, if any. free(lowercase_extension); } return result; } Media StaticAnalyser::GetMedia(const char *file_name) { TargetPlatform::IntType throwaway; return GetMediaAndPlatforms(file_name, throwaway); } std::list<Target> StaticAnalyser::GetTargets(const char *file_name) { std::list<Target> targets; // Collect all disks, tapes and ROMs as can be extrapolated from this file, forming the // union of all platforms this file might be a target for. TargetPlatform::IntType potential_platforms = 0; Media media = GetMediaAndPlatforms(file_name, potential_platforms); // Hand off to platform-specific determination of whether these things are actually compatible and, // if so, how to load them. if(potential_platforms & TargetPlatform::Acorn) Acorn::AddTargets(media, targets); if(potential_platforms & TargetPlatform::AmstradCPC) AmstradCPC::AddTargets(media, targets); if(potential_platforms & TargetPlatform::Atari2600) Atari::AddTargets(media, targets); if(potential_platforms & TargetPlatform::Commodore) Commodore::AddTargets(media, targets); if(potential_platforms & TargetPlatform::Oric) Oric::AddTargets(media, targets); if(potential_platforms & TargetPlatform::ZX8081) ZX8081::AddTargets(media, targets, potential_platforms); // Reset any tapes to their initial position for(auto target : targets) { for(auto tape : media.tapes) { tape->reset(); } } return targets; } <|endoftext|>
<commit_before>/*************************************************************************/ /* editor_log.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "editor_log.h" #include "core/os/keyboard.h" #include "core/version.h" #include "editor_node.h" #include "editor_scale.h" #include "scene/gui/center_container.h" #include "scene/resources/dynamic_font.h" void EditorLog::_error_handler(void *p_self, const char *p_func, const char *p_file, int p_line, const char *p_error, const char *p_errorexp, ErrorHandlerType p_type) { EditorLog *self = (EditorLog *)p_self; if (self->current != Thread::get_caller_id()) return; String err_str; if (p_errorexp && p_errorexp[0]) { err_str = p_errorexp; } else { err_str = String(p_file) + ":" + itos(p_line) + " - " + String(p_error); } if (p_type == ERR_HANDLER_WARNING) { self->add_message(err_str, MSG_TYPE_WARNING); } else { self->add_message(err_str, MSG_TYPE_ERROR); } } void EditorLog::_notification(int p_what) { if (p_what == NOTIFICATION_ENTER_TREE) { //button->set_icon(get_icon("Console","EditorIcons")); log->add_font_override("normal_font", get_font("output_source", "EditorFonts")); } else if (p_what == NOTIFICATION_THEME_CHANGED) { Ref<DynamicFont> df_output_code = get_font("output_source", "EditorFonts"); if (df_output_code.is_valid()) { if (log != NULL) { log->add_font_override("normal_font", get_font("output_source", "EditorFonts")); } } } } void EditorLog::_clear_request() { log->clear(); tool_button->set_icon(Ref<Texture>()); } void EditorLog::_copy_request() { log->selection_copy(); } void EditorLog::clear() { _clear_request(); } void EditorLog::copy() { _copy_request(); } void EditorLog::add_message(const String &p_msg, MessageType p_type) { log->add_newline(); bool restore = p_type != MSG_TYPE_STD; switch (p_type) { case MSG_TYPE_STD: { } break; case MSG_TYPE_ERROR: { log->push_color(get_color("error_color", "Editor")); Ref<Texture> icon = get_icon("Error", "EditorIcons"); log->add_image(icon); log->add_text(" "); tool_button->set_icon(icon); } break; case MSG_TYPE_WARNING: { log->push_color(get_color("warning_color", "Editor")); Ref<Texture> icon = get_icon("Warning", "EditorIcons"); log->add_image(icon); log->add_text(" "); tool_button->set_icon(icon); } break; case MSG_TYPE_EDITOR: { // Distinguish editor messages from messages printed by the project log->push_color(get_color("font_color", "Editor") * Color(1, 1, 1, 0.6)); } break; } log->add_text(p_msg); if (restore) log->pop(); } void EditorLog::set_tool_button(ToolButton *p_tool_button) { tool_button = p_tool_button; } void EditorLog::_undo_redo_cbk(void *p_self, const String &p_name) { EditorLog *self = (EditorLog *)p_self; self->add_message(p_name, EditorLog::MSG_TYPE_EDITOR); } void EditorLog::_bind_methods() { ClassDB::bind_method(D_METHOD("_clear_request"), &EditorLog::_clear_request); ClassDB::bind_method(D_METHOD("_copy_request"), &EditorLog::_copy_request); ADD_SIGNAL(MethodInfo("clear_request")); ADD_SIGNAL(MethodInfo("copy_request")); } EditorLog::EditorLog() { VBoxContainer *vb = this; HBoxContainer *hb = memnew(HBoxContainer); vb->add_child(hb); title = memnew(Label); title->set_text(TTR("Output:")); title->set_h_size_flags(SIZE_EXPAND_FILL); hb->add_child(title); copybutton = memnew(Button); hb->add_child(copybutton); copybutton->set_text(TTR("Copy")); copybutton->set_shortcut(ED_SHORTCUT("editor/copy_output", TTR("Copy Selection"), KEY_MASK_CMD | KEY_C)); copybutton->connect("pressed", this, "_copy_request"); clearbutton = memnew(Button); hb->add_child(clearbutton); clearbutton->set_text(TTR("Clear")); clearbutton->set_shortcut(ED_SHORTCUT("editor/clear_output", TTR("Clear Output"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_K)); clearbutton->connect("pressed", this, "_clear_request"); log = memnew(RichTextLabel); log->set_scroll_follow(true); log->set_selection_enabled(true); log->set_focus_mode(FOCUS_CLICK); log->set_custom_minimum_size(Size2(0, 180) * EDSCALE); log->set_v_size_flags(SIZE_EXPAND_FILL); log->set_h_size_flags(SIZE_EXPAND_FILL); vb->add_child(log); add_message(VERSION_FULL_NAME " (c) 2007-2020 Juan Linietsky, Ariel Manzur & Godot Contributors."); eh.errfunc = _error_handler; eh.userdata = this; add_error_handler(&eh); current = Thread::get_caller_id(); add_constant_override("separation", get_constant("separation", "VBoxContainer")); EditorNode::get_undo_redo()->set_commit_notify_callback(_undo_redo_cbk, this); } void EditorLog::deinit() { remove_error_handler(&eh); } EditorLog::~EditorLog() { } <commit_msg>Tweak the editor log selection color to match the current editor theme<commit_after>/*************************************************************************/ /* editor_log.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "editor_log.h" #include "core/os/keyboard.h" #include "core/version.h" #include "editor_node.h" #include "editor_scale.h" #include "scene/gui/center_container.h" #include "scene/resources/dynamic_font.h" void EditorLog::_error_handler(void *p_self, const char *p_func, const char *p_file, int p_line, const char *p_error, const char *p_errorexp, ErrorHandlerType p_type) { EditorLog *self = (EditorLog *)p_self; if (self->current != Thread::get_caller_id()) return; String err_str; if (p_errorexp && p_errorexp[0]) { err_str = p_errorexp; } else { err_str = String(p_file) + ":" + itos(p_line) + " - " + String(p_error); } if (p_type == ERR_HANDLER_WARNING) { self->add_message(err_str, MSG_TYPE_WARNING); } else { self->add_message(err_str, MSG_TYPE_ERROR); } } void EditorLog::_notification(int p_what) { if (p_what == NOTIFICATION_ENTER_TREE) { //button->set_icon(get_icon("Console","EditorIcons")); log->add_font_override("normal_font", get_font("output_source", "EditorFonts")); log->add_color_override("selection_color", get_color("accent_color", "Editor") * Color(1, 1, 1, 0.4)); } else if (p_what == NOTIFICATION_THEME_CHANGED) { Ref<DynamicFont> df_output_code = get_font("output_source", "EditorFonts"); if (df_output_code.is_valid()) { if (log != NULL) { log->add_font_override("normal_font", get_font("output_source", "EditorFonts")); log->add_color_override("selection_color", get_color("accent_color", "Editor") * Color(1, 1, 1, 0.4)); } } } } void EditorLog::_clear_request() { log->clear(); tool_button->set_icon(Ref<Texture>()); } void EditorLog::_copy_request() { log->selection_copy(); } void EditorLog::clear() { _clear_request(); } void EditorLog::copy() { _copy_request(); } void EditorLog::add_message(const String &p_msg, MessageType p_type) { log->add_newline(); bool restore = p_type != MSG_TYPE_STD; switch (p_type) { case MSG_TYPE_STD: { } break; case MSG_TYPE_ERROR: { log->push_color(get_color("error_color", "Editor")); Ref<Texture> icon = get_icon("Error", "EditorIcons"); log->add_image(icon); log->add_text(" "); tool_button->set_icon(icon); } break; case MSG_TYPE_WARNING: { log->push_color(get_color("warning_color", "Editor")); Ref<Texture> icon = get_icon("Warning", "EditorIcons"); log->add_image(icon); log->add_text(" "); tool_button->set_icon(icon); } break; case MSG_TYPE_EDITOR: { // Distinguish editor messages from messages printed by the project log->push_color(get_color("font_color", "Editor") * Color(1, 1, 1, 0.6)); } break; } log->add_text(p_msg); if (restore) log->pop(); } void EditorLog::set_tool_button(ToolButton *p_tool_button) { tool_button = p_tool_button; } void EditorLog::_undo_redo_cbk(void *p_self, const String &p_name) { EditorLog *self = (EditorLog *)p_self; self->add_message(p_name, EditorLog::MSG_TYPE_EDITOR); } void EditorLog::_bind_methods() { ClassDB::bind_method(D_METHOD("_clear_request"), &EditorLog::_clear_request); ClassDB::bind_method(D_METHOD("_copy_request"), &EditorLog::_copy_request); ADD_SIGNAL(MethodInfo("clear_request")); ADD_SIGNAL(MethodInfo("copy_request")); } EditorLog::EditorLog() { VBoxContainer *vb = this; HBoxContainer *hb = memnew(HBoxContainer); vb->add_child(hb); title = memnew(Label); title->set_text(TTR("Output:")); title->set_h_size_flags(SIZE_EXPAND_FILL); hb->add_child(title); copybutton = memnew(Button); hb->add_child(copybutton); copybutton->set_text(TTR("Copy")); copybutton->set_shortcut(ED_SHORTCUT("editor/copy_output", TTR("Copy Selection"), KEY_MASK_CMD | KEY_C)); copybutton->connect("pressed", this, "_copy_request"); clearbutton = memnew(Button); hb->add_child(clearbutton); clearbutton->set_text(TTR("Clear")); clearbutton->set_shortcut(ED_SHORTCUT("editor/clear_output", TTR("Clear Output"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_K)); clearbutton->connect("pressed", this, "_clear_request"); log = memnew(RichTextLabel); log->set_scroll_follow(true); log->set_selection_enabled(true); log->set_focus_mode(FOCUS_CLICK); log->set_custom_minimum_size(Size2(0, 180) * EDSCALE); log->set_v_size_flags(SIZE_EXPAND_FILL); log->set_h_size_flags(SIZE_EXPAND_FILL); vb->add_child(log); add_message(VERSION_FULL_NAME " (c) 2007-2020 Juan Linietsky, Ariel Manzur & Godot Contributors."); eh.errfunc = _error_handler; eh.userdata = this; add_error_handler(&eh); current = Thread::get_caller_id(); add_constant_override("separation", get_constant("separation", "VBoxContainer")); EditorNode::get_undo_redo()->set_commit_notify_callback(_undo_redo_cbk, this); } void EditorLog::deinit() { remove_error_handler(&eh); } EditorLog::~EditorLog() { } <|endoftext|>
<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // 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 <Trigger.hpp> void trigger(const bool subbandDedispersion, const unsigned int padding, const unsigned int integration, const float threshold, const AstroData::Observation & observation, const std::vector<float> & snrData, const std::vector<unsigned int> & samplesData, TriggeredEvents & triggeredEvents) { unsigned int nrDMs = 0; if ( subbandDedispersion ) { nrDMs = observation.getNrDMs(true) * observation.getNrDMs(); } else { nrDMs = observation.getNrDMs(); } #pragma omp parallel for for ( unsigned int beam = 0; beam < observation.getNrSynthesizedBeams(); beam++ ) { for ( unsigned int dm = 0; dm < nrDMs; dm++ ) { if ( snrData[(beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm] >= threshold ) { TriggeredEvent event; event.beam = beam; event.sample = samplesData[(beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm]; event.integration = integration; event.DM = dm; event.SNR = snrData[(beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm]; try { // Add event to its existing list triggeredEvents.at(beam).at(dm).push_back(event); } catch ( std::out_of_range err ) { // Add event to new list std::vector<TriggeredEvent> events; events.push_back(event); triggeredEvents.at(beam).insert(std::pair<unsigned int, std::vector<TriggeredEvent>>(dm, events)); } } } } } void compact(const AstroData::Observation & observation, const TriggeredEvents & triggeredEvents, CompactedEvents & compactedEvents) { CompactedEvents temporaryEvents(observation.getNrSynthesizedBeams()); // Compact integration for ( auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents ) { for ( auto dmEvents = beamEvents->begin(); dmEvents != beamEvents->end(); ++dmEvents ) { CompactedEvent event; for ( auto dmEvent = dmEvents->second.begin(); dmEvent != dmEvents->second.end(); ++dmEvent ) { if ( dmEvent->SNR > event.SNR ) { event.beam = dmEvent->beam; event.sample = dmEvent->sample; event.integration = dmEvent->integration; event.DM = dmEvent->DM; event.SNR = dmEvent->SNR; } } event.compactedIntegration = dmEvents->second.size(); temporaryEvents.at(event.beam).push_back(event); } } // Compact DM for ( auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents ) { for ( auto event = beamEvents->begin(); event != beamEvents->end(); ++event ) { CompactedEvent finalEvent; unsigned int window = 0; while ( (event->DM + window) == (event + window)->DM ) { if ( (event + window)->SNR > finalEvent.SNR ) { finalEvent.beam = (event + window)->beam; finalEvent.sample = (event + window)->sample; finalEvent.integration = (event + window)->integration; finalEvent.compactedIntegration = (event + window)->compactedIntegration; finalEvent.DM = (event + window)->DM; finalEvent.SNR = (event + window)->SNR; } window++; } finalEvent.compactedDMs = window; compactedEvents.at(finalEvent.beam).push_back(finalEvent); // Move the iterator forward event += (window - 1); } } } <commit_msg>Removed linter warning.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // 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 <Trigger.hpp> void trigger(const bool subbandDedispersion, const unsigned int padding, const unsigned int integration, const float threshold, const AstroData::Observation & observation, const std::vector<float> & snrData, const std::vector<unsigned int> & samplesData, TriggeredEvents & triggeredEvents) { unsigned int nrDMs = 0; if ( subbandDedispersion ) { nrDMs = observation.getNrDMs(true) * observation.getNrDMs(); } else { nrDMs = observation.getNrDMs(); } #pragma omp parallel for for ( unsigned int beam = 0; beam < observation.getNrSynthesizedBeams(); beam++ ) { for ( unsigned int dm = 0; dm < nrDMs; dm++ ) { if ( snrData[(beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm] >= threshold ) { TriggeredEvent event; event.beam = beam; event.sample = samplesData[(beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm]; event.integration = integration; event.DM = dm; event.SNR = snrData[(beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm]; try { // Add event to its existing list triggeredEvents.at(beam).at(dm).push_back(event); } catch ( std::out_of_range & err ) { // Add event to new list std::vector<TriggeredEvent> events; events.push_back(event); triggeredEvents.at(beam).insert(std::pair<unsigned int, std::vector<TriggeredEvent>>(dm, events)); } } } } } void compact(const AstroData::Observation & observation, const TriggeredEvents & triggeredEvents, CompactedEvents & compactedEvents) { CompactedEvents temporaryEvents(observation.getNrSynthesizedBeams()); // Compact integration for ( auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents ) { for ( auto dmEvents = beamEvents->begin(); dmEvents != beamEvents->end(); ++dmEvents ) { CompactedEvent event; for ( auto dmEvent = dmEvents->second.begin(); dmEvent != dmEvents->second.end(); ++dmEvent ) { if ( dmEvent->SNR > event.SNR ) { event.beam = dmEvent->beam; event.sample = dmEvent->sample; event.integration = dmEvent->integration; event.DM = dmEvent->DM; event.SNR = dmEvent->SNR; } } event.compactedIntegration = dmEvents->second.size(); temporaryEvents.at(event.beam).push_back(event); } } // Compact DM for ( auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents ) { for ( auto event = beamEvents->begin(); event != beamEvents->end(); ++event ) { CompactedEvent finalEvent; unsigned int window = 0; while ( (event->DM + window) == (event + window)->DM ) { if ( (event + window)->SNR > finalEvent.SNR ) { finalEvent.beam = (event + window)->beam; finalEvent.sample = (event + window)->sample; finalEvent.integration = (event + window)->integration; finalEvent.compactedIntegration = (event + window)->compactedIntegration; finalEvent.DM = (event + window)->DM; finalEvent.SNR = (event + window)->SNR; } window++; } finalEvent.compactedDMs = window; compactedEvents.at(finalEvent.beam).push_back(finalEvent); // Move the iterator forward event += (window - 1); } } } <|endoftext|>
<commit_before>//===-- ScheduleDAG.cpp - Implement a trivial DAG scheduler ---------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This implements a simple code linearizer for DAGs. This is not a very good // way to emit code, but gets working code quickly. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sched" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/CodeGen/SelectionDAG.h" #include "llvm/CodeGen/SSARegMap.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetLowering.h" #include "llvm/Support/CommandLine.h" using namespace llvm; #ifndef _NDEBUG static cl::opt<bool> ViewDAGs("view-sched-dags", cl::Hidden, cl::desc("Pop up a window to show sched dags as they are processed")); #else static const bool ViewDAGS = 0; #endif namespace { class SimpleSched { SelectionDAG &DAG; MachineBasicBlock *BB; const TargetMachine &TM; const TargetInstrInfo &TII; const MRegisterInfo &MRI; SSARegMap *RegMap; MachineConstantPool *ConstPool; std::map<SDNode *, unsigned> EmittedOps; public: SimpleSched(SelectionDAG &D, MachineBasicBlock *bb) : DAG(D), BB(bb), TM(D.getTarget()), TII(*TM.getInstrInfo()), MRI(*TM.getRegisterInfo()), RegMap(BB->getParent()->getSSARegMap()), ConstPool(BB->getParent()->getConstantPool()) { assert(&TII && "Target doesn't provide instr info?"); assert(&MRI && "Target doesn't provide register info?"); } MachineBasicBlock *Run() { Emit(DAG.getRoot()); return BB; } private: unsigned Emit(SDOperand Op); }; } unsigned SimpleSched::Emit(SDOperand Op) { // Check to see if we have already emitted this. If so, return the value // already emitted. Note that if a node has a single use it cannot be // revisited, so don't bother putting it in the map. unsigned *OpSlot; if (Op.Val->hasOneUse()) { OpSlot = 0; // No reuse possible. } else { std::map<SDNode *, unsigned>::iterator OpI = EmittedOps.lower_bound(Op.Val); if (OpI != EmittedOps.end() && OpI->first == Op.Val) return OpI->second + Op.ResNo; OpSlot = &EmittedOps.insert(OpI, std::make_pair(Op.Val, 0))->second; } unsigned ResultReg = 0; if (Op.isTargetOpcode()) { unsigned Opc = Op.getTargetOpcode(); const TargetInstrDescriptor &II = TII.get(Opc); // The results of target nodes have register or immediate operands first, // then an optional chain, and optional flag operands (which do not go into // the machine instrs). unsigned NumResults = Op.Val->getNumValues(); while (NumResults && Op.Val->getValueType(NumResults-1) == MVT::Flag) --NumResults; if (NumResults && Op.Val->getValueType(NumResults-1) == MVT::Other) --NumResults; // Skip over chain result. // The inputs to target nodes have any actual inputs first, followed by an // optional chain operand, then flag operands. Compute the number of actual // operands that will go into the machine instr. unsigned NodeOperands = Op.getNumOperands(); while (NodeOperands && Op.getOperand(NodeOperands-1).getValueType() == MVT::Flag) --NodeOperands; if (NodeOperands && // Ignore chain if it exists. Op.getOperand(NodeOperands-1).getValueType() == MVT::Other) --NodeOperands; unsigned NumMIOperands = NodeOperands+NumResults; #ifndef _NDEBUG assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&& "#operands for dag node doesn't match .td file!"); #endif // Create the new machine instruction. MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true); // Add result register values for things that are defined by this // instruction. if (NumResults) { // Create the result registers for this node and add the result regs to // the machine instruction. const TargetOperandInfo *OpInfo = II.OpInfo; ResultReg = RegMap->createVirtualRegister(OpInfo[0].RegClass); MI->addRegOperand(ResultReg, MachineOperand::Def); for (unsigned i = 1; i != NumResults; ++i) { assert(OpInfo[i].RegClass && "Isn't a register operand!"); MI->addRegOperand(RegMap->createVirtualRegister(OpInfo[0].RegClass), MachineOperand::Def); } } // If there is a token chain operand, emit it first, as a hack to get avoid // really bad cases. if (Op.getNumOperands() > NodeOperands && Op.getOperand(NodeOperands).getValueType() == MVT::Other) Emit(Op.getOperand(NodeOperands)); // Emit all of the actual operands of this instruction, adding them to the // instruction as appropriate. for (unsigned i = 0; i != NodeOperands; ++i) { if (Op.getOperand(i).isTargetOpcode()) { // Note that this case is redundant with the final else block, but we // include it because it is the most common and it makes the logic // simpler here. assert(Op.getOperand(i).getValueType() != MVT::Other && Op.getOperand(i).getValueType() != MVT::Flag && "Chain and flag operands should occur at end of operand list!"); MI->addRegOperand(Emit(Op.getOperand(i)), MachineOperand::Use); } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(i))) { MI->addZeroExtImm64Operand(C->getValue()); } else if (RegisterSDNode*R =dyn_cast<RegisterSDNode>(Op.getOperand(i))) { MI->addRegOperand(R->getReg(), MachineOperand::Use); } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(i))) { MI->addGlobalAddressOperand(TGA->getGlobal(), false, 0); } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op.getOperand(i))) { MI->addMachineBasicBlockOperand(BB->getBasicBlock()); } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op.getOperand(i))) { MI->addFrameIndexOperand(FI->getIndex()); } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(i))) { unsigned Idx = ConstPool->getConstantPoolIndex(CP->get()); MI->addConstantPoolIndexOperand(Idx); } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op.getOperand(i))) { MI->addExternalSymbolOperand(ES->getSymbol(), false); } else { assert(Op.getOperand(i).getValueType() != MVT::Other && Op.getOperand(i).getValueType() != MVT::Flag && "Chain and flag operands should occur at end of operand list!"); MI->addRegOperand(Emit(Op.getOperand(i)), MachineOperand::Use); } } // Finally, if this node has any flag operands, we *must* emit them last, to // avoid emitting operations that might clobber the flags. if (Op.getNumOperands() > NodeOperands) { unsigned i = NodeOperands; if (Op.getOperand(i).getValueType() == MVT::Other) ++i; // the chain is already selected. for (; i != Op.getNumOperands(); ++i) { assert(Op.getOperand(i).getValueType() == MVT::Flag && "Must be flag operands!"); Emit(Op.getOperand(i)); } } // Now that we have emitted all operands, emit this instruction itself. if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) { BB->insert(BB->end(), MI); } else { // Insert this instruction into the end of the basic block, potentially // taking some custom action. BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB); } } else { switch (Op.getOpcode()) { default: Op.Val->dump(); assert(0 && "This target-independent node should have been selected!"); case ISD::EntryToken: break; case ISD::TokenFactor: for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) Emit(Op.getOperand(i)); break; case ISD::CopyToReg: { Emit(Op.getOperand(0)); // Emit the chain. unsigned Val = Emit(Op.getOperand(2)); MRI.copyRegToReg(*BB, BB->end(), cast<RegisterSDNode>(Op.getOperand(1))->getReg(), Val, RegMap->getRegClass(Val)); break; } case ISD::CopyFromReg: { Emit(Op.getOperand(0)); // Emit the chain. unsigned SrcReg = cast<RegisterSDNode>(Op.getOperand(1))->getReg(); // Figure out the register class to create for the destreg. const TargetRegisterClass *TRC = 0; if (MRegisterInfo::isVirtualRegister(SrcReg)) { TRC = RegMap->getRegClass(SrcReg); } else { // FIXME: we don't know what register class to generate this for. Do // a brute force search and pick the first match. :( for (MRegisterInfo::regclass_iterator I = MRI.regclass_begin(), E = MRI.regclass_end(); I != E; ++I) if ((*I)->contains(SrcReg)) { TRC = *I; break; } assert(TRC && "Couldn't find register class for reg copy!"); } // Create the reg, emit the copy. ResultReg = RegMap->createVirtualRegister(TRC); MRI.copyRegToReg(*BB, BB->end(), ResultReg, SrcReg, TRC); break; } } } if (OpSlot) *OpSlot = ResultReg; return ResultReg+Op.ResNo; } /// Pick a safe ordering and emit instructions for each target node in the /// graph. void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &SD) { if (ViewDAGs) SD.viewGraph(); BB = SimpleSched(SD, BB).Run(); } <commit_msg>Handle CopyToReg nodes with flag operands correctly<commit_after>//===-- ScheduleDAG.cpp - Implement a trivial DAG scheduler ---------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This implements a simple code linearizer for DAGs. This is not a very good // way to emit code, but gets working code quickly. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sched" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/CodeGen/SelectionDAG.h" #include "llvm/CodeGen/SSARegMap.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetLowering.h" #include "llvm/Support/CommandLine.h" using namespace llvm; #ifndef _NDEBUG static cl::opt<bool> ViewDAGs("view-sched-dags", cl::Hidden, cl::desc("Pop up a window to show sched dags as they are processed")); #else static const bool ViewDAGS = 0; #endif namespace { class SimpleSched { SelectionDAG &DAG; MachineBasicBlock *BB; const TargetMachine &TM; const TargetInstrInfo &TII; const MRegisterInfo &MRI; SSARegMap *RegMap; MachineConstantPool *ConstPool; std::map<SDNode *, unsigned> EmittedOps; public: SimpleSched(SelectionDAG &D, MachineBasicBlock *bb) : DAG(D), BB(bb), TM(D.getTarget()), TII(*TM.getInstrInfo()), MRI(*TM.getRegisterInfo()), RegMap(BB->getParent()->getSSARegMap()), ConstPool(BB->getParent()->getConstantPool()) { assert(&TII && "Target doesn't provide instr info?"); assert(&MRI && "Target doesn't provide register info?"); } MachineBasicBlock *Run() { Emit(DAG.getRoot()); return BB; } private: unsigned Emit(SDOperand Op); }; } unsigned SimpleSched::Emit(SDOperand Op) { // Check to see if we have already emitted this. If so, return the value // already emitted. Note that if a node has a single use it cannot be // revisited, so don't bother putting it in the map. unsigned *OpSlot; if (Op.Val->hasOneUse()) { OpSlot = 0; // No reuse possible. } else { std::map<SDNode *, unsigned>::iterator OpI = EmittedOps.lower_bound(Op.Val); if (OpI != EmittedOps.end() && OpI->first == Op.Val) return OpI->second + Op.ResNo; OpSlot = &EmittedOps.insert(OpI, std::make_pair(Op.Val, 0))->second; } unsigned ResultReg = 0; if (Op.isTargetOpcode()) { unsigned Opc = Op.getTargetOpcode(); const TargetInstrDescriptor &II = TII.get(Opc); // The results of target nodes have register or immediate operands first, // then an optional chain, and optional flag operands (which do not go into // the machine instrs). unsigned NumResults = Op.Val->getNumValues(); while (NumResults && Op.Val->getValueType(NumResults-1) == MVT::Flag) --NumResults; if (NumResults && Op.Val->getValueType(NumResults-1) == MVT::Other) --NumResults; // Skip over chain result. // The inputs to target nodes have any actual inputs first, followed by an // optional chain operand, then flag operands. Compute the number of actual // operands that will go into the machine instr. unsigned NodeOperands = Op.getNumOperands(); while (NodeOperands && Op.getOperand(NodeOperands-1).getValueType() == MVT::Flag) --NodeOperands; if (NodeOperands && // Ignore chain if it exists. Op.getOperand(NodeOperands-1).getValueType() == MVT::Other) --NodeOperands; unsigned NumMIOperands = NodeOperands+NumResults; #ifndef _NDEBUG assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&& "#operands for dag node doesn't match .td file!"); #endif // Create the new machine instruction. MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true); // Add result register values for things that are defined by this // instruction. if (NumResults) { // Create the result registers for this node and add the result regs to // the machine instruction. const TargetOperandInfo *OpInfo = II.OpInfo; ResultReg = RegMap->createVirtualRegister(OpInfo[0].RegClass); MI->addRegOperand(ResultReg, MachineOperand::Def); for (unsigned i = 1; i != NumResults; ++i) { assert(OpInfo[i].RegClass && "Isn't a register operand!"); MI->addRegOperand(RegMap->createVirtualRegister(OpInfo[0].RegClass), MachineOperand::Def); } } // If there is a token chain operand, emit it first, as a hack to get avoid // really bad cases. if (Op.getNumOperands() > NodeOperands && Op.getOperand(NodeOperands).getValueType() == MVT::Other) Emit(Op.getOperand(NodeOperands)); // Emit all of the actual operands of this instruction, adding them to the // instruction as appropriate. for (unsigned i = 0; i != NodeOperands; ++i) { if (Op.getOperand(i).isTargetOpcode()) { // Note that this case is redundant with the final else block, but we // include it because it is the most common and it makes the logic // simpler here. assert(Op.getOperand(i).getValueType() != MVT::Other && Op.getOperand(i).getValueType() != MVT::Flag && "Chain and flag operands should occur at end of operand list!"); MI->addRegOperand(Emit(Op.getOperand(i)), MachineOperand::Use); } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(i))) { MI->addZeroExtImm64Operand(C->getValue()); } else if (RegisterSDNode*R =dyn_cast<RegisterSDNode>(Op.getOperand(i))) { MI->addRegOperand(R->getReg(), MachineOperand::Use); } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(i))) { MI->addGlobalAddressOperand(TGA->getGlobal(), false, 0); } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op.getOperand(i))) { MI->addMachineBasicBlockOperand(BB->getBasicBlock()); } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op.getOperand(i))) { MI->addFrameIndexOperand(FI->getIndex()); } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(i))) { unsigned Idx = ConstPool->getConstantPoolIndex(CP->get()); MI->addConstantPoolIndexOperand(Idx); } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op.getOperand(i))) { MI->addExternalSymbolOperand(ES->getSymbol(), false); } else { assert(Op.getOperand(i).getValueType() != MVT::Other && Op.getOperand(i).getValueType() != MVT::Flag && "Chain and flag operands should occur at end of operand list!"); MI->addRegOperand(Emit(Op.getOperand(i)), MachineOperand::Use); } } // Finally, if this node has any flag operands, we *must* emit them last, to // avoid emitting operations that might clobber the flags. if (Op.getNumOperands() > NodeOperands) { unsigned i = NodeOperands; if (Op.getOperand(i).getValueType() == MVT::Other) ++i; // the chain is already selected. for (; i != Op.getNumOperands(); ++i) { assert(Op.getOperand(i).getValueType() == MVT::Flag && "Must be flag operands!"); Emit(Op.getOperand(i)); } } // Now that we have emitted all operands, emit this instruction itself. if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) { BB->insert(BB->end(), MI); } else { // Insert this instruction into the end of the basic block, potentially // taking some custom action. BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB); } } else { switch (Op.getOpcode()) { default: Op.Val->dump(); assert(0 && "This target-independent node should have been selected!"); case ISD::EntryToken: break; case ISD::TokenFactor: for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) Emit(Op.getOperand(i)); break; case ISD::CopyToReg: { SDOperand ChainOp; if (Op.getNumOperands() == 4) ChainOp = Op.getOperand(3); if (Op.getOperand(0).Val != ChainOp.Val) Emit(Op.getOperand(0)); // Emit the chain. unsigned Val = Emit(Op.getOperand(2)); if (ChainOp.Val) Emit(ChainOp); MRI.copyRegToReg(*BB, BB->end(), cast<RegisterSDNode>(Op.getOperand(1))->getReg(), Val, RegMap->getRegClass(Val)); break; } case ISD::CopyFromReg: { Emit(Op.getOperand(0)); // Emit the chain. unsigned SrcReg = cast<RegisterSDNode>(Op.getOperand(1))->getReg(); // Figure out the register class to create for the destreg. const TargetRegisterClass *TRC = 0; if (MRegisterInfo::isVirtualRegister(SrcReg)) { TRC = RegMap->getRegClass(SrcReg); } else { // FIXME: we don't know what register class to generate this for. Do // a brute force search and pick the first match. :( for (MRegisterInfo::regclass_iterator I = MRI.regclass_begin(), E = MRI.regclass_end(); I != E; ++I) if ((*I)->contains(SrcReg)) { TRC = *I; break; } assert(TRC && "Couldn't find register class for reg copy!"); } // Create the reg, emit the copy. ResultReg = RegMap->createVirtualRegister(TRC); MRI.copyRegToReg(*BB, BB->end(), ResultReg, SrcReg, TRC); break; } } } if (OpSlot) *OpSlot = ResultReg; return ResultReg+Op.ResNo; } /// Pick a safe ordering and emit instructions for each target node in the /// graph. void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &SD) { if (ViewDAGs) SD.viewGraph(); BB = SimpleSched(SD, BB).Run(); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <[email protected]> // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "AutoloadingTransform.h" #include "cling/Interpreter/Transaction.h" #include "clang/AST/DeclVisitor.h" using namespace clang; namespace cling { class DeclFixer : public DeclVisitor<DeclFixer> { public: void VisitDecl(Decl* D) { if (DeclContext* DC = dyn_cast<DeclContext>(D)) for (auto Child : DC->decls()) Visit(Child); } void VisitEnumDecl(EnumDecl* ED) { if (ED->isFixed()) { StringRef str = ED->getAttr<AnnotateAttr>()->getAnnotation(); char ch = str.back(); str.drop_back(2); // Missing new[](...) - see clang bug # {yet to come}. // ED->getAttr<AnnotateAttr>()->setAnnotation(ED->getASTContext(), str); struct EnumDeclDerived: public EnumDecl { static void setFixed(EnumDecl* ED, bool value = true) { ((EnumDeclDerived*)ED)->IsFixed = value; } }; if (ch != '1') EnumDeclDerived::setFixed(ED, false); } } }; void AutoloadingTransform::Transform() { const Transaction* T = getTransaction(); if (T->decls_begin() == T->decls_end()) return; DeclGroupRef DGR = T->decls_begin()->m_DGR; if (DGR.isNull()) return; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { DeclFixer visitor; for (Transaction::const_iterator I = T->decls_begin(), E = T->decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; for (DeclGroupRef::iterator J = DCI.m_DGR.begin(), JE = DCI.m_DGR.end(); J != JE; ++J) { visitor.Visit(*J); //FIXME: Enable when safe ! // if ( (*J)->hasAttr<AnnotateAttr>() /*FIXME: && CorrectCallbackLoaded() how ? */ ) // clang::Decl::castToDeclContext(*J)->setHasExternalLexicalStorage(); } } } } } // end namespace cling <commit_msg>interpreter/cling/lib/Interpreter/AutoloadingTransform.cpp<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <[email protected]> // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "AutoloadingTransform.h" #include "cling/Interpreter/Transaction.h" #include "clang/AST/DeclVisitor.h" #include "clang/AST/ASTContext.h" using namespace clang; namespace cling { class DeclFixer : public DeclVisitor<DeclFixer> { public: void VisitDecl(Decl* D) { if (DeclContext* DC = dyn_cast<DeclContext>(D)) for (auto Child : DC->decls()) Visit(Child); } void VisitEnumDecl(EnumDecl* ED) { if (ED->isFixed()) { StringRef str = ED->getAttr<AnnotateAttr>()->getAnnotation(); char ch = str.back(); str.drop_back(2); ED->getAttr<AnnotateAttr>()->setAnnotation(ED->getASTContext(), str); struct EnumDeclDerived: public EnumDecl { static void setFixed(EnumDecl* ED, bool value = true) { ((EnumDeclDerived*)ED)->IsFixed = value; } }; if (ch != '1') EnumDeclDerived::setFixed(ED, false); } } }; void AutoloadingTransform::Transform() { const Transaction* T = getTransaction(); if (T->decls_begin() == T->decls_end()) return; DeclGroupRef DGR = T->decls_begin()->m_DGR; if (DGR.isNull()) return; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { DeclFixer visitor; for (Transaction::const_iterator I = T->decls_begin(), E = T->decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; for (DeclGroupRef::iterator J = DCI.m_DGR.begin(), JE = DCI.m_DGR.end(); J != JE; ++J) { visitor.Visit(*J); //FIXME: Enable when safe ! // if ( (*J)->hasAttr<AnnotateAttr>() /*FIXME: && CorrectCallbackLoaded() how ? */ ) // clang::Decl::castToDeclContext(*J)->setHasExternalLexicalStorage(); } } } } } // end namespace cling <|endoftext|>
<commit_before>/* system.cpp Classic Invaders Copyright (c) 2013, Simon Que All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of The No Quarter Arcade (http://www.noquarterarcade.com/) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "system.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __i386__ #include <SDL/SDL.h> #else ///////////// Begin embedded system definitions //////////////// #include <avr/io.h> #define FOSC 8000000 #define BAUD 9600 #define MYUBRR 12 static int uart_putchar(char c, FILE *stream); static int uart_getchar(FILE *stream); static void init_fdev(FILE* stream, int (*put_func)(char, FILE*), int (*get_func)(FILE*), int flags) { stream->flags = flags; stream->put = put_func; stream->get = get_func; stream->udata = NULL; } static FILE mystdout; static FILE mystdin; static int uart_putchar(char c, FILE *stream) { if (c == '\n') uart_putchar('\r', stream); loop_until_bit_is_set(UCSR0A, UDRE0); UDR0 = c; return 0; } static int uart_getchar(FILE *stream) { while( !(UCSR0A & (1<<RXC0)) ); return(UDR0); } // Initializes AVR UART. static void init_uart() { UBRR0H = MYUBRR >> 8; UBRR0L = MYUBRR; UCSR0B = (1<<TXEN0); UCSR0C = (1<<UCSZ00)|(1<<UCSZ01); DDRE = (1<<PORTE1); stdout = &mystdout; // Required for printf over UART. stdin = &mystdin; // Required for scanf over UART. } // Initializes AVR external memory. static void init_external_memory() { MCUCR = (1<<SRE); XMCRB = (1<<XMBK) | (1<<XMM0); DDRC = 0xff; PORTC = 0; } static void system_init() { init_fdev(&mystdout, uart_putchar, NULL, _FDEV_SETUP_WRITE); init_fdev(&mystdin, NULL, uart_getchar, _FDEV_SETUP_READ); init_uart(); init_external_memory(); } #endif // defined(__i386__) ///////////// End embedded system definitions //////////////// namespace System { bool init() { #ifdef __i386__ atexit(SDL_Quit); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) < 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); return false; } #else system_init(); #endif return true; } KeyState get_key_state() { KeyState key_state; memset(&key_state, 0, sizeof(key_state)); #ifdef __i386__ // Get the current keys from SDL. Call SDL_PollEvent() to update the // key array with the latest values. Uint8* keys = SDL_GetKeyState(NULL); SDL_Event event; while(SDL_PollEvent(&event)); if (keys[SDLK_ESCAPE]) key_state.quit = 1; if (keys[SDLK_p]) key_state.pause = 1; if (keys[SDLK_LEFT]) key_state.left = 1; if (keys[SDLK_RIGHT]) key_state.right = 1; if (keys[SDLK_SPACE]) key_state.fire = 1; #endif // defined(__i386__) return key_state; } // This is just a wrapper around SDL_GetTicks. As part of the embedded port, // its contents will eventually be replaced with something else. uint32_t get_ticks() { uint32_t ticks = 0; #ifdef __i386__ ticks = SDL_GetTicks(); #endif return ticks; } } <commit_msg>system: initialize stderr on AVR<commit_after>/* system.cpp Classic Invaders Copyright (c) 2013, Simon Que All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of The No Quarter Arcade (http://www.noquarterarcade.com/) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "system.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __i386__ #include <SDL/SDL.h> #else ///////////// Begin embedded system definitions //////////////// #include <avr/io.h> #define FOSC 8000000 #define BAUD 9600 #define MYUBRR 12 static int uart_putchar(char c, FILE *stream); static int uart_getchar(FILE *stream); static void init_fdev(FILE* stream, int (*put_func)(char, FILE*), int (*get_func)(FILE*), int flags) { stream->flags = flags; stream->put = put_func; stream->get = get_func; stream->udata = NULL; } static FILE mystdout; static FILE mystdin; static int uart_putchar(char c, FILE *stream) { if (c == '\n') uart_putchar('\r', stream); loop_until_bit_is_set(UCSR0A, UDRE0); UDR0 = c; return 0; } static int uart_getchar(FILE *stream) { while( !(UCSR0A & (1<<RXC0)) ); return(UDR0); } // Initializes AVR UART. static void init_uart() { UBRR0H = MYUBRR >> 8; UBRR0L = MYUBRR; UCSR0B = (1<<TXEN0); UCSR0C = (1<<UCSZ00)|(1<<UCSZ01); DDRE = (1<<PORTE1); stdout = &mystdout; // Required for printf over UART. stderr = &mystdout; // Required for fprintf(stderr) over UART. stdin = &mystdin; // Required for scanf over UART. } // Initializes AVR external memory. static void init_external_memory() { MCUCR = (1<<SRE); XMCRB = (1<<XMBK) | (1<<XMM0); DDRC = 0xff; PORTC = 0; } static void system_init() { init_fdev(&mystdout, uart_putchar, NULL, _FDEV_SETUP_WRITE); init_fdev(&mystdin, NULL, uart_getchar, _FDEV_SETUP_READ); init_uart(); init_external_memory(); } #endif // defined(__i386__) ///////////// End embedded system definitions //////////////// namespace System { bool init() { #ifdef __i386__ atexit(SDL_Quit); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) < 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); return false; } #else system_init(); #endif return true; } KeyState get_key_state() { KeyState key_state; memset(&key_state, 0, sizeof(key_state)); #ifdef __i386__ // Get the current keys from SDL. Call SDL_PollEvent() to update the // key array with the latest values. Uint8* keys = SDL_GetKeyState(NULL); SDL_Event event; while(SDL_PollEvent(&event)); if (keys[SDLK_ESCAPE]) key_state.quit = 1; if (keys[SDLK_p]) key_state.pause = 1; if (keys[SDLK_LEFT]) key_state.left = 1; if (keys[SDLK_RIGHT]) key_state.right = 1; if (keys[SDLK_SPACE]) key_state.fire = 1; #endif // defined(__i386__) return key_state; } // This is just a wrapper around SDL_GetTicks. As part of the embedded port, // its contents will eventually be replaced with something else. uint32_t get_ticks() { uint32_t ticks = 0; #ifdef __i386__ ticks = SDL_GetTicks(); #endif return ticks; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <limits.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/ioctl.h> #include <cutils/ashmem.h> #include <cutils/log.h> #include <cutils/atomic.h> #include <ion/ion.h> #include <hardware/hardware.h> #include <hardware/gralloc.h> #include "gralloc_priv.h" #include "gr.h" #include "HdmiDisplay.h" /*****************************************************************************/ struct gralloc_context_t { alloc_device_t device; /* our private data here */ volatile int vsync; pthread_mutex_t vsync_lock; pthread_cond_t vsync_cond; HdmiDisplay *hdmiDisplay; uint32_t nextSegmentNumber; }; static gralloc_context_t *gralloc_dev = 0; static int gralloc_alloc_buffer(alloc_device_t* dev, size_t size, size_t stride, int usage, buffer_handle_t* pHandle); /*****************************************************************************/ int fb_device_open(hw_module_t const* module, const char* name, hw_device_t** device); static int gralloc_device_open(const hw_module_t* module, const char* name, hw_device_t** device); extern int gralloc_lock(gralloc_module_t const* module, buffer_handle_t handle, int usage, int l, int t, int w, int h, void** vaddr); extern int gralloc_unlock(gralloc_module_t const* module, buffer_handle_t handle); extern int gralloc_register_buffer(gralloc_module_t const* module, buffer_handle_t handle); extern int gralloc_unregister_buffer(gralloc_module_t const* module, buffer_handle_t handle); /*****************************************************************************/ static struct hw_module_methods_t gralloc_module_methods = { open: gralloc_device_open }; struct private_gralloc_module_t HAL_MODULE_INFO_SYM = { base: { common: { tag: HARDWARE_MODULE_TAG, version_major: 1, version_minor: 0, id: GRALLOC_HARDWARE_MODULE_ID, name: "Graphics Memory Allocator Module", author: "The Android Open Source Project", methods: &gralloc_module_methods, dso: 0, reserved: {0} }, registerBuffer: gralloc_register_buffer, unregisterBuffer: gralloc_unregister_buffer, lock: gralloc_lock, unlock: gralloc_unlock, perform: 0, }, lock: PTHREAD_MUTEX_INITIALIZER, currentBuffer: 0, }; /*****************************************************************************/ static int gralloc_alloc_buffer(alloc_device_t* dev, size_t size, size_t stride, int usage, buffer_handle_t* pHandle) { int err = 0; int fd = -1; int segmentNumber = 0; size = roundUpToPageSize(size); struct gralloc_context_t *ctx = reinterpret_cast<gralloc_context_t*>(dev); if (ctx->hdmiDisplay != 0) { PortalAlloc portalAlloc; memset(&portalAlloc, 0, sizeof(portalAlloc)); portal.alloc(size, &fd, &portalAlloc); if (usage & GRALLOC_USAGE_HW_FB) { ALOGD("adding translation table entries\n"); segmentNumber = ctx->nextSegmentNumber; ctx->nextSegmentNumber += portalAlloc.numEntries; ctx->hdmiDisplay->beginTranslationTable(segmentNumber); for (int i = 0; i < portalAlloc.numEntries; i++) { ALOGD("adding translation entry %lx %lx", portalAlloc.entries[i].dma_address, portalAlloc.entries[i].length); ctx->hdmiDisplay->addTranslationEntry(portalAlloc.entries[i].dma_address >> 12, portalAlloc.entries[i].length >> 12); } } //ptr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); } if (fd < 0) { fd = ashmem_create_region("gralloc-buffer", size); if (fd < 0) { ALOGE("couldn't create ashmem (%s)", strerror(-errno)); err = -errno; } } if (err == 0) { private_handle_t* hnd = new private_handle_t(fd, size, 0); hnd->stride = stride; gralloc_module_t* module = reinterpret_cast<gralloc_module_t*>( dev->common.module); hnd->segmentNumber = segmentNumber; err = mapBuffer(module, hnd); if (err == 0) { *pHandle = hnd; } } ALOGE_IF(err, "gralloc failed err=%s", strerror(-err)); return err; } /*****************************************************************************/ static int gralloc_alloc(alloc_device_t* dev, int w, int h, int format, int usage, buffer_handle_t* pHandle, int* pStride) { if (!pHandle || !pStride) return -EINVAL; size_t size, stride; int align = 32; int bpp = 0; switch (format) { case HAL_PIXEL_FORMAT_RGBA_8888: case HAL_PIXEL_FORMAT_RGBX_8888: case HAL_PIXEL_FORMAT_BGRA_8888: bpp = 4; break; case HAL_PIXEL_FORMAT_RGB_888: bpp = 3; break; case HAL_PIXEL_FORMAT_RGB_565: case HAL_PIXEL_FORMAT_RGBA_5551: case HAL_PIXEL_FORMAT_RGBA_4444: bpp = 2; break; default: return -EINVAL; } size_t bpr = (w*bpp + (align-1)) & ~(align-1); size = bpr * h; stride = bpr / bpp; int err; err = gralloc_alloc_buffer(dev, size, stride, usage, pHandle); if (err < 0) { return err; } *pStride = stride; return 0; } static int gralloc_free(alloc_device_t* dev, buffer_handle_t handle) { if (private_handle_t::validate(handle) < 0) return -EINVAL; private_handle_t const* hnd = reinterpret_cast<private_handle_t const*>(handle); gralloc_module_t* module = reinterpret_cast<gralloc_module_t*>(dev->common.module); struct gralloc_context_t *ctx = reinterpret_cast<gralloc_context_t*>(dev); private_handle_t *private_handle = const_cast<private_handle_t*>(hnd); if (ctx->hdmiDisplay) { ALOGD("freeing ion buffer fd %d\n", private_handle->fd); portal.free(private_handle->fd); } else { ALOGD("freeing ashmem buffer %p\n", private_handle); terminateBuffer(module, private_handle); } close(hnd->fd); delete hnd; return 0; } /*****************************************************************************/ static int gralloc_close(struct hw_device_t *dev) { gralloc_context_t* ctx = reinterpret_cast<gralloc_context_t*>(dev); if (ctx) { /* TODO: keep a list of all buffer_handle_t created, and free them * all here. */ free(ctx); } return 0; } static int fb_setSwapInterval(struct framebuffer_device_t* dev, int interval) { framebuffer_device_t* ctx = (framebuffer_device_t*)dev; if (interval < dev->minSwapInterval || interval > dev->maxSwapInterval) return -EINVAL; // FIXME: implement fb_setSwapInterval return 0; } class GrallocHdmiDisplayIndications : public HdmiDisplayIndications { virtual void vsyncReceived(unsigned long long v) { if (1) ALOGD("vsyncReceivedHandler %llx\n", v); pthread_mutex_lock(&gralloc_dev->vsync_lock); gralloc_dev->vsync = 1; pthread_cond_signal(&gralloc_dev->vsync_cond); pthread_mutex_unlock(&gralloc_dev->vsync_lock); } }; static int fb_post(struct framebuffer_device_t* dev, buffer_handle_t buffer) { if (private_handle_t::validate(buffer) < 0) return -EINVAL; private_handle_t const* hnd = reinterpret_cast<private_handle_t const*>(buffer); private_gralloc_module_t* m = reinterpret_cast<private_gralloc_module_t*>( dev->common.module); if (gralloc_dev && gralloc_dev->hdmiDisplay) { ALOGD("fb_post segmentNumber=%d\n", hnd->segmentNumber); pthread_mutex_lock(&gralloc_dev->vsync_lock); gralloc_dev->vsync = 0; gralloc_dev->hdmiDisplay->waitForVsync(0); gralloc_dev->hdmiDisplay->startFrameBuffer0(hnd->segmentNumber); while (!gralloc_dev->vsync) { pthread_cond_wait(&gralloc_dev->vsync_cond, &gralloc_dev->vsync_lock); } pthread_mutex_unlock(&gralloc_dev->vsync_lock); ALOGD("fb posted\n"); } return 0; } static pthread_t fb_thread; static void *fb_thread_routine(void *data) { PortalInterface::exec(0); return data; } static int fb_close(struct hw_device_t *dev) { pthread_kill(fb_thread, SIGTERM); if (dev) { free(dev); } return 0; } int gralloc_device_open(const hw_module_t* module, const char* name, hw_device_t** device) { int status = -EINVAL; fprintf(stderr, "gralloc_device_open: name=%s\n", name); if (!strcmp(name, "gpu0")) { gralloc_context_t *dev; dev = (gralloc_context_t*)malloc(sizeof(*dev)); gralloc_dev = dev; /* initialize our state here */ memset(dev, 0, sizeof(*dev)); /* initialize the procs */ dev->device.common.tag = HARDWARE_DEVICE_TAG; dev->device.common.version = 0; dev->device.common.module = const_cast<hw_module_t*>(module); dev->device.common.close = gralloc_close; dev->device.alloc = gralloc_alloc; dev->device.free = gralloc_free; *device = &dev->device.common; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutex_init(&dev->vsync_lock, &attr); pthread_condattr_t condattr; pthread_condattr_init(&condattr); pthread_cond_init(&dev->vsync_cond, &condattr); dev->hdmiDisplay = HdmiDisplay::createHdmiDisplay("fpga0", new GrallocHdmiDisplayIndications); dev->nextSegmentNumber = 0; status = 0; } else if (!strcmp(name, GRALLOC_HARDWARE_FB0)) { alloc_device_t* gralloc_device; status = gralloc_open(module, &gralloc_device); if (status < 0) return status; /* initialize our state here */ framebuffer_device_t *dev = (framebuffer_device_t*)malloc(sizeof(*dev)); memset(dev, 0, sizeof(*dev)); /* initialize the procs */ dev->common.tag = HARDWARE_DEVICE_TAG; dev->common.version = 0; dev->common.module = const_cast<hw_module_t*>(module); dev->common.close = fb_close; dev->setSwapInterval = fb_setSwapInterval; dev->post = fb_post; dev->setUpdateRect = 0; pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&thread, &attr, fb_thread_routine, 0); private_gralloc_module_t* m = (private_gralloc_module_t*)module; //status = mapFrameBuffer(m); status = 0; if (status >= 0) { int format = HAL_PIXEL_FORMAT_RGBX_8888; unsigned short nlines = 480; unsigned short npixels = 720; unsigned short vsyncwidth = 5; unsigned short stridebytes = (npixels * 4 + 31) & ~31; unsigned short lmin = 40; unsigned short lmax = lmin + nlines; unsigned short pmin = 192; unsigned short pmax = pmin + npixels; const_cast<uint32_t&>(dev->flags) = 0; const_cast<uint32_t&>(dev->width) = npixels; const_cast<uint32_t&>(dev->height) = nlines; const_cast<int&>(dev->stride) = stridebytes; const_cast<int&>(dev->format) = format; const_cast<float&>(dev->xdpi) = 100; const_cast<float&>(dev->ydpi) = 100; const_cast<float&>(dev->fps) = 60; const_cast<int&>(dev->minSwapInterval) = 1; const_cast<int&>(dev->maxSwapInterval) = 1; gralloc_dev->hdmiDisplay->hdmiLinesPixels((pmin + npixels) << 16 | (lmin + vsyncwidth + nlines)); gralloc_dev->hdmiDisplay->hdmiStrideBytes(stridebytes); gralloc_dev->hdmiDisplay->hdmiLineCountMinMax(lmax << 16 | lmin); gralloc_dev->hdmiDisplay->hdmiPixelCountMinMax(pmax << 16 | pmin); //gralloc_dev->hdmiDisplay->updateFrequency(60l * (long)(pmin + npixels) * (long)(lmin + vsyncwidth + nlines)); *device = &dev->common; } } return status; } <commit_msg>use PortalInterface::setClockFrequency to set FCLK1 in gralloc<commit_after>/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <limits.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/ioctl.h> #include <cutils/ashmem.h> #include <cutils/log.h> #include <cutils/atomic.h> #include <ion/ion.h> #include <hardware/hardware.h> #include <hardware/gralloc.h> #include "gralloc_priv.h" #include "gr.h" #include "HdmiDisplay.h" /*****************************************************************************/ struct gralloc_context_t { alloc_device_t device; /* our private data here */ volatile int vsync; pthread_mutex_t vsync_lock; pthread_cond_t vsync_cond; HdmiDisplay *hdmiDisplay; uint32_t nextSegmentNumber; }; static gralloc_context_t *gralloc_dev = 0; static int gralloc_alloc_buffer(alloc_device_t* dev, size_t size, size_t stride, int usage, buffer_handle_t* pHandle); /*****************************************************************************/ int fb_device_open(hw_module_t const* module, const char* name, hw_device_t** device); static int gralloc_device_open(const hw_module_t* module, const char* name, hw_device_t** device); extern int gralloc_lock(gralloc_module_t const* module, buffer_handle_t handle, int usage, int l, int t, int w, int h, void** vaddr); extern int gralloc_unlock(gralloc_module_t const* module, buffer_handle_t handle); extern int gralloc_register_buffer(gralloc_module_t const* module, buffer_handle_t handle); extern int gralloc_unregister_buffer(gralloc_module_t const* module, buffer_handle_t handle); /*****************************************************************************/ static struct hw_module_methods_t gralloc_module_methods = { open: gralloc_device_open }; struct private_gralloc_module_t HAL_MODULE_INFO_SYM = { base: { common: { tag: HARDWARE_MODULE_TAG, version_major: 1, version_minor: 0, id: GRALLOC_HARDWARE_MODULE_ID, name: "Graphics Memory Allocator Module", author: "The Android Open Source Project", methods: &gralloc_module_methods, dso: 0, reserved: {0} }, registerBuffer: gralloc_register_buffer, unregisterBuffer: gralloc_unregister_buffer, lock: gralloc_lock, unlock: gralloc_unlock, perform: 0, }, lock: PTHREAD_MUTEX_INITIALIZER, currentBuffer: 0, }; /*****************************************************************************/ static int gralloc_alloc_buffer(alloc_device_t* dev, size_t size, size_t stride, int usage, buffer_handle_t* pHandle) { int err = 0; int fd = -1; int segmentNumber = 0; size = roundUpToPageSize(size); struct gralloc_context_t *ctx = reinterpret_cast<gralloc_context_t*>(dev); if (ctx->hdmiDisplay != 0) { PortalAlloc portalAlloc; memset(&portalAlloc, 0, sizeof(portalAlloc)); portal.alloc(size, &fd, &portalAlloc); if (usage & GRALLOC_USAGE_HW_FB) { ALOGD("adding translation table entries\n"); segmentNumber = ctx->nextSegmentNumber; ctx->nextSegmentNumber += portalAlloc.numEntries; ctx->hdmiDisplay->beginTranslationTable(segmentNumber); for (int i = 0; i < portalAlloc.numEntries; i++) { ALOGD("adding translation entry %lx %lx", portalAlloc.entries[i].dma_address, portalAlloc.entries[i].length); ctx->hdmiDisplay->addTranslationEntry(portalAlloc.entries[i].dma_address >> 12, portalAlloc.entries[i].length >> 12); } } //ptr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); } if (fd < 0) { fd = ashmem_create_region("gralloc-buffer", size); if (fd < 0) { ALOGE("couldn't create ashmem (%s)", strerror(-errno)); err = -errno; } } if (err == 0) { private_handle_t* hnd = new private_handle_t(fd, size, 0); hnd->stride = stride; gralloc_module_t* module = reinterpret_cast<gralloc_module_t*>( dev->common.module); hnd->segmentNumber = segmentNumber; err = mapBuffer(module, hnd); if (err == 0) { *pHandle = hnd; } } ALOGE_IF(err, "gralloc failed err=%s", strerror(-err)); return err; } /*****************************************************************************/ static int gralloc_alloc(alloc_device_t* dev, int w, int h, int format, int usage, buffer_handle_t* pHandle, int* pStride) { if (!pHandle || !pStride) return -EINVAL; size_t size, stride; int align = 32; int bpp = 0; switch (format) { case HAL_PIXEL_FORMAT_RGBA_8888: case HAL_PIXEL_FORMAT_RGBX_8888: case HAL_PIXEL_FORMAT_BGRA_8888: bpp = 4; break; case HAL_PIXEL_FORMAT_RGB_888: bpp = 3; break; case HAL_PIXEL_FORMAT_RGB_565: case HAL_PIXEL_FORMAT_RGBA_5551: case HAL_PIXEL_FORMAT_RGBA_4444: bpp = 2; break; default: return -EINVAL; } size_t bpr = (w*bpp + (align-1)) & ~(align-1); size = bpr * h; stride = bpr / bpp; int err; err = gralloc_alloc_buffer(dev, size, stride, usage, pHandle); if (err < 0) { return err; } *pStride = stride; return 0; } static int gralloc_free(alloc_device_t* dev, buffer_handle_t handle) { if (private_handle_t::validate(handle) < 0) return -EINVAL; private_handle_t const* hnd = reinterpret_cast<private_handle_t const*>(handle); gralloc_module_t* module = reinterpret_cast<gralloc_module_t*>(dev->common.module); struct gralloc_context_t *ctx = reinterpret_cast<gralloc_context_t*>(dev); private_handle_t *private_handle = const_cast<private_handle_t*>(hnd); if (ctx->hdmiDisplay) { ALOGD("freeing ion buffer fd %d\n", private_handle->fd); portal.free(private_handle->fd); } else { ALOGD("freeing ashmem buffer %p\n", private_handle); terminateBuffer(module, private_handle); } close(hnd->fd); delete hnd; return 0; } /*****************************************************************************/ static int gralloc_close(struct hw_device_t *dev) { gralloc_context_t* ctx = reinterpret_cast<gralloc_context_t*>(dev); if (ctx) { /* TODO: keep a list of all buffer_handle_t created, and free them * all here. */ free(ctx); } return 0; } static int fb_setSwapInterval(struct framebuffer_device_t* dev, int interval) { framebuffer_device_t* ctx = (framebuffer_device_t*)dev; if (interval < dev->minSwapInterval || interval > dev->maxSwapInterval) return -EINVAL; // FIXME: implement fb_setSwapInterval return 0; } class GrallocHdmiDisplayIndications : public HdmiDisplayIndications { virtual void vsyncReceived(unsigned long long v) { if (1) ALOGD("vsyncReceivedHandler %llx\n", v); pthread_mutex_lock(&gralloc_dev->vsync_lock); gralloc_dev->vsync = 1; pthread_cond_signal(&gralloc_dev->vsync_cond); pthread_mutex_unlock(&gralloc_dev->vsync_lock); } }; static int fb_post(struct framebuffer_device_t* dev, buffer_handle_t buffer) { if (private_handle_t::validate(buffer) < 0) return -EINVAL; private_handle_t const* hnd = reinterpret_cast<private_handle_t const*>(buffer); private_gralloc_module_t* m = reinterpret_cast<private_gralloc_module_t*>( dev->common.module); if (gralloc_dev && gralloc_dev->hdmiDisplay) { ALOGD("fb_post segmentNumber=%d\n", hnd->segmentNumber); pthread_mutex_lock(&gralloc_dev->vsync_lock); gralloc_dev->vsync = 0; gralloc_dev->hdmiDisplay->waitForVsync(0); gralloc_dev->hdmiDisplay->startFrameBuffer0(hnd->segmentNumber); while (!gralloc_dev->vsync) { pthread_cond_wait(&gralloc_dev->vsync_cond, &gralloc_dev->vsync_lock); } pthread_mutex_unlock(&gralloc_dev->vsync_lock); ALOGD("fb posted\n"); } return 0; } static pthread_t fb_thread; static void *fb_thread_routine(void *data) { PortalInterface::exec(0); return data; } static int fb_close(struct hw_device_t *dev) { pthread_kill(fb_thread, SIGTERM); if (dev) { free(dev); } return 0; } int gralloc_device_open(const hw_module_t* module, const char* name, hw_device_t** device) { int status = -EINVAL; fprintf(stderr, "gralloc_device_open: name=%s\n", name); if (!strcmp(name, "gpu0")) { gralloc_context_t *dev; dev = (gralloc_context_t*)malloc(sizeof(*dev)); gralloc_dev = dev; /* initialize our state here */ memset(dev, 0, sizeof(*dev)); /* initialize the procs */ dev->device.common.tag = HARDWARE_DEVICE_TAG; dev->device.common.version = 0; dev->device.common.module = const_cast<hw_module_t*>(module); dev->device.common.close = gralloc_close; dev->device.alloc = gralloc_alloc; dev->device.free = gralloc_free; *device = &dev->device.common; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutex_init(&dev->vsync_lock, &attr); pthread_condattr_t condattr; pthread_condattr_init(&condattr); pthread_cond_init(&dev->vsync_cond, &condattr); dev->hdmiDisplay = HdmiDisplay::createHdmiDisplay("fpga0", new GrallocHdmiDisplayIndications); dev->nextSegmentNumber = 0; status = 0; } else if (!strcmp(name, GRALLOC_HARDWARE_FB0)) { alloc_device_t* gralloc_device; status = gralloc_open(module, &gralloc_device); if (status < 0) return status; /* initialize our state here */ framebuffer_device_t *dev = (framebuffer_device_t*)malloc(sizeof(*dev)); memset(dev, 0, sizeof(*dev)); /* initialize the procs */ dev->common.tag = HARDWARE_DEVICE_TAG; dev->common.version = 0; dev->common.module = const_cast<hw_module_t*>(module); dev->common.close = fb_close; dev->setSwapInterval = fb_setSwapInterval; dev->post = fb_post; dev->setUpdateRect = 0; pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&thread, &attr, fb_thread_routine, 0); private_gralloc_module_t* m = (private_gralloc_module_t*)module; //status = mapFrameBuffer(m); status = 0; if (status >= 0) { int format = HAL_PIXEL_FORMAT_RGBX_8888; unsigned short nlines = 480; unsigned short npixels = 720; unsigned short vsyncwidth = 5; unsigned short stridebytes = (npixels * 4 + 31) & ~31; unsigned short lmin = 40; unsigned short lmax = lmin + nlines; unsigned short pmin = 192; unsigned short pmax = pmin + npixels; const_cast<uint32_t&>(dev->flags) = 0; const_cast<uint32_t&>(dev->width) = npixels; const_cast<uint32_t&>(dev->height) = nlines; const_cast<int&>(dev->stride) = stridebytes; const_cast<int&>(dev->format) = format; const_cast<float&>(dev->xdpi) = 100; const_cast<float&>(dev->ydpi) = 100; const_cast<float&>(dev->fps) = 60; const_cast<int&>(dev->minSwapInterval) = 1; const_cast<int&>(dev->maxSwapInterval) = 1; gralloc_dev->hdmiDisplay->hdmiLinesPixels((pmin + npixels) << 16 | (lmin + vsyncwidth + nlines)); gralloc_dev->hdmiDisplay->hdmiStrideBytes(stridebytes); gralloc_dev->hdmiDisplay->hdmiLineCountMinMax(lmax << 16 | lmin); gralloc_dev->hdmiDisplay->hdmiPixelCountMinMax(pmax << 16 | pmin); PortalInterface::setClockFrequency(1, 60l * (long)(pmin + npixels) * (long)(lmin + vsyncwidth + nlines), 0); *device = &dev->common; } } return status; } <|endoftext|>
<commit_before>// // 6526Implementation.hpp // Clock Signal // // Created by Thomas Harte on 18/07/2021. // Copyright © 2021 Thomas Harte. All rights reserved. // #ifndef _526Implementation_h #define _526Implementation_h #include <cassert> #include <cstdio> namespace MOS { namespace MOS6526 { enum Interrupts: uint8_t { TimerA = 1 << 0, TimerB = 1 << 1, Alarm = 1 << 2, SerialPort = 1 << 3, Flag = 1 << 4, }; template <typename BusHandlerT, Personality personality> template <int port> void MOS6526<BusHandlerT, personality>::set_port_output() { const uint8_t output = output_[port] | (~data_direction_[port]); port_handler_.set_port_output(Port(port), output); } template <typename BusHandlerT, Personality personality> template <int port> uint8_t MOS6526<BusHandlerT, personality>::get_port_input() { const uint8_t input = port_handler_.get_port_input(Port(port)); return (input & ~data_direction_[port]) | (output_[port] & data_direction_[port]); } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::posit_interrupt(uint8_t mask) { if(!mask) { return; } interrupt_state_ |= mask; update_interrupts(); } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::update_interrupts() { if(interrupt_state_ & interrupt_control_) { pending_ |= InterruptInOne; } } template <typename BusHandlerT, Personality personality> bool MOS6526<BusHandlerT, personality>::get_interrupt_line() { return interrupt_state_ & 0x80; } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::set_cnt_input(bool active) { cnt_edge_ = active && !cnt_state_; cnt_state_ = active; } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::set_flag_input(bool low) { if(low && !flag_state_) { posit_interrupt(Interrupts::Flag); } flag_state_ = low; } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::write(int address, uint8_t value) { address &= 0xf; switch(address) { // Port output. case 0: output_[0] = value; set_port_output<0>(); break; case 1: output_[1] = value; set_port_output<1>(); break; // Port direction. case 2: data_direction_[0] = value; set_port_output<0>(); break; case 3: data_direction_[1] = value; set_port_output<1>(); break; // Counters; writes set the reload values. case 4: counter_[0].template set_reload<0, personality == Personality::P8250>(value); break; case 5: counter_[0].template set_reload<8, personality == Personality::P8250>(value); break; case 6: counter_[1].template set_reload<0, personality == Personality::P8250>(value); break; case 7: counter_[1].template set_reload<8, personality == Personality::P8250>(value); break; // Time-of-day clock. case 8: tod_.template write<0>(value); break; case 9: tod_.template write<1>(value); break; case 10: tod_.template write<2>(value); break; case 11: tod_.template write<3>(value); break; // Interrupt control. case 13: { if(value & 0x80) { interrupt_control_ |= value & 0x7f; } else { interrupt_control_ &= ~(value & 0x7f); } update_interrupts(); } break; // Control. Posted to both the counters and the clock as it affects both. case 14: counter_[0].template set_control<false>(value); tod_.template set_control<false>(value); break; case 15: counter_[1].template set_control<true>(value); tod_.template set_control<true>(value); break; default: printf("Unhandled 6526 write: %02x to %d\n", value, address); assert(false); break; } } template <typename BusHandlerT, Personality personality> uint8_t MOS6526<BusHandlerT, personality>::read(int address) { address &= 0xf; switch(address) { case 0: return get_port_input<0>(); case 1: return get_port_input<1>(); case 2: case 3: return data_direction_[address - 2]; // Counters; reads obtain the current values. case 4: return uint8_t(counter_[0].value >> 0); case 5: return uint8_t(counter_[0].value >> 8); case 6: return uint8_t(counter_[1].value >> 0); case 7: return uint8_t(counter_[1].value >> 8); // Interrupt state. case 13: { const uint8_t result = interrupt_state_; interrupt_state_ = 0; pending_ &= ~(InterruptNow | InterruptInOne); update_interrupts(); return result; } break; case 14: case 15: return counter_[address - 14].control; // Time-of-day clock. case 8: return tod_.template read<0>(); case 9: return tod_.template read<1>(); case 10: return tod_.template read<2>(); case 11: return tod_.template read<3>(); default: printf("Unhandled 6526 read from %d\n", address); assert(false); break; } return 0xff; } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::run_for(const HalfCycles half_cycles) { half_divider_ += half_cycles; int sub = half_divider_.divide_cycles().template as<int>(); while(sub--) { pending_ <<= 1; if(pending_ & InterruptNow) { interrupt_state_ |= 0x80; } pending_ &= PendingClearMask; // TODO: use CNT potentially to clock timer A, elimiante conditional above. const bool timer1_did_reload = counter_[0].template advance<false>(false, cnt_state_, cnt_edge_); const bool timer1_carry = timer1_did_reload && (counter_[1].control & 0x60) == 0x40; const bool timer2_did_reload = counter_[1].template advance<true>(timer1_carry, cnt_state_, cnt_edge_); posit_interrupt((timer1_did_reload ? Interrupts::TimerA : 0x00) | (timer2_did_reload ? Interrupts::TimerB : 0x00)); cnt_edge_ = false; } } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::advance_tod(int count) { if(!count) return; if(tod_.advance(count)) { posit_interrupt(Interrupts::Alarm); } } } } #endif /* _526Implementation_h */ <commit_msg>Add TODOs rather than complete stop on shift register acccesses.<commit_after>// // 6526Implementation.hpp // Clock Signal // // Created by Thomas Harte on 18/07/2021. // Copyright © 2021 Thomas Harte. All rights reserved. // #ifndef _526Implementation_h #define _526Implementation_h #include <cassert> #include <cstdio> namespace MOS { namespace MOS6526 { enum Interrupts: uint8_t { TimerA = 1 << 0, TimerB = 1 << 1, Alarm = 1 << 2, SerialPort = 1 << 3, Flag = 1 << 4, }; template <typename BusHandlerT, Personality personality> template <int port> void MOS6526<BusHandlerT, personality>::set_port_output() { const uint8_t output = output_[port] | (~data_direction_[port]); port_handler_.set_port_output(Port(port), output); } template <typename BusHandlerT, Personality personality> template <int port> uint8_t MOS6526<BusHandlerT, personality>::get_port_input() { const uint8_t input = port_handler_.get_port_input(Port(port)); return (input & ~data_direction_[port]) | (output_[port] & data_direction_[port]); } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::posit_interrupt(uint8_t mask) { if(!mask) { return; } interrupt_state_ |= mask; update_interrupts(); } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::update_interrupts() { if(interrupt_state_ & interrupt_control_) { pending_ |= InterruptInOne; } } template <typename BusHandlerT, Personality personality> bool MOS6526<BusHandlerT, personality>::get_interrupt_line() { return interrupt_state_ & 0x80; } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::set_cnt_input(bool active) { cnt_edge_ = active && !cnt_state_; cnt_state_ = active; } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::set_flag_input(bool low) { if(low && !flag_state_) { posit_interrupt(Interrupts::Flag); } flag_state_ = low; } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::write(int address, uint8_t value) { address &= 0xf; switch(address) { // Port output. case 0: output_[0] = value; set_port_output<0>(); break; case 1: output_[1] = value; set_port_output<1>(); break; // Port direction. case 2: data_direction_[0] = value; set_port_output<0>(); break; case 3: data_direction_[1] = value; set_port_output<1>(); break; // Counters; writes set the reload values. case 4: counter_[0].template set_reload<0, personality == Personality::P8250>(value); break; case 5: counter_[0].template set_reload<8, personality == Personality::P8250>(value); break; case 6: counter_[1].template set_reload<0, personality == Personality::P8250>(value); break; case 7: counter_[1].template set_reload<8, personality == Personality::P8250>(value); break; // Time-of-day clock. case 8: tod_.template write<0>(value); break; case 9: tod_.template write<1>(value); break; case 10: tod_.template write<2>(value); break; case 11: tod_.template write<3>(value); break; // Interrupt control. case 13: { if(value & 0x80) { interrupt_control_ |= value & 0x7f; } else { interrupt_control_ &= ~(value & 0x7f); } update_interrupts(); } break; // Control. Posted to both the counters and the clock as it affects both. case 14: counter_[0].template set_control<false>(value); tod_.template set_control<false>(value); break; case 15: counter_[1].template set_control<true>(value); tod_.template set_control<true>(value); break; // Shift control. case 12: printf("TODO: write to shift register\n"); break; default: printf("Unhandled 6526 write: %02x to %d\n", value, address); assert(false); break; } } template <typename BusHandlerT, Personality personality> uint8_t MOS6526<BusHandlerT, personality>::read(int address) { address &= 0xf; switch(address) { case 0: return get_port_input<0>(); case 1: return get_port_input<1>(); case 2: case 3: return data_direction_[address - 2]; // Counters; reads obtain the current values. case 4: return uint8_t(counter_[0].value >> 0); case 5: return uint8_t(counter_[0].value >> 8); case 6: return uint8_t(counter_[1].value >> 0); case 7: return uint8_t(counter_[1].value >> 8); // Interrupt state. case 13: { const uint8_t result = interrupt_state_; interrupt_state_ = 0; pending_ &= ~(InterruptNow | InterruptInOne); update_interrupts(); return result; } break; case 14: case 15: return counter_[address - 14].control; // Time-of-day clock. case 8: return tod_.template read<0>(); case 9: return tod_.template read<1>(); case 10: return tod_.template read<2>(); case 11: return tod_.template read<3>(); // Shift register. case 12: printf("TODO: read from shift register\n"); break; default: printf("Unhandled 6526 read from %d\n", address); assert(false); break; } return 0xff; } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::run_for(const HalfCycles half_cycles) { half_divider_ += half_cycles; int sub = half_divider_.divide_cycles().template as<int>(); while(sub--) { pending_ <<= 1; if(pending_ & InterruptNow) { interrupt_state_ |= 0x80; } pending_ &= PendingClearMask; // TODO: use CNT potentially to clock timer A, elimiante conditional above. const bool timer1_did_reload = counter_[0].template advance<false>(false, cnt_state_, cnt_edge_); const bool timer1_carry = timer1_did_reload && (counter_[1].control & 0x60) == 0x40; const bool timer2_did_reload = counter_[1].template advance<true>(timer1_carry, cnt_state_, cnt_edge_); posit_interrupt((timer1_did_reload ? Interrupts::TimerA : 0x00) | (timer2_did_reload ? Interrupts::TimerB : 0x00)); cnt_edge_ = false; } } template <typename BusHandlerT, Personality personality> void MOS6526<BusHandlerT, personality>::advance_tod(int count) { if(!count) return; if(tod_.advance(count)) { posit_interrupt(Interrupts::Alarm); } } } } #endif /* _526Implementation_h */ <|endoftext|>
<commit_before>#include "Base.h" #include "Animation.h" #include "AnimationController.h" #include "AnimationClip.h" #include "AnimationTarget.h" #include "Game.h" #include "Transform.h" #include "Properties.h" #define ANIMATION_INDEFINITE_STR "INDEFINITE" #define ANIMATION_DEFAULT_CLIP 0 #define ANIMATION_ROTATE_OFFSET 0 #define ANIMATION_SRT_OFFSET 3 namespace gameplay { Animation::Animation(const char* id, AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned long* keyTimes, float* keyValues, unsigned int type) : _controller(Game::getInstance()->getAnimationController()), _id(id), _duration(0), _defaultClip(NULL), _clips(NULL) { createChannel(target, propertyId, keyCount, keyTimes, keyValues, type); } Animation::Animation(const char* id, AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned long* keyTimes, float* keyValues, float* keyInValue, float* keyOutValue, unsigned int type) : _controller(Game::getInstance()->getAnimationController()), _id(id), _duration(0), _defaultClip(NULL), _clips(NULL) { createChannel(target, propertyId, keyCount, keyTimes, keyValues, keyInValue, keyOutValue, type); } Animation::Animation(const char* id) : _controller(Game::getInstance()->getAnimationController()), _id(id), _duration(0), _defaultClip(NULL), _clips(NULL) { } Animation::~Animation() { _channels.clear(); if (_defaultClip) { if (_defaultClip->isClipStateBitSet(AnimationClip::CLIP_IS_PLAYING_BIT)) _controller->unschedule(_defaultClip); SAFE_RELEASE(_defaultClip); } if (_clips) { std::vector<AnimationClip*>::iterator clipIter = _clips->begin(); while (clipIter != _clips->end()) { AnimationClip* clip = *clipIter; if (clip->isClipStateBitSet(AnimationClip::CLIP_IS_PLAYING_BIT)) _controller->unschedule(clip); SAFE_RELEASE(clip); clipIter++; } _clips->clear(); } SAFE_DELETE(_clips); } Animation::Channel::Channel(Animation* animation, AnimationTarget* target, int propertyId, Curve* curve, unsigned long duration) : _animation(animation), _target(target), _propertyId(propertyId), _curve(curve), _duration(duration) { // get property component count, and ensure the property exists on the AnimationTarget by getting the property component count. assert(_target->getAnimationPropertyComponentCount(propertyId)); _target->addChannel(this); } Animation::Channel::Channel(const Channel& copy, Animation* animation, AnimationTarget* target) : _animation(animation), _target(target), _propertyId(copy._propertyId), _curve(copy._curve), _duration(copy._duration) { _target->addChannel(this); } Animation::Channel::~Channel() { SAFE_RELEASE(_curve); SAFE_RELEASE(_animation); } Curve* Animation::Channel::getCurve() const { return _curve; } const char* Animation::getId() const { return _id.c_str(); } unsigned long Animation::getDuration() const { return _duration; } void Animation::createClips(const char* animationFile) { assert(animationFile); Properties* properties = Properties::create(animationFile); assert(properties); Properties* pAnimation = properties->getNextNamespace(); assert(pAnimation); int frameCount = pAnimation->getInt("frameCount"); assert(frameCount > 0); createClips(pAnimation, (unsigned int)frameCount); SAFE_DELETE(properties); } AnimationClip* Animation::createClip(const char* id, unsigned long start, unsigned long end) { AnimationClip* clip = new AnimationClip(id, this, start, end); addClip(clip); return clip; } AnimationClip* Animation::getClip(const char* id) { // If id is NULL return the default clip. if (id == NULL) { if (_defaultClip == NULL) createDefaultClip(); return _defaultClip; } else { return findClip(id); } } void Animation::play(const char* clipId) { // If id is NULL, play the default clip. if (clipId == NULL) { if (_defaultClip == NULL) createDefaultClip(); _defaultClip->play(); } else { // Find animation clip.. and play. AnimationClip* clip = findClip(clipId); if (clip != NULL) clip->play(); } } void Animation::stop(const char* clipId) { // If id is NULL, play the default clip. if (clipId == NULL) { if (_defaultClip) _defaultClip->stop(); } else { // Find animation clip.. and play. AnimationClip* clip = findClip(clipId); if (clip != NULL) clip->stop(); } } void Animation::pause(const char * clipId) { if (clipId == NULL) { if (_defaultClip) _defaultClip->pause(); } else { AnimationClip* clip = findClip(clipId); if (clip != NULL) clip->pause(); } } bool Animation::targets(AnimationTarget* target) const { for (std::vector<Animation::Channel*>::const_iterator itr = _channels.begin(); itr != _channels.end(); ++itr) { if ((*itr)->_target == target) { return true; } } return false; } void Animation::createDefaultClip() { _defaultClip = new AnimationClip("default_clip", this, 0.0f, _duration); } void Animation::createClips(Properties* animationProperties, unsigned int frameCount) { assert(animationProperties); Properties* pClip = animationProperties->getNextNamespace(); while (pClip != NULL && std::strcmp(pClip->getNamespace(), "clip") == 0) { int begin = pClip->getInt("begin"); int end = pClip->getInt("end"); AnimationClip* clip = createClip(pClip->getId(), ((float) begin / frameCount) * _duration, ((float) end / frameCount) * _duration); const char* repeat = pClip->getString("repeatCount"); if (repeat) { if (strcmp(repeat, ANIMATION_INDEFINITE_STR) == 0) { clip->setRepeatCount(AnimationClip::REPEAT_INDEFINITE); } else { float value; sscanf(repeat, "%f", &value); clip->setRepeatCount(value); } } const char* speed = pClip->getString("speed"); if (speed) { float value; sscanf(speed, "%f", &value); clip->setSpeed(value); } pClip = animationProperties->getNextNamespace(); } } void Animation::addClip(AnimationClip* clip) { if (_clips == NULL) _clips = new std::vector<AnimationClip*>; _clips->push_back(clip); } AnimationClip* Animation::findClip(const char* id) const { if (_clips) { AnimationClip* clip = NULL; unsigned int clipCount = _clips->size(); for (unsigned int i = 0; i < clipCount; i++) { clip = _clips->at(i); if (clip->_id.compare(id) == 0) { return _clips->at(i); } } } return NULL; } Animation::Channel* Animation::createChannel(AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned long* keyTimes, float* keyValues, unsigned int type) { unsigned int propertyComponentCount = target->getAnimationPropertyComponentCount(propertyId); assert(propertyComponentCount > 0); Curve* curve = Curve::create(keyCount, propertyComponentCount); if (target->_targetType == AnimationTarget::TRANSFORM) setTransformRotationOffset(curve, propertyId); unsigned long lowest = keyTimes[0]; unsigned long duration = keyTimes[keyCount-1] - lowest; float* normalizedKeyTimes = new float[keyCount]; normalizedKeyTimes[0] = 0.0f; curve->setPoint(0, normalizedKeyTimes[0], keyValues, (Curve::InterpolationType) type); unsigned int pointOffset = propertyComponentCount; unsigned int i = 1; for (; i < keyCount - 1; i++) { normalizedKeyTimes[i] = (float) (keyTimes[i] - lowest) / (float) duration; curve->setPoint(i, normalizedKeyTimes[i], (keyValues + pointOffset), (Curve::InterpolationType) type); pointOffset += propertyComponentCount; } i = keyCount - 1; normalizedKeyTimes[i] = 1.0f; curve->setPoint(i, normalizedKeyTimes[i], keyValues + pointOffset, (Curve::InterpolationType) type); SAFE_DELETE(normalizedKeyTimes); Channel* channel = new Channel(this, target, propertyId, curve, duration); addChannel(channel); return channel; } Animation::Channel* Animation::createChannel(AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned long* keyTimes, float* keyValues, float* keyInValue, float* keyOutValue, unsigned int type) { unsigned int propertyComponentCount = target->getAnimationPropertyComponentCount(propertyId); assert(propertyComponentCount > 0); Curve* curve = Curve::create(keyCount, propertyComponentCount); if (target->_targetType == AnimationTarget::TRANSFORM) setTransformRotationOffset(curve, propertyId); unsigned long lowest = keyTimes[0]; unsigned long duration = keyTimes[keyCount-1] - lowest; float* normalizedKeyTimes = new float[keyCount]; normalizedKeyTimes[0] = 0.0f; curve->setPoint(0, normalizedKeyTimes[0], keyValues, (Curve::InterpolationType) type, keyInValue, keyOutValue); unsigned int pointOffset = propertyComponentCount; unsigned int i = 1; for (; i < keyCount - 1; i++) { normalizedKeyTimes[i] = (float) (keyTimes[i] - lowest) / (float) duration; curve->setPoint(i, normalizedKeyTimes[i], (keyValues + pointOffset), (Curve::InterpolationType) type, (keyInValue + pointOffset), (keyOutValue + pointOffset)); pointOffset += propertyComponentCount; } i = keyCount - 1; normalizedKeyTimes[i] = 1.0f; curve->setPoint(i, normalizedKeyTimes[i], keyValues + pointOffset, (Curve::InterpolationType) type, keyInValue + pointOffset, keyOutValue + pointOffset); SAFE_DELETE(normalizedKeyTimes); Channel* channel = new Channel(this, target, propertyId, curve, duration); addChannel(channel); return channel; } void Animation::addChannel(Channel* channel) { _channels.push_back(channel); if (channel->_duration > _duration) _duration = channel->_duration; } void Animation::removeChannel(Channel* channel) { std::vector<Animation::Channel*>::iterator itr = _channels.begin(); while (itr != _channels.end()) { Animation::Channel* chan = *itr; if (channel == chan) { _channels.erase(itr); return; } else { itr++; } } } void Animation::setTransformRotationOffset(Curve* curve, unsigned int propertyId) { switch (propertyId) { case Transform::ANIMATE_ROTATE: case Transform::ANIMATE_ROTATE_TRANSLATE: curve->setQuaternionOffset(ANIMATION_ROTATE_OFFSET); return; case Transform::ANIMATE_SCALE_ROTATE_TRANSLATE: curve->setQuaternionOffset(ANIMATION_SRT_OFFSET); return; } return; } Animation* Animation::clone() { Animation* animation = new Animation(getId()); return animation; } } <commit_msg>Fixed reference counting issue with Curve.<commit_after>#include "Base.h" #include "Animation.h" #include "AnimationController.h" #include "AnimationClip.h" #include "AnimationTarget.h" #include "Game.h" #include "Transform.h" #include "Properties.h" #define ANIMATION_INDEFINITE_STR "INDEFINITE" #define ANIMATION_DEFAULT_CLIP 0 #define ANIMATION_ROTATE_OFFSET 0 #define ANIMATION_SRT_OFFSET 3 namespace gameplay { Animation::Animation(const char* id, AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned long* keyTimes, float* keyValues, unsigned int type) : _controller(Game::getInstance()->getAnimationController()), _id(id), _duration(0), _defaultClip(NULL), _clips(NULL) { createChannel(target, propertyId, keyCount, keyTimes, keyValues, type); } Animation::Animation(const char* id, AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned long* keyTimes, float* keyValues, float* keyInValue, float* keyOutValue, unsigned int type) : _controller(Game::getInstance()->getAnimationController()), _id(id), _duration(0), _defaultClip(NULL), _clips(NULL) { createChannel(target, propertyId, keyCount, keyTimes, keyValues, keyInValue, keyOutValue, type); } Animation::Animation(const char* id) : _controller(Game::getInstance()->getAnimationController()), _id(id), _duration(0), _defaultClip(NULL), _clips(NULL) { } Animation::~Animation() { _channels.clear(); if (_defaultClip) { if (_defaultClip->isClipStateBitSet(AnimationClip::CLIP_IS_PLAYING_BIT)) _controller->unschedule(_defaultClip); SAFE_RELEASE(_defaultClip); } if (_clips) { std::vector<AnimationClip*>::iterator clipIter = _clips->begin(); while (clipIter != _clips->end()) { AnimationClip* clip = *clipIter; if (clip->isClipStateBitSet(AnimationClip::CLIP_IS_PLAYING_BIT)) _controller->unschedule(clip); SAFE_RELEASE(clip); clipIter++; } _clips->clear(); } SAFE_DELETE(_clips); } Animation::Channel::Channel(Animation* animation, AnimationTarget* target, int propertyId, Curve* curve, unsigned long duration) : _animation(animation), _target(target), _propertyId(propertyId), _curve(curve), _duration(duration) { // get property component count, and ensure the property exists on the AnimationTarget by getting the property component count. assert(_target->getAnimationPropertyComponentCount(propertyId)); _curve->addRef(); _target->addChannel(this); } Animation::Channel::Channel(const Channel& copy, Animation* animation, AnimationTarget* target) : _animation(animation), _target(target), _propertyId(copy._propertyId), _curve(copy._curve), _duration(copy._duration) { _curve->addRef(); _target->addChannel(this); } Animation::Channel::~Channel() { SAFE_RELEASE(_curve); SAFE_RELEASE(_animation); } Curve* Animation::Channel::getCurve() const { return _curve; } const char* Animation::getId() const { return _id.c_str(); } unsigned long Animation::getDuration() const { return _duration; } void Animation::createClips(const char* animationFile) { assert(animationFile); Properties* properties = Properties::create(animationFile); assert(properties); Properties* pAnimation = properties->getNextNamespace(); assert(pAnimation); int frameCount = pAnimation->getInt("frameCount"); assert(frameCount > 0); createClips(pAnimation, (unsigned int)frameCount); SAFE_DELETE(properties); } AnimationClip* Animation::createClip(const char* id, unsigned long start, unsigned long end) { AnimationClip* clip = new AnimationClip(id, this, start, end); addClip(clip); return clip; } AnimationClip* Animation::getClip(const char* id) { // If id is NULL return the default clip. if (id == NULL) { if (_defaultClip == NULL) createDefaultClip(); return _defaultClip; } else { return findClip(id); } } void Animation::play(const char* clipId) { // If id is NULL, play the default clip. if (clipId == NULL) { if (_defaultClip == NULL) createDefaultClip(); _defaultClip->play(); } else { // Find animation clip.. and play. AnimationClip* clip = findClip(clipId); if (clip != NULL) clip->play(); } } void Animation::stop(const char* clipId) { // If id is NULL, play the default clip. if (clipId == NULL) { if (_defaultClip) _defaultClip->stop(); } else { // Find animation clip.. and play. AnimationClip* clip = findClip(clipId); if (clip != NULL) clip->stop(); } } void Animation::pause(const char * clipId) { if (clipId == NULL) { if (_defaultClip) _defaultClip->pause(); } else { AnimationClip* clip = findClip(clipId); if (clip != NULL) clip->pause(); } } bool Animation::targets(AnimationTarget* target) const { for (std::vector<Animation::Channel*>::const_iterator itr = _channels.begin(); itr != _channels.end(); ++itr) { if ((*itr)->_target == target) { return true; } } return false; } void Animation::createDefaultClip() { _defaultClip = new AnimationClip("default_clip", this, 0.0f, _duration); } void Animation::createClips(Properties* animationProperties, unsigned int frameCount) { assert(animationProperties); Properties* pClip = animationProperties->getNextNamespace(); while (pClip != NULL && std::strcmp(pClip->getNamespace(), "clip") == 0) { int begin = pClip->getInt("begin"); int end = pClip->getInt("end"); AnimationClip* clip = createClip(pClip->getId(), ((float) begin / frameCount) * _duration, ((float) end / frameCount) * _duration); const char* repeat = pClip->getString("repeatCount"); if (repeat) { if (strcmp(repeat, ANIMATION_INDEFINITE_STR) == 0) { clip->setRepeatCount(AnimationClip::REPEAT_INDEFINITE); } else { float value; sscanf(repeat, "%f", &value); clip->setRepeatCount(value); } } const char* speed = pClip->getString("speed"); if (speed) { float value; sscanf(speed, "%f", &value); clip->setSpeed(value); } pClip = animationProperties->getNextNamespace(); } } void Animation::addClip(AnimationClip* clip) { if (_clips == NULL) _clips = new std::vector<AnimationClip*>; _clips->push_back(clip); } AnimationClip* Animation::findClip(const char* id) const { if (_clips) { AnimationClip* clip = NULL; unsigned int clipCount = _clips->size(); for (unsigned int i = 0; i < clipCount; i++) { clip = _clips->at(i); if (clip->_id.compare(id) == 0) { return _clips->at(i); } } } return NULL; } Animation::Channel* Animation::createChannel(AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned long* keyTimes, float* keyValues, unsigned int type) { unsigned int propertyComponentCount = target->getAnimationPropertyComponentCount(propertyId); assert(propertyComponentCount > 0); Curve* curve = Curve::create(keyCount, propertyComponentCount); if (target->_targetType == AnimationTarget::TRANSFORM) setTransformRotationOffset(curve, propertyId); unsigned long lowest = keyTimes[0]; unsigned long duration = keyTimes[keyCount-1] - lowest; float* normalizedKeyTimes = new float[keyCount]; normalizedKeyTimes[0] = 0.0f; curve->setPoint(0, normalizedKeyTimes[0], keyValues, (Curve::InterpolationType) type); unsigned int pointOffset = propertyComponentCount; unsigned int i = 1; for (; i < keyCount - 1; i++) { normalizedKeyTimes[i] = (float) (keyTimes[i] - lowest) / (float) duration; curve->setPoint(i, normalizedKeyTimes[i], (keyValues + pointOffset), (Curve::InterpolationType) type); pointOffset += propertyComponentCount; } i = keyCount - 1; normalizedKeyTimes[i] = 1.0f; curve->setPoint(i, normalizedKeyTimes[i], keyValues + pointOffset, (Curve::InterpolationType) type); SAFE_DELETE(normalizedKeyTimes); Channel* channel = new Channel(this, target, propertyId, curve, duration); curve->release(); addChannel(channel); return channel; } Animation::Channel* Animation::createChannel(AnimationTarget* target, int propertyId, unsigned int keyCount, unsigned long* keyTimes, float* keyValues, float* keyInValue, float* keyOutValue, unsigned int type) { unsigned int propertyComponentCount = target->getAnimationPropertyComponentCount(propertyId); assert(propertyComponentCount > 0); Curve* curve = Curve::create(keyCount, propertyComponentCount); if (target->_targetType == AnimationTarget::TRANSFORM) setTransformRotationOffset(curve, propertyId); unsigned long lowest = keyTimes[0]; unsigned long duration = keyTimes[keyCount-1] - lowest; float* normalizedKeyTimes = new float[keyCount]; normalizedKeyTimes[0] = 0.0f; curve->setPoint(0, normalizedKeyTimes[0], keyValues, (Curve::InterpolationType) type, keyInValue, keyOutValue); unsigned int pointOffset = propertyComponentCount; unsigned int i = 1; for (; i < keyCount - 1; i++) { normalizedKeyTimes[i] = (float) (keyTimes[i] - lowest) / (float) duration; curve->setPoint(i, normalizedKeyTimes[i], (keyValues + pointOffset), (Curve::InterpolationType) type, (keyInValue + pointOffset), (keyOutValue + pointOffset)); pointOffset += propertyComponentCount; } i = keyCount - 1; normalizedKeyTimes[i] = 1.0f; curve->setPoint(i, normalizedKeyTimes[i], keyValues + pointOffset, (Curve::InterpolationType) type, keyInValue + pointOffset, keyOutValue + pointOffset); SAFE_DELETE(normalizedKeyTimes); Channel* channel = new Channel(this, target, propertyId, curve, duration); curve->release(); addChannel(channel); return channel; } void Animation::addChannel(Channel* channel) { _channels.push_back(channel); if (channel->_duration > _duration) _duration = channel->_duration; } void Animation::removeChannel(Channel* channel) { std::vector<Animation::Channel*>::iterator itr = _channels.begin(); while (itr != _channels.end()) { Animation::Channel* chan = *itr; if (channel == chan) { _channels.erase(itr); return; } else { itr++; } } } void Animation::setTransformRotationOffset(Curve* curve, unsigned int propertyId) { switch (propertyId) { case Transform::ANIMATE_ROTATE: case Transform::ANIMATE_ROTATE_TRANSLATE: curve->setQuaternionOffset(ANIMATION_ROTATE_OFFSET); return; case Transform::ANIMATE_SCALE_ROTATE_TRANSLATE: curve->setQuaternionOffset(ANIMATION_SRT_OFFSET); return; } return; } Animation* Animation::clone() { Animation* animation = new Animation(getId()); return animation; } } <|endoftext|>
<commit_before>#ifndef TELEGRAMQT_PENDING_OPERATION_PRIVATE_HPP #define TELEGRAMQT_PENDING_OPERATION_PRIVATE_HPP #include "PendingOperation.hpp" namespace Telegram { class PendingOperationPrivate { public: Q_DECLARE_PUBLIC(PendingOperation) explicit PendingOperationPrivate(PendingOperation *parent) : q_ptr(parent) { } virtual ~PendingOperationPrivate() = default; static const PendingOperationPrivate *get(const PendingOperation *op) { return op->d; } virtual QObject *toQObject() { return nullptr; } virtual const QObject *toQObject() const { return nullptr; } QVariantHash m_errorDetails; bool m_finished = false; bool m_succeeded = true; PendingOperation *q_ptr = nullptr; }; } // Telegram namespace #endif // TELEGRAMQT_PENDING_OPERATION_PRIVATE_HPP <commit_msg>PendingOperation: Add a Private getter from mutable instance<commit_after>#ifndef TELEGRAMQT_PENDING_OPERATION_PRIVATE_HPP #define TELEGRAMQT_PENDING_OPERATION_PRIVATE_HPP #include "PendingOperation.hpp" namespace Telegram { class PendingOperationPrivate { public: Q_DECLARE_PUBLIC(PendingOperation) explicit PendingOperationPrivate(PendingOperation *parent) : q_ptr(parent) { } virtual ~PendingOperationPrivate() = default; static const PendingOperationPrivate *get(const PendingOperation *op) { return op->d; } static PendingOperationPrivate *get(PendingOperation *op) { return op->d; } virtual QObject *toQObject() { return nullptr; } virtual const QObject *toQObject() const { return nullptr; } QVariantHash m_errorDetails; bool m_finished = false; bool m_succeeded = true; PendingOperation *q_ptr = nullptr; }; } // Telegram namespace #endif // TELEGRAMQT_PENDING_OPERATION_PRIVATE_HPP <|endoftext|>
<commit_before><commit_msg>Planning: added more checks on whether an obstacle should be ignored or not.<commit_after><|endoftext|>
<commit_before>// Copyright 2004-present Facebook. All Rights Reserved. #include "UIManagerBinding.h" #include <react/debug/SystraceSection.h> #include <jsi/JSIDynamic.h> namespace facebook { namespace react { static jsi::Object getModule( jsi::Runtime &runtime, const std::string &moduleName) { auto batchedBridge = runtime.global().getPropertyAsObject(runtime, "__fbBatchedBridge"); auto getCallableModule = batchedBridge.getPropertyAsFunction(runtime, "getCallableModule"); auto module = getCallableModule .callWithThis( runtime, batchedBridge, {jsi::String::createFromUtf8(runtime, moduleName)}) .asObject(runtime); return module; } void UIManagerBinding::install( jsi::Runtime &runtime, std::shared_ptr<UIManagerBinding> uiManagerBinding) { auto uiManagerModuleName = "nativeFabricUIManager"; auto object = jsi::Object::createFromHostObject(runtime, uiManagerBinding); runtime.global().setProperty(runtime, uiManagerModuleName, std::move(object)); } UIManagerBinding::UIManagerBinding(std::unique_ptr<UIManager> uiManager) : uiManager_(std::move(uiManager)) {} void UIManagerBinding::startSurface( jsi::Runtime &runtime, SurfaceId surfaceId, const std::string &moduleName, const folly::dynamic &initalProps) const { folly::dynamic parameters = folly::dynamic::object(); parameters["rootTag"] = surfaceId; parameters["initialProps"] = initalProps; auto module = getModule(runtime, "AppRegistry"); auto method = module.getPropertyAsFunction(runtime, "runApplication"); method.callWithThis( runtime, module, {jsi::String::createFromUtf8(runtime, moduleName), jsi::valueFromDynamic(runtime, parameters)}); } void UIManagerBinding::stopSurface(jsi::Runtime &runtime, SurfaceId surfaceId) const { auto module = getModule(runtime, "ReactFabric"); auto method = module.getPropertyAsFunction(runtime, "unmountComponentAtNode"); method.callWithThis(runtime, module, {jsi::Value{surfaceId}}); } void UIManagerBinding::dispatchEvent( jsi::Runtime &runtime, const EventTarget *eventTarget, const std::string &type, const folly::dynamic &payload) const { auto eventTargetValue = jsi::Value::null(); if (eventTarget) { SystraceSection s("UIManagerBinding::JSIDispatchFabricEventToTarget"); auto &eventTargetWrapper = static_cast<const EventTargetWrapper &>(*eventTarget); eventTargetValue = eventTargetWrapper.instanceHandle.lock(runtime); if (eventTargetValue.isUndefined()) { return; } } auto &eventHandlerWrapper = static_cast<const EventHandlerWrapper &>(*eventHandler_); eventHandlerWrapper.callback.call( runtime, {std::move(eventTargetValue), jsi::String::createFromUtf8(runtime, type), jsi::valueFromDynamic(runtime, payload)}); } void UIManagerBinding::invalidate() const { uiManager_->setShadowTreeRegistry(nullptr); uiManager_->setDelegate(nullptr); } jsi::Value UIManagerBinding::get( jsi::Runtime &runtime, const jsi::PropNameID &name) { auto methodName = name.utf8(runtime); auto &uiManager = *uiManager_; // Semantic: Creates a new node with given pieces. if (methodName == "createNode") { return jsi::Function::createFromHostFunction( runtime, name, 5, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { return valueFromShadowNode( runtime, uiManager.createNode( tagFromValue(runtime, arguments[0]), componentNameFromValue(runtime, arguments[1]), surfaceIdFromValue(runtime, arguments[2]), rawPropsFromValue(runtime, arguments[3]), eventTargetFromValue(runtime, arguments[4]))); }); } // Semantic: Clones the node with *same* props and *same* children. if (methodName == "cloneNode") { return jsi::Function::createFromHostFunction( runtime, name, 1, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { return valueFromShadowNode( runtime, uiManager.cloneNode(shadowNodeFromValue(runtime, arguments[0]))); }); } // Semantic: Clones the node with *same* props and *empty* children. if (methodName == "cloneNodeWithNewChildren") { return jsi::Function::createFromHostFunction( runtime, name, 1, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { return valueFromShadowNode( runtime, uiManager.cloneNode( shadowNodeFromValue(runtime, arguments[0]), ShadowNode::emptySharedShadowNodeSharedList())); }); } // Semantic: Clones the node with *given* props and *same* children. if (methodName == "cloneNodeWithNewProps") { return jsi::Function::createFromHostFunction( runtime, name, 2, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { return valueFromShadowNode( runtime, uiManager.cloneNode( shadowNodeFromValue(runtime, arguments[0]), nullptr, rawPropsFromValue(runtime, arguments[1]))); }); } // Semantic: Clones the node with *given* props and *empty* children. if (methodName == "cloneNodeWithNewChildrenAndProps") { return jsi::Function::createFromHostFunction( runtime, name, 2, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { return valueFromShadowNode( runtime, uiManager.cloneNode( shadowNodeFromValue(runtime, arguments[0]), ShadowNode::emptySharedShadowNodeSharedList(), rawPropsFromValue(runtime, arguments[1]))); }); } if (methodName == "appendChild") { return jsi::Function::createFromHostFunction( runtime, name, 2, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { uiManager.appendChild( shadowNodeFromValue(runtime, arguments[0]), shadowNodeFromValue(runtime, arguments[1])); return jsi::Value::undefined(); }); } if (methodName == "createChildSet") { return jsi::Function::createFromHostFunction( runtime, name, 1, [](jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { auto shadowNodeList = std::make_shared<SharedShadowNodeList>(SharedShadowNodeList({})); return valueFromShadowNodeList(runtime, shadowNodeList); }); } if (methodName == "appendChildToSet") { return jsi::Function::createFromHostFunction( runtime, name, 2, [](jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { auto shadowNodeList = shadowNodeListFromValue(runtime, arguments[0]); auto shadowNode = shadowNodeFromValue(runtime, arguments[1]); shadowNodeList->push_back(shadowNode); return jsi::Value::undefined(); }); } if (methodName == "completeRoot") { return jsi::Function::createFromHostFunction( runtime, name, 2, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { uiManager.completeSurface( surfaceIdFromValue(runtime, arguments[0]), shadowNodeListFromValue(runtime, arguments[1])); return jsi::Value::undefined(); }); } if (methodName == "registerEventHandler") { return jsi::Function::createFromHostFunction( runtime, name, 1, [this]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { auto eventHandler = arguments[0].getObject(runtime).getFunction(runtime); eventHandler_ = std::make_unique<EventHandlerWrapper>(std::move(eventHandler)); return jsi::Value::undefined(); }); } if (methodName == "getRelativeLayoutMetrics") { return jsi::Function::createFromHostFunction( runtime, name, 2, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { auto layoutMetrics = uiManager.getRelativeLayoutMetrics( *shadowNodeFromValue(runtime, arguments[0]), shadowNodeFromValue(runtime, arguments[1]).get()); auto frame = layoutMetrics.frame; auto result = jsi::Object(runtime); result.setProperty(runtime, "left", frame.origin.x); result.setProperty(runtime, "top", frame.origin.y); result.setProperty(runtime, "width", frame.size.width); result.setProperty(runtime, "height", frame.size.height); return result; }); } if (methodName == "setNativeProps") { return jsi::Function::createFromHostFunction( runtime, name, 2, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { uiManager.setNativeProps( shadowNodeFromValue(runtime, arguments[0]), rawPropsFromValue(runtime, arguments[1])); return jsi::Value::undefined(); }); } return jsi::Value::undefined(); } } // namespace react } // namespace facebook <commit_msg>Fabric: Fixed incorrect systrace marker in UIManagerBinding::dispatchEvent<commit_after>// Copyright 2004-present Facebook. All Rights Reserved. #include "UIManagerBinding.h" #include <react/debug/SystraceSection.h> #include <jsi/JSIDynamic.h> namespace facebook { namespace react { static jsi::Object getModule( jsi::Runtime &runtime, const std::string &moduleName) { auto batchedBridge = runtime.global().getPropertyAsObject(runtime, "__fbBatchedBridge"); auto getCallableModule = batchedBridge.getPropertyAsFunction(runtime, "getCallableModule"); auto module = getCallableModule .callWithThis( runtime, batchedBridge, {jsi::String::createFromUtf8(runtime, moduleName)}) .asObject(runtime); return module; } void UIManagerBinding::install( jsi::Runtime &runtime, std::shared_ptr<UIManagerBinding> uiManagerBinding) { auto uiManagerModuleName = "nativeFabricUIManager"; auto object = jsi::Object::createFromHostObject(runtime, uiManagerBinding); runtime.global().setProperty(runtime, uiManagerModuleName, std::move(object)); } UIManagerBinding::UIManagerBinding(std::unique_ptr<UIManager> uiManager) : uiManager_(std::move(uiManager)) {} void UIManagerBinding::startSurface( jsi::Runtime &runtime, SurfaceId surfaceId, const std::string &moduleName, const folly::dynamic &initalProps) const { folly::dynamic parameters = folly::dynamic::object(); parameters["rootTag"] = surfaceId; parameters["initialProps"] = initalProps; auto module = getModule(runtime, "AppRegistry"); auto method = module.getPropertyAsFunction(runtime, "runApplication"); method.callWithThis( runtime, module, {jsi::String::createFromUtf8(runtime, moduleName), jsi::valueFromDynamic(runtime, parameters)}); } void UIManagerBinding::stopSurface(jsi::Runtime &runtime, SurfaceId surfaceId) const { auto module = getModule(runtime, "ReactFabric"); auto method = module.getPropertyAsFunction(runtime, "unmountComponentAtNode"); method.callWithThis(runtime, module, {jsi::Value{surfaceId}}); } void UIManagerBinding::dispatchEvent( jsi::Runtime &runtime, const EventTarget *eventTarget, const std::string &type, const folly::dynamic &payload) const { SystraceSection s("UIManagerBinding::dispatchEvent"); auto eventTargetValue = jsi::Value::null(); if (eventTarget) { auto &eventTargetWrapper = static_cast<const EventTargetWrapper &>(*eventTarget); eventTargetValue = eventTargetWrapper.instanceHandle.lock(runtime); if (eventTargetValue.isUndefined()) { return; } } auto &eventHandlerWrapper = static_cast<const EventHandlerWrapper &>(*eventHandler_); eventHandlerWrapper.callback.call( runtime, {std::move(eventTargetValue), jsi::String::createFromUtf8(runtime, type), jsi::valueFromDynamic(runtime, payload)}); } void UIManagerBinding::invalidate() const { uiManager_->setShadowTreeRegistry(nullptr); uiManager_->setDelegate(nullptr); } jsi::Value UIManagerBinding::get( jsi::Runtime &runtime, const jsi::PropNameID &name) { auto methodName = name.utf8(runtime); auto &uiManager = *uiManager_; // Semantic: Creates a new node with given pieces. if (methodName == "createNode") { return jsi::Function::createFromHostFunction( runtime, name, 5, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { return valueFromShadowNode( runtime, uiManager.createNode( tagFromValue(runtime, arguments[0]), componentNameFromValue(runtime, arguments[1]), surfaceIdFromValue(runtime, arguments[2]), rawPropsFromValue(runtime, arguments[3]), eventTargetFromValue(runtime, arguments[4]))); }); } // Semantic: Clones the node with *same* props and *same* children. if (methodName == "cloneNode") { return jsi::Function::createFromHostFunction( runtime, name, 1, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { return valueFromShadowNode( runtime, uiManager.cloneNode(shadowNodeFromValue(runtime, arguments[0]))); }); } // Semantic: Clones the node with *same* props and *empty* children. if (methodName == "cloneNodeWithNewChildren") { return jsi::Function::createFromHostFunction( runtime, name, 1, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { return valueFromShadowNode( runtime, uiManager.cloneNode( shadowNodeFromValue(runtime, arguments[0]), ShadowNode::emptySharedShadowNodeSharedList())); }); } // Semantic: Clones the node with *given* props and *same* children. if (methodName == "cloneNodeWithNewProps") { return jsi::Function::createFromHostFunction( runtime, name, 2, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { return valueFromShadowNode( runtime, uiManager.cloneNode( shadowNodeFromValue(runtime, arguments[0]), nullptr, rawPropsFromValue(runtime, arguments[1]))); }); } // Semantic: Clones the node with *given* props and *empty* children. if (methodName == "cloneNodeWithNewChildrenAndProps") { return jsi::Function::createFromHostFunction( runtime, name, 2, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { return valueFromShadowNode( runtime, uiManager.cloneNode( shadowNodeFromValue(runtime, arguments[0]), ShadowNode::emptySharedShadowNodeSharedList(), rawPropsFromValue(runtime, arguments[1]))); }); } if (methodName == "appendChild") { return jsi::Function::createFromHostFunction( runtime, name, 2, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { uiManager.appendChild( shadowNodeFromValue(runtime, arguments[0]), shadowNodeFromValue(runtime, arguments[1])); return jsi::Value::undefined(); }); } if (methodName == "createChildSet") { return jsi::Function::createFromHostFunction( runtime, name, 1, [](jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { auto shadowNodeList = std::make_shared<SharedShadowNodeList>(SharedShadowNodeList({})); return valueFromShadowNodeList(runtime, shadowNodeList); }); } if (methodName == "appendChildToSet") { return jsi::Function::createFromHostFunction( runtime, name, 2, [](jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { auto shadowNodeList = shadowNodeListFromValue(runtime, arguments[0]); auto shadowNode = shadowNodeFromValue(runtime, arguments[1]); shadowNodeList->push_back(shadowNode); return jsi::Value::undefined(); }); } if (methodName == "completeRoot") { return jsi::Function::createFromHostFunction( runtime, name, 2, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { uiManager.completeSurface( surfaceIdFromValue(runtime, arguments[0]), shadowNodeListFromValue(runtime, arguments[1])); return jsi::Value::undefined(); }); } if (methodName == "registerEventHandler") { return jsi::Function::createFromHostFunction( runtime, name, 1, [this]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { auto eventHandler = arguments[0].getObject(runtime).getFunction(runtime); eventHandler_ = std::make_unique<EventHandlerWrapper>(std::move(eventHandler)); return jsi::Value::undefined(); }); } if (methodName == "getRelativeLayoutMetrics") { return jsi::Function::createFromHostFunction( runtime, name, 2, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { auto layoutMetrics = uiManager.getRelativeLayoutMetrics( *shadowNodeFromValue(runtime, arguments[0]), shadowNodeFromValue(runtime, arguments[1]).get()); auto frame = layoutMetrics.frame; auto result = jsi::Object(runtime); result.setProperty(runtime, "left", frame.origin.x); result.setProperty(runtime, "top", frame.origin.y); result.setProperty(runtime, "width", frame.size.width); result.setProperty(runtime, "height", frame.size.height); return result; }); } if (methodName == "setNativeProps") { return jsi::Function::createFromHostFunction( runtime, name, 2, [&uiManager]( jsi::Runtime &runtime, const jsi::Value &thisValue, const jsi::Value *arguments, size_t count) -> jsi::Value { uiManager.setNativeProps( shadowNodeFromValue(runtime, arguments[0]), rawPropsFromValue(runtime, arguments[1])); return jsi::Value::undefined(); }); } return jsi::Value::undefined(); } } // namespace react } // namespace facebook <|endoftext|>
<commit_before>/* * @file opencog/dynamics/openpsi/PsiDemandUpdaterAgent.cc * * @author Jinhua Chua <[email protected]> * @date 2011-11-22 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <boost/tokenizer.hpp> #include <boost/lexical_cast.hpp> #include <opencog/atomspace/SimpleTruthValue.h> #include <opencog/spacetime/SpaceTime.h> #include <opencog/guile/SchemeEval.h> #include <opencog/util/Config.h> // TODO: the methods from AtomSpaceUtil to openpsi directory #include <opencog/embodiment/AtomSpaceExtensions/AtomSpaceUtil.h> #include "PsiDemandUpdaterAgent.h" using namespace opencog; bool PsiDemandUpdaterAgent::Demand::runUpdater(AtomSpace & atomSpace) { std::string demandUpdater = this->demandName + "DemandUpdater"; #if HAVE_GUILE // Initialize scheme evaluator SchemeEval evaluator1(&atomSpace); std::string scheme_expression, scheme_return_value; scheme_expression = "( " + demandUpdater + " )"; // Run the Procedure that update Demands and get the updated value scheme_return_value = evaluator1.eval(scheme_expression); if ( evaluator1.eval_error() ) { logger().error("PsiDemandUpdaterAgent::Demand::%s - " "Failed to execute '%s'", __FUNCTION__, scheme_expression.c_str()); return false; } // Store the updated demand value (result) this->currentDemandValue = atof( scheme_return_value.c_str() ); logger().debug("PsiDemandUpdaterAgent::Demand::%s - " "The level of demand '%s' will be set to '%f'", __FUNCTION__, this->demandName.c_str(), this->currentDemandValue); #endif // HAVE_GUILE return true; } bool PsiDemandUpdaterAgent::Demand::updateDemandGoal (AtomSpace & atomSpace, const octime_t timeStamp) { // Get the GroundedPredicateNode "fuzzy_within" Handle hGroundedPredicateNode = atomSpace.getOutgoing(hFuzzyWithin, 0); bool isNotPredicateNode = atomSpace.getType(hGroundedPredicateNode) != GROUNDED_PREDICATE_NODE; bool isOutgoingNotPredicateNode = atomSpace.getType(atomSpace.getOutgoing(hGroundedPredicateNode, 0)) != GROUNDED_PREDICATE_NODE; if ( hGroundedPredicateNode == opencog::Handle::UNDEFINED || (isNotPredicateNode && isOutgoingNotPredicateNode)) { logger().error("PsiDemandUpdaterAgent::Demand::%s - Expect a GroundedPredicateNode for demand '%s'. But got '%s'", __FUNCTION__, this->demandName.c_str(), atomSpace.atomAsString(hGroundedPredicateNode).c_str()); return false; } // Get ListLink containing ExecutionOutputLink and parameters of FuzzyWithin Handle hListLink = atomSpace.getOutgoing(hFuzzyWithin, 1); if ( hListLink == opencog::Handle::UNDEFINED || atomSpace.getType(hListLink) != LIST_LINK || atomSpace.getArity(hListLink) != 3 ) { logger().error("PsiDemandUpdaterAgent::Demand::%s - Expect a ListLink for demand '%s' with three arity (parameters of FuzzyWithin). But got '%s'", __FUNCTION__, this->demandName.c_str(), atomSpace.atomAsString(hListLink).c_str()); return false; } // Get the ExecutionOutputLink Handle hExecutionOutputLink = atomSpace.getOutgoing(hListLink, 2); if ( hExecutionOutputLink == opencog::Handle::UNDEFINED || atomSpace.getType(hExecutionOutputLink) != EXECUTION_OUTPUT_LINK || atomSpace.getArity(hExecutionOutputLink) != 1 ) { logger().error("PsiDemandUpdaterAgent::Demand::%s - Expect an ExecutionOutputLink (updater) for demand '%s' with only one arity. But got '%s'", __FUNCTION__, this->demandName.c_str(), atomSpace.atomAsString(hExecutionOutputLink).c_str()); return false; } #if HAVE_GUILE // Initialize scheme evaluator SchemeEval evaluator1(&atomSpace); std::string scheme_expression, scheme_return_value; // Store the updated Demand levels to AtomSpace // set_modulator_or_demand_value would create a new NumberNode and SilarityLink // // Note: Since OpenCog would forget (remove) those Nodes and Links gradually, // unless you create them to be permanent, don't worry about the overflow of memory. scheme_expression = "( set_modulator_or_demand_value \"" + this->demandName + "Demand\" " + boost::lexical_cast<std::string>(this->currentDemandValue) + " " + boost::lexical_cast<std::string>(timeStamp) + " " + ")"; // Run the scheme procedure scheme_return_value = evaluator1.eval(scheme_expression); if ( evaluator1.eval_error() ) { logger().error( "PsiDemandUpdaterAgent::Demand::%s - Failed to execute '%s'", __FUNCTION__, scheme_expression.c_str()); return false; } logger().debug("PsiDemandUpdaterAgent::Demand::%s - Updated the value of '%s' demand to %f and store it to AtomSpace", __FUNCTION__, this->demandName.c_str(), this->currentDemandValue); // Get the fuzzy_within scheme procedure name, which should be "fuzzy_within" std::string demandGoalEvaluator = atomSpace.getName(hGroundedPredicateNode); // Get min/ max acceptable values std::string minValueStr = atomSpace.getName( atomSpace.getOutgoing(hListLink, 0) ); std::string maxValueStr = atomSpace.getName( atomSpace.getOutgoing(hListLink, 1) ); scheme_expression = "( fuzzy_within " + boost::lexical_cast<std::string>(this->currentDemandValue) + " " + minValueStr + " " + maxValueStr + " " + "100" ")"; // Run the scheme procedure scheme_return_value = evaluator1.eval(scheme_expression); if ( evaluator1.eval_error() ) { logger().error( "PsiDemandUpdaterAgent::Demand::%s - Failed to execute '%s' for demand '%s'", __FUNCTION__, scheme_expression.c_str(), this->demandName.c_str()); return false; } // Store the result and update TruthValue of EvaluationLinkDemandGoal and EvaluationLinkFuzzyWithin // TODO: Use PLN forward chainer to handle this? TruthValuePtr demand_satisfaction = SimpleTruthValue::createTV(atof(scheme_return_value.c_str()), 1.0f); atomSpace.setTV(this->hDemandGoal, demand_satisfaction); // Add AtTimeLink around EvaluationLink of DemandGoal, which is required by fishgram Handle atTimeLink = timeServer().addTimeInfo(this->hDemandGoal, timeStamp, demand_satisfaction ); // // Update the LatestLink std::string predicateName = this->demandName + "DemandGoal"; Handle demandPredicateNode = atomSpace.addNode(PREDICATE_NODE, predicateName.c_str()); std::vector <Handle> outgoings; Handle listLink = atomSpace.addLink(LIST_LINK, outgoings); outgoings.push_back(demandPredicateNode); outgoings.push_back(listLink); Handle evaluationLink = atomSpace.addLink(EVALUATION_LINK, outgoings); atomSpace.setTV(evaluationLink, demand_satisfaction); atTimeLink = timeServer().addTimeInfo(evaluationLink, timeStamp, demand_satisfaction); AtomSpaceUtil::updateLatestDemand(atomSpace, atTimeLink, demandPredicateNode); atomSpace.setTV( this->hFuzzyWithin, demand_satisfaction); this->currentDemandTruthValue = atof(scheme_return_value.c_str()); logger().debug( "PsiDemandUpdaterAgent::Demand::%s - The level (truth value) of DemandGoal '%s' has been set to %s", __FUNCTION__, this->demandName.c_str(), scheme_return_value.c_str()); return true; #else // HAVE_GUILE logger().error("PsiDemandUpdaterAgent::Demand::%s - guile is required", __FUNCTION__); return false; #endif // HAVE_GUILE } PsiDemandUpdaterAgent::~PsiDemandUpdaterAgent() { logger().info("[PsiDemandUpdaterAgent] destructor"); } PsiDemandUpdaterAgent::PsiDemandUpdaterAgent(CogServer& cs) : Agent(cs) { this->cycleCount = 0; // Force the Agent initialize itself during its first cycle. this->forceInitNextCycle(); } void PsiDemandUpdaterAgent::init() { logger().debug( "PsiDemandUpdaterAgent::%s - Initialize the Agent [cycle = %d]", __FUNCTION__, this->cycleCount); // Get AtomSpace AtomSpace& atomSpace = _cogserver.getAtomSpace(); // Clear old demandList this->demandList.clear(); // Get demand names from the configuration file std::string demandNames = config()["PSI_DEMANDS"]; // Process Demands one by one boost::char_separator<char> sep(", "); boost::tokenizer< boost::char_separator<char> > demandNamesTok (demandNames, sep); std::string demandName, demandUpdater; Handle hDemandGoal, hFuzzyWithin; // Process Demands one by one for ( boost::tokenizer< boost::char_separator<char> >::iterator iDemandName = demandNamesTok.begin(); iDemandName != demandNamesTok.end(); iDemandName ++ ) { demandName = (*iDemandName); demandUpdater = demandName + "DemandUpdater"; // Search the corresponding SimultaneousEquivalenceLink if ( !AtomSpaceUtil::getDemandEvaluationLinks(atomSpace, demandName, hDemandGoal, hFuzzyWithin) ) { logger().warn( "PsiDemandUpdaterAgent::%s - Failed to get EvaluationLinks for demand '%s' [cycle = %d]", __FUNCTION__, demandName.c_str(), this->cycleCount); continue; } this->demandList.push_back(Demand(demandName, hDemandGoal, hFuzzyWithin)); logger().debug("PsiDemandUpdaterAgent::%s - Store the meta data of demand '%s' successfully [cycle = %d]", __FUNCTION__, demandName.c_str(), this->cycleCount); }// for // Avoid initialize during next cycle this->bInitialized = true; hasPsiDemandUpdaterForTheFirstTime = false; } void PsiDemandUpdaterAgent::run() { this->cycleCount = _cogserver.getCycleCount(); logger().debug( "PsiDemandUpdaterAgent::%s - Executing run %d times", __FUNCTION__, this->cycleCount); // Get AtomSpace AtomSpace& atomSpace = _cogserver.getAtomSpace(); logger().debug("got atomspace"); // Get current time stamp //unsigned long timeStamp = oac->getPAI().getLatestSimWorldTimestamp(); TimeServer timeServer(atomSpace); octime_t timeStamp = timeServer.getLatestTimestamp(); logger().debug("timestamp %s", timeStamp); // Initialize the Agent (demandList etc) if ( !this->bInitialized ) this->init(); // Update demand values for (Demand & demand : this->demandList) { logger().debug("PsiDemandUpdaterAgent::%s - Going to run updaters for demand '%s' [cycle = %d]", __FUNCTION__, demand.getDemandName().c_str(), this->cycleCount); demand.runUpdater(atomSpace); } // Update Demand Goals for (Demand & demand : this->demandList) { logger().debug("PsiDemandUpdaterAgent::%s - Going to set the updated value to AtomSpace for demand '%s' [cycle = %d]", __FUNCTION__, demand.getDemandName().c_str(), this->cycleCount); demand.updateDemandGoal(atomSpace, timeStamp); } hasPsiDemandUpdaterForTheFirstTime = true; } double PsiDemandUpdaterAgent::getDemandValue(string demanName) const { for (const Demand & demand : this->demandList) { if ( demand.getDemandName() == demanName) return demand.getDemandValue(); } return 0.0000; } <commit_msg> remove TimeServer<commit_after>/* * @file opencog/dynamics/openpsi/PsiDemandUpdaterAgent.cc * * @author Jinhua Chua <[email protected]> * @date 2011-11-22 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <boost/tokenizer.hpp> #include <boost/lexical_cast.hpp> #include <opencog/atomspace/SimpleTruthValue.h> #include <opencog/spacetime/SpaceTime.h> #include <opencog/guile/SchemeEval.h> #include <opencog/util/Config.h> #include <opencog/util/octime.h> // TODO: the methods from AtomSpaceUtil to openpsi directory #include <opencog/embodiment/AtomSpaceExtensions/AtomSpaceUtil.h> #include "PsiDemandUpdaterAgent.h" using namespace opencog; bool PsiDemandUpdaterAgent::Demand::runUpdater(AtomSpace & atomSpace) { std::string demandUpdater = this->demandName + "DemandUpdater"; #if HAVE_GUILE // Initialize scheme evaluator SchemeEval evaluator1(&atomSpace); std::string scheme_expression, scheme_return_value; scheme_expression = "( " + demandUpdater + " )"; // Run the Procedure that update Demands and get the updated value scheme_return_value = evaluator1.eval(scheme_expression); if ( evaluator1.eval_error() ) { logger().error("PsiDemandUpdaterAgent::Demand::%s - " "Failed to execute '%s'", __FUNCTION__, scheme_expression.c_str()); return false; } // Store the updated demand value (result) this->currentDemandValue = atof( scheme_return_value.c_str() ); logger().debug("PsiDemandUpdaterAgent::Demand::%s - " "The level of demand '%s' will be set to '%f'", __FUNCTION__, this->demandName.c_str(), this->currentDemandValue); #endif // HAVE_GUILE return true; } bool PsiDemandUpdaterAgent::Demand::updateDemandGoal (AtomSpace & atomSpace, const octime_t timeStamp) { // Get the GroundedPredicateNode "fuzzy_within" Handle hGroundedPredicateNode = atomSpace.getOutgoing(hFuzzyWithin, 0); bool isNotPredicateNode = atomSpace.getType(hGroundedPredicateNode) != GROUNDED_PREDICATE_NODE; bool isOutgoingNotPredicateNode = atomSpace.getType(atomSpace.getOutgoing(hGroundedPredicateNode, 0)) != GROUNDED_PREDICATE_NODE; if ( hGroundedPredicateNode == opencog::Handle::UNDEFINED || (isNotPredicateNode && isOutgoingNotPredicateNode)) { logger().error("PsiDemandUpdaterAgent::Demand::%s - Expect a GroundedPredicateNode for demand '%s'. But got '%s'", __FUNCTION__, this->demandName.c_str(), atomSpace.atomAsString(hGroundedPredicateNode).c_str()); return false; } // Get ListLink containing ExecutionOutputLink and parameters of FuzzyWithin Handle hListLink = atomSpace.getOutgoing(hFuzzyWithin, 1); if ( hListLink == opencog::Handle::UNDEFINED || atomSpace.getType(hListLink) != LIST_LINK || atomSpace.getArity(hListLink) != 3 ) { logger().error("PsiDemandUpdaterAgent::Demand::%s - Expect a ListLink for demand '%s' with three arity (parameters of FuzzyWithin). But got '%s'", __FUNCTION__, this->demandName.c_str(), atomSpace.atomAsString(hListLink).c_str()); return false; } // Get the ExecutionOutputLink Handle hExecutionOutputLink = atomSpace.getOutgoing(hListLink, 2); if ( hExecutionOutputLink == opencog::Handle::UNDEFINED || atomSpace.getType(hExecutionOutputLink) != EXECUTION_OUTPUT_LINK || atomSpace.getArity(hExecutionOutputLink) != 1 ) { logger().error("PsiDemandUpdaterAgent::Demand::%s - Expect an ExecutionOutputLink (updater) for demand '%s' with only one arity. But got '%s'", __FUNCTION__, this->demandName.c_str(), atomSpace.atomAsString(hExecutionOutputLink).c_str()); return false; } #if HAVE_GUILE // Initialize scheme evaluator SchemeEval evaluator1(&atomSpace); std::string scheme_expression, scheme_return_value; // Store the updated Demand levels to AtomSpace // set_modulator_or_demand_value would create a new NumberNode and SilarityLink // // Note: Since OpenCog would forget (remove) those Nodes and Links gradually, // unless you create them to be permanent, don't worry about the overflow of memory. scheme_expression = "( set_modulator_or_demand_value \"" + this->demandName + "Demand\" " + boost::lexical_cast<std::string>(this->currentDemandValue) + " " + boost::lexical_cast<std::string>(timeStamp) + " " + ")"; // Run the scheme procedure scheme_return_value = evaluator1.eval(scheme_expression); if ( evaluator1.eval_error() ) { logger().error( "PsiDemandUpdaterAgent::Demand::%s - Failed to execute '%s'", __FUNCTION__, scheme_expression.c_str()); return false; } logger().debug("PsiDemandUpdaterAgent::Demand::%s - Updated the value of '%s' demand to %f and store it to AtomSpace", __FUNCTION__, this->demandName.c_str(), this->currentDemandValue); // Get the fuzzy_within scheme procedure name, which should be "fuzzy_within" std::string demandGoalEvaluator = atomSpace.getName(hGroundedPredicateNode); // Get min/ max acceptable values std::string minValueStr = atomSpace.getName( atomSpace.getOutgoing(hListLink, 0) ); std::string maxValueStr = atomSpace.getName( atomSpace.getOutgoing(hListLink, 1) ); scheme_expression = "( fuzzy_within " + boost::lexical_cast<std::string>(this->currentDemandValue) + " " + minValueStr + " " + maxValueStr + " " + "100" ")"; // Run the scheme procedure scheme_return_value = evaluator1.eval(scheme_expression); if ( evaluator1.eval_error() ) { logger().error( "PsiDemandUpdaterAgent::Demand::%s - Failed to execute '%s' for demand '%s'", __FUNCTION__, scheme_expression.c_str(), this->demandName.c_str()); return false; } // Store the result and update TruthValue of EvaluationLinkDemandGoal and EvaluationLinkFuzzyWithin // TODO: Use PLN forward chainer to handle this? TruthValuePtr demand_satisfaction = SimpleTruthValue::createTV(atof(scheme_return_value.c_str()), 1.0f); atomSpace.setTV(this->hDemandGoal, demand_satisfaction); // Add AtTimeLink around EvaluationLink of DemandGoal, which is required by fishgram Handle atTimeLink = timeServer().addTimeInfo(this->hDemandGoal, timeStamp, demand_satisfaction ); // // Update the LatestLink std::string predicateName = this->demandName + "DemandGoal"; Handle demandPredicateNode = atomSpace.addNode(PREDICATE_NODE, predicateName.c_str()); std::vector <Handle> outgoings; Handle listLink = atomSpace.addLink(LIST_LINK, outgoings); outgoings.push_back(demandPredicateNode); outgoings.push_back(listLink); Handle evaluationLink = atomSpace.addLink(EVALUATION_LINK, outgoings); atomSpace.setTV(evaluationLink, demand_satisfaction); atTimeLink = timeServer().addTimeInfo(evaluationLink, timeStamp, demand_satisfaction); AtomSpaceUtil::updateLatestDemand(atomSpace, atTimeLink, demandPredicateNode); atomSpace.setTV( this->hFuzzyWithin, demand_satisfaction); this->currentDemandTruthValue = atof(scheme_return_value.c_str()); logger().debug( "PsiDemandUpdaterAgent::Demand::%s - The level (truth value) of DemandGoal '%s' has been set to %s", __FUNCTION__, this->demandName.c_str(), scheme_return_value.c_str()); return true; #else // HAVE_GUILE logger().error("PsiDemandUpdaterAgent::Demand::%s - guile is required", __FUNCTION__); return false; #endif // HAVE_GUILE } PsiDemandUpdaterAgent::~PsiDemandUpdaterAgent() { logger().info("[PsiDemandUpdaterAgent] destructor"); } PsiDemandUpdaterAgent::PsiDemandUpdaterAgent(CogServer& cs) : Agent(cs) { this->cycleCount = 0; // This is needed for time stamping initReferenceTime(); // Force the Agent initialize itself during its first cycle. this->forceInitNextCycle(); } void PsiDemandUpdaterAgent::init() { logger().debug( "PsiDemandUpdaterAgent::%s - Initialize the Agent [cycle = %d]", __FUNCTION__, this->cycleCount); // Get AtomSpace AtomSpace& atomSpace = _cogserver.getAtomSpace(); // Clear old demandList this->demandList.clear(); // Get demand names from the configuration file std::string demandNames = config()["PSI_DEMANDS"]; // Process Demands one by one boost::char_separator<char> sep(", "); boost::tokenizer< boost::char_separator<char> > demandNamesTok (demandNames, sep); std::string demandName, demandUpdater; Handle hDemandGoal, hFuzzyWithin; // Process Demands one by one for ( boost::tokenizer< boost::char_separator<char> >::iterator iDemandName = demandNamesTok.begin(); iDemandName != demandNamesTok.end(); iDemandName ++ ) { demandName = (*iDemandName); demandUpdater = demandName + "DemandUpdater"; // Search the corresponding SimultaneousEquivalenceLink if ( !AtomSpaceUtil::getDemandEvaluationLinks(atomSpace, demandName, hDemandGoal, hFuzzyWithin) ) { logger().warn( "PsiDemandUpdaterAgent::%s - Failed to get EvaluationLinks for demand '%s' [cycle = %d]", __FUNCTION__, demandName.c_str(), this->cycleCount); continue; } this->demandList.push_back(Demand(demandName, hDemandGoal, hFuzzyWithin)); logger().debug("PsiDemandUpdaterAgent::%s - Store the meta data of demand '%s' successfully [cycle = %d]", __FUNCTION__, demandName.c_str(), this->cycleCount); }// for // Avoid initialize during next cycle this->bInitialized = true; hasPsiDemandUpdaterForTheFirstTime = false; } void PsiDemandUpdaterAgent::run() { this->cycleCount = _cogserver.getCycleCount(); logger().debug( "PsiDemandUpdaterAgent::%s - Executing run %d times", __FUNCTION__, this->cycleCount); // Get AtomSpace AtomSpace& atomSpace = _cogserver.getAtomSpace(); // Get current time stamp octime_t timeStamp = getElapsedMillis(); // Initialize the Agent (demandList etc) if ( !this->bInitialized ) this->init(); // Update demand values for (Demand & demand : this->demandList) { logger().debug("PsiDemandUpdaterAgent::%s - Going to run updaters for demand '%s' [cycle = %d]", __FUNCTION__, demand.getDemandName().c_str(), this->cycleCount); demand.runUpdater(atomSpace); } // Update Demand Goals for (Demand & demand : this->demandList) { logger().debug("PsiDemandUpdaterAgent::%s - Going to set the updated value to AtomSpace for demand '%s' [cycle = %d]", __FUNCTION__, demand.getDemandName().c_str(), this->cycleCount); demand.updateDemandGoal(atomSpace, timeStamp); } hasPsiDemandUpdaterForTheFirstTime = true; } double PsiDemandUpdaterAgent::getDemandValue(string demanName) const { for (const Demand & demand : this->demandList) { if ( demand.getDemandName() == demanName) return demand.getDemandValue(); } return 0.0000; } <|endoftext|>
<commit_before>// Ignore unused parameter warnings coming from cppunit headers #include <libmesh/ignore_warnings.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <libmesh/restore_warnings.h> #include <libmesh/libmesh.h> #include <libmesh/mesh.h> #include <libmesh/elem.h> #include <libmesh/mesh_generation.h> #include <libmesh/mesh_refinement.h> #include "test_comm.h" // THE CPPUNIT_TEST_SUITE_END macro expands to code that involves // std::auto_ptr, which in turn produces -Wdeprecated-declarations // warnings. These can be ignored in GCC as long as we wrap the // offending code in appropriate pragmas. We can't get away with a // single ignore_warnings.h inclusion at the beginning of this file, // since the libmesh headers pull in a restore_warnings.h at some // point. We also don't bother restoring warnings at the end of this // file since it's not a header. #include <libmesh/ignore_warnings.h> using namespace libMesh; class ExtraIntegersTest : public CppUnit::TestCase { /** * The goal of this test is to verify the ability to add extra * integer storage to a Mesh object, then set and query those extra * integers in the objects within the mesh. */ public: CPPUNIT_TEST_SUITE( ExtraIntegersTest ); CPPUNIT_TEST( testExtraIntegersEdge2 ); CPPUNIT_TEST_SUITE_END(); protected: // Helper function called by the test implementations, saves a few lines of code. void test_helper_1D(ElemType elem_type) { Mesh mesh(*TestCommWorld, /*dim=*/2); // Request some extra integers before building unsigned int i1 = mesh.add_elem_integer("i1"); MeshTools::Generation::build_line(mesh, /*nx=*/10, /*xmin=*/0., /*xmax=*/1., elem_type); for (const auto & elem : mesh.element_ptr_range()) { CPPUNIT_ASSERT_EQUAL(elem->n_extra_integers(), 1u); CPPUNIT_ASSERT_EQUAL(elem->get_extra_integer(i1), DofObject::invalid_id); elem->set_extra_integer(i1, dof_id_type(elem->point(0)(0)*100)); CPPUNIT_ASSERT_EQUAL(elem->get_extra_integer(i1), dof_id_type(elem->point(0)(0)*100)); } // Force (in parallel) a different partitioning - we'll simply put // everything on rank 0, which hopefully is not what our default // partitioner did! mesh.partition(1); CPPUNIT_ASSERT_EQUAL(i1, mesh.add_elem_integer("i1")); // Make sure we didn't screw up any extra integers thereby. for (const auto & elem : mesh.element_ptr_range()) { CPPUNIT_ASSERT_EQUAL(elem->n_extra_integers(), 1u); CPPUNIT_ASSERT_EQUAL(elem->get_extra_integer(i1), dof_id_type(elem->point(0)(0)*100)); } #ifdef LIBMESH_ENABLE_AMR MeshRefinement mr(mesh); mr.uniformly_refine(1); // Make sure the old elements have the same integers and the new // elements have be initialized as undefined. for (const auto & elem : mesh.element_ptr_range()) { CPPUNIT_ASSERT_EQUAL(elem->n_extra_integers(), 1u); if (elem->level()) CPPUNIT_ASSERT_EQUAL(elem->get_extra_integer(i1), DofObject::invalid_id); else { CPPUNIT_ASSERT_EQUAL(elem->get_extra_integer(i1), dof_id_type(elem->point(0)(0)*100)); } } #endif } public: void setUp() {} void tearDown() {} void testExtraIntegersEdge2() { test_helper_1D(EDGE2); } }; CPPUNIT_TEST_SUITE_REGISTRATION( ExtraIntegersTest ); <commit_msg>Add extra_node_integer coverage to unit tests<commit_after>// Ignore unused parameter warnings coming from cppunit headers #include <libmesh/ignore_warnings.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <libmesh/restore_warnings.h> #include <libmesh/libmesh.h> #include <libmesh/mesh.h> #include <libmesh/elem.h> #include <libmesh/mesh_generation.h> #include <libmesh/mesh_refinement.h> #include "test_comm.h" // THE CPPUNIT_TEST_SUITE_END macro expands to code that involves // std::auto_ptr, which in turn produces -Wdeprecated-declarations // warnings. These can be ignored in GCC as long as we wrap the // offending code in appropriate pragmas. We can't get away with a // single ignore_warnings.h inclusion at the beginning of this file, // since the libmesh headers pull in a restore_warnings.h at some // point. We also don't bother restoring warnings at the end of this // file since it's not a header. #include <libmesh/ignore_warnings.h> using namespace libMesh; class ExtraIntegersTest : public CppUnit::TestCase { /** * The goal of this test is to verify the ability to add extra * integer storage to a Mesh object, then set and query those extra * integers in the objects within the mesh. */ public: CPPUNIT_TEST_SUITE( ExtraIntegersTest ); CPPUNIT_TEST( testExtraIntegersEdge2 ); CPPUNIT_TEST_SUITE_END(); protected: // Helper function called by the test implementations, saves a few lines of code. void test_helper_1D(ElemType elem_type) { Mesh mesh(*TestCommWorld, /*dim=*/2); // Request some extra integers before building unsigned int i1 = mesh.add_elem_integer("i1"); unsigned int ni1 = mesh.add_node_integer("ni1"); unsigned int ni2 = mesh.add_node_integer("ni2"); MeshTools::Generation::build_line(mesh, /*nx=*/10, /*xmin=*/0., /*xmax=*/1., elem_type); for (const auto & elem : mesh.element_ptr_range()) { CPPUNIT_ASSERT_EQUAL(elem->n_extra_integers(), 1u); CPPUNIT_ASSERT_EQUAL(elem->get_extra_integer(i1), DofObject::invalid_id); elem->set_extra_integer(i1, dof_id_type(elem->point(0)(0)*100)); CPPUNIT_ASSERT_EQUAL(elem->get_extra_integer(i1), dof_id_type(elem->point(0)(0)*100)); } for (const auto & node : mesh.node_ptr_range()) { CPPUNIT_ASSERT_EQUAL(node->n_extra_integers(), 2u); CPPUNIT_ASSERT_EQUAL(node->get_extra_integer(ni1), DofObject::invalid_id); CPPUNIT_ASSERT_EQUAL(node->get_extra_integer(ni2), DofObject::invalid_id); } // Force (in parallel) a different partitioning - we'll simply put // everything on rank 0, which hopefully is not what our default // partitioner did! mesh.partition(1); CPPUNIT_ASSERT_EQUAL(i1, mesh.add_elem_integer("i1")); CPPUNIT_ASSERT_EQUAL(ni1, mesh.add_node_integer("ni1")); CPPUNIT_ASSERT_EQUAL(ni2, mesh.add_node_integer("ni2")); // Make sure we didn't screw up any extra integers thereby. for (const auto & elem : mesh.element_ptr_range()) { CPPUNIT_ASSERT_EQUAL(elem->n_extra_integers(), 1u); CPPUNIT_ASSERT_EQUAL(elem->get_extra_integer(i1), dof_id_type(elem->point(0)(0)*100)); } for (const auto & node : mesh.node_ptr_range()) { CPPUNIT_ASSERT_EQUAL(node->n_extra_integers(), 2u); CPPUNIT_ASSERT_EQUAL(node->get_extra_integer(ni1), DofObject::invalid_id); CPPUNIT_ASSERT_EQUAL(node->get_extra_integer(ni2), DofObject::invalid_id); } #ifdef LIBMESH_ENABLE_AMR MeshRefinement mr(mesh); mr.uniformly_refine(1); // Make sure the old elements have the same integers and the new // elements have be initialized as undefined. for (const auto & elem : mesh.element_ptr_range()) { CPPUNIT_ASSERT_EQUAL(elem->n_extra_integers(), 1u); if (elem->level()) CPPUNIT_ASSERT_EQUAL(elem->get_extra_integer(i1), DofObject::invalid_id); else { CPPUNIT_ASSERT_EQUAL(elem->get_extra_integer(i1), dof_id_type(elem->point(0)(0)*100)); for (auto & node : elem->node_ref_range()) CPPUNIT_ASSERT_EQUAL(node.n_extra_integers(), 2u); } } #endif } public: void setUp() {} void tearDown() {} void testExtraIntegersEdge2() { test_helper_1D(EDGE2); } }; CPPUNIT_TEST_SUITE_REGISTRATION( ExtraIntegersTest ); <|endoftext|>
<commit_before>/* Copyright (c) 2017-2019, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <TDebug> #include <TLogger> #include <TLog> #include <TAppSettings> #include "tloggerfactory.h" #include "tbasiclogstream.h" #include "tsystemglobal.h" #undef tFatal #undef tError #undef tWarn #undef tInfo #undef tDebug #undef tTrace /*! \class TDebug \brief The TDebug class provides a file output stream for debugging information. */ static TAbstractLogStream *stream = nullptr; static QList<TLogger *> loggers; /*! Sets up all the loggers set in the logger.ini. This function is for internal use only. */ void Tf::setupAppLoggers() { const QStringList loggerList = Tf::app()->loggerSettings().value("Loggers").toString().split(' ', QString::SkipEmptyParts); for (auto &lg : loggerList) { TLogger *lgr = TLoggerFactory::create(lg); if (lgr) { loggers << lgr; tSystemDebug("Logger added: %s", qPrintable(lgr->key())); } } if (!stream) { stream = new TBasicLogStream(loggers, qApp); } } /*! Releases all the loggers. This function is for internal use only. */ void Tf::releaseAppLoggers() { delete stream; stream = nullptr; for (auto &logger : (const QList<TLogger*>&)loggers) { delete logger; } loggers.clear(); } static void tMessage(int priority, const char *msg, va_list ap) { TLog log(priority, QString().vsprintf(msg, ap).toLocal8Bit()); if (stream) { stream->writeLog(log); } } static void tFlushMessage() { if (stream) { stream->flush(); } } TDebug::~TDebug() { ts.flush(); if (!buffer.isNull()) { TLog log(msgPriority, buffer.toLocal8Bit()); if (stream) { stream->writeLog(log); } } } TDebug::TDebug(const TDebug &other) : buffer(other.buffer), ts(&buffer, QIODevice::WriteOnly), msgPriority(other.msgPriority) { } TDebug &TDebug::operator=(const TDebug &other) { buffer = other.buffer; ts.setString(&buffer, QIODevice::WriteOnly); msgPriority = other.msgPriority; return *this; } /*! Writes the fatal message \a fmt to the file app.log. */ void TDebug::fatal(const char *fmt, ...) const { va_list ap; va_start(ap, fmt); tMessage(Tf::FatalLevel, fmt, ap); va_end(ap); tFlushMessage(); if (Tf::appSettings()->value(Tf::ApplicationAbortOnFatal).toBool()) { #if (defined(Q_OS_UNIX) || defined(Q_CC_MINGW)) abort(); // trap; generates core dump #else _exit(-1); #endif } } /*! Writes the error message \a fmt to the file app.log. */ void TDebug::error(const char *fmt, ...) const { va_list ap; va_start(ap, fmt); tMessage(Tf::ErrorLevel, fmt, ap); va_end(ap); tFlushMessage(); } /*! Writes the warning message \a fmt to the file app.log. */ void TDebug::warn(const char *fmt, ...) const { va_list ap; va_start(ap, fmt); tMessage(Tf::WarnLevel, fmt, ap); va_end(ap); tFlushMessage(); } /*! Writes the information message \a fmt to the file app.log. */ void TDebug::info(const char *fmt, ...) const { va_list ap; va_start(ap, fmt); tMessage(Tf::InfoLevel, fmt, ap); va_end(ap); } /*! Writes the debug message \a fmt to the file app.log. */ void TDebug::debug(const char *fmt, ...) const { va_list ap; va_start(ap, fmt); tMessage(Tf::DebugLevel, fmt, ap); va_end(ap); } /*! Writes the trace message \a fmt to the file app.log. */ void TDebug::trace(const char *fmt, ...) const { va_list ap; va_start(ap, fmt); tMessage(Tf::TraceLevel, fmt, ap); va_end(ap); } <commit_msg>polish<commit_after>/* Copyright (c) 2017-2019, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <TDebug> #include <TLogger> #include <TLog> #include <TAppSettings> #include "tloggerfactory.h" #include "tbasiclogstream.h" #include "tsystemglobal.h" #undef tFatal #undef tError #undef tWarn #undef tInfo #undef tDebug #undef tTrace /*! \class TDebug \brief The TDebug class provides a file output stream for debugging information. */ static TAbstractLogStream *stream = nullptr; static QList<TLogger *> loggers; /*! Sets up all the loggers set in the logger.ini. This function is for internal use only. */ void Tf::setupAppLoggers() { const QStringList loggerList = Tf::app()->loggerSettings().value("Loggers").toString().split(' ', QString::SkipEmptyParts); for (auto &lg : loggerList) { TLogger *lgr = TLoggerFactory::create(lg); if (lgr) { loggers << lgr; tSystemDebug("Logger added: %s", qPrintable(lgr->key())); } } if (!stream) { stream = new TBasicLogStream(loggers, qApp); } } /*! Releases all the loggers. This function is for internal use only. */ void Tf::releaseAppLoggers() { delete stream; stream = nullptr; for (auto &logger : (const QList<TLogger*>&)loggers) { delete logger; } loggers.clear(); } static void tMessage(int priority, const char *msg, va_list ap) { if (stream) { TLog log(priority, QString().vsprintf(msg, ap).toLocal8Bit()); stream->writeLog(log); } } static void tFlushMessage() { if (stream) { stream->flush(); } } TDebug::~TDebug() { ts.flush(); if (!buffer.isNull()) { TLog log(msgPriority, buffer.toLocal8Bit()); if (stream) { stream->writeLog(log); } } } TDebug::TDebug(const TDebug &other) : buffer(other.buffer), ts(&buffer, QIODevice::WriteOnly), msgPriority(other.msgPriority) { } TDebug &TDebug::operator=(const TDebug &other) { buffer = other.buffer; ts.setString(&buffer, QIODevice::WriteOnly); msgPriority = other.msgPriority; return *this; } /*! Writes the fatal message \a fmt to the file app.log. */ void TDebug::fatal(const char *fmt, ...) const { va_list ap; va_start(ap, fmt); tMessage(Tf::FatalLevel, fmt, ap); va_end(ap); tFlushMessage(); if (Tf::appSettings()->value(Tf::ApplicationAbortOnFatal).toBool()) { #if (defined(Q_OS_UNIX) || defined(Q_CC_MINGW)) abort(); // trap; generates core dump #else _exit(-1); #endif } } /*! Writes the error message \a fmt to the file app.log. */ void TDebug::error(const char *fmt, ...) const { va_list ap; va_start(ap, fmt); tMessage(Tf::ErrorLevel, fmt, ap); va_end(ap); tFlushMessage(); } /*! Writes the warning message \a fmt to the file app.log. */ void TDebug::warn(const char *fmt, ...) const { va_list ap; va_start(ap, fmt); tMessage(Tf::WarnLevel, fmt, ap); va_end(ap); tFlushMessage(); } /*! Writes the information message \a fmt to the file app.log. */ void TDebug::info(const char *fmt, ...) const { va_list ap; va_start(ap, fmt); tMessage(Tf::InfoLevel, fmt, ap); va_end(ap); } /*! Writes the debug message \a fmt to the file app.log. */ void TDebug::debug(const char *fmt, ...) const { va_list ap; va_start(ap, fmt); tMessage(Tf::DebugLevel, fmt, ap); va_end(ap); } /*! Writes the trace message \a fmt to the file app.log. */ void TDebug::trace(const char *fmt, ...) const { va_list ap; va_start(ap, fmt); tMessage(Tf::TraceLevel, fmt, ap); va_end(ap); } <|endoftext|>
<commit_before>#include "LightForm.h" #include "Object.h" #include "LightManager.h" using namespace Rendering; using namespace Rendering::Light; using namespace Rendering::Manager; LightForm::LightForm() { _color = Color::White(); } LightForm::~LightForm() { } void LightForm::Initialize() { //null } void LightForm::Destroy() { //null } <commit_msg>LightForm - Init할 때, LightManager에 자신을 추가하도록 구현 #51<commit_after>#include "LightForm.h" #include "Object.h" #include "Director.h" using namespace Rendering; using namespace Rendering::Light; LightForm::LightForm() { _color = Color::White(); } LightForm::~LightForm() { } void LightForm::Initialize() { Core::Scene* scene = Device::Director::GetInstance()->GetCurrentScene(); scene->GetLightManager()->Add(this, _owner->GetName().c_str()); } void LightForm::Destroy() { }<|endoftext|>
<commit_before><commit_msg>coverity#1132707 Unintended sign extension<commit_after><|endoftext|>
<commit_before>#include "DeferredShaderHandler.h" DeferredShaderHandler::DeferredShaderHandler() : ShaderHandler() { this->m_samplerState = nullptr; for (int i = 0; i < BUFFER_COUNT; i++) { this->m_deferredRenderTargetTextures[i] = nullptr; this->m_deferredRenderTargetViews[i] = nullptr; this->m_deferredShaderResources[i] = nullptr; } } DeferredShaderHandler::~DeferredShaderHandler() { } int DeferredShaderHandler::Initialize(ID3D11Device * device, HWND * windowHandle, DirectX::XMFLOAT2 resolution) { HRESULT hResult; ID3D10Blob* vertexShaderBuffer[4] = { nullptr }; ID3D10Blob* geoShaderBuffer = nullptr; ID3D10Blob* pixelShaderBuffer = nullptr; //Insert shader path here WCHAR* vsFilename = L"../GraphicsDLL/DeferredVertexShader.hlsl"; WCHAR* gsFilename = L"../GraphicsDLL/DeferredGeometryShader.hlsl"; WCHAR* psFilename = L"../GraphicsDLL/DeferredPixelShader.hlsl"; // Compile the shaders \\ hResult = D3DCompileFromFile(vsFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &vertexShaderBuffer[0], NULL); if (FAILED(hResult)) { return 1; } hResult = D3DCompileFromFile(gsFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &geoShaderBuffer, NULL); if (FAILED(hResult)) { return 1; } hResult = D3DCompileFromFile(psFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &pixelShaderBuffer, NULL); if (FAILED(hResult)) { return 1; } // Create the shaders \\ hResult = device->CreateVertexShader(vertexShaderBuffer[0]->GetBufferPointer(), vertexShaderBuffer[0]->GetBufferSize(), NULL, &this->m_vertexShader[0]); if (FAILED(hResult)) { return 1; } hResult = device->CreateGeometryShader(geoShaderBuffer->GetBufferPointer(), geoShaderBuffer->GetBufferSize(), NULL, &this->m_geoShader); if (FAILED(hResult)) { return 1; } hResult = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &this->m_pixelShader); if (FAILED(hResult)) { return 1; } // Create the input layout \\ D3D11_INPUT_ELEMENT_DESC polygonLayout[4]; polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "NORMAL"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; polygonLayout[2].SemanticName = "TANGENT"; polygonLayout[2].SemanticIndex = 0; polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[2].InputSlot = 0; polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[2].InstanceDataStepRate = 0; polygonLayout[3].SemanticName = "TEXCOORD"; polygonLayout[3].SemanticIndex = 0; polygonLayout[3].Format = DXGI_FORMAT_R32G32_FLOAT; polygonLayout[3].InputSlot = 0; polygonLayout[3].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[3].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[3].InstanceDataStepRate = 0; unsigned int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); //Create the vertex input layout. hResult = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer[0]->GetBufferPointer(), vertexShaderBuffer[0]->GetBufferSize(), &this->m_layout); if (FAILED(hResult)) { return 1; } //Release and nullptr the buffers as they are no longer needed vertexShaderBuffer[0]->Release(); vertexShaderBuffer[0] = nullptr; geoShaderBuffer->Release(); geoShaderBuffer = nullptr; pixelShaderBuffer->Release(); pixelShaderBuffer = nullptr; // Create the matrix buffer \\ D3D11_BUFFER_DESC matrixBufferDesc; ZeroMemory(&matrixBufferDesc, sizeof(matrixBufferDesc)); //Fill the description of the dynamic matrix constant buffer that is in the vertex shader matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(ShaderLib::DeferredConstantBuffer); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. hResult = device->CreateBuffer(&matrixBufferDesc, NULL, &this->m_matrixBuffer); if (FAILED(hResult)) { return 1; } // Create the sampler \\ D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); //Fill the texture sampler state description samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; //Create the texture sampler state hResult = device->CreateSamplerState(&samplerDesc, &this->m_samplerState); if (FAILED(hResult)) { return 1; } // Create the render target and shader resource views \\ D3D11_TEXTURE2D_DESC renderTextureDesc; D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc; D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc; //Initialize the render target texture description ZeroMemory(&renderTextureDesc, sizeof(renderTextureDesc)); //Setup the render target texture description renderTextureDesc.Width = resolution.x; renderTextureDesc.Height = resolution.y; renderTextureDesc.MipLevels = 1; renderTextureDesc.ArraySize = 1; renderTextureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; renderTextureDesc.SampleDesc.Count = 1; //No MSAA renderTextureDesc.SampleDesc.Quality = 0; renderTextureDesc.Usage = D3D11_USAGE_DEFAULT; renderTextureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; renderTextureDesc.CPUAccessFlags = 0; renderTextureDesc.MiscFlags = 0; //Create the render target textures for (int i = 0; i < BUFFER_COUNT; i++) { hResult = device->CreateTexture2D(&renderTextureDesc, NULL, &this->m_deferredRenderTargetTextures[i]); if (FAILED(hResult)) { return 1; } } //Setup the description of the render target views renderTargetViewDesc.Format = renderTextureDesc.Format; renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; renderTargetViewDesc.Texture2D.MipSlice = 0; //Create the render target views for (int i = 0; i<BUFFER_COUNT; i++) { hResult = device->CreateRenderTargetView(this->m_deferredRenderTargetTextures[i], &renderTargetViewDesc, &this->m_deferredRenderTargetViews[i]); if (FAILED(hResult)) { return 1; } } //Setup the description of the shader resource view shaderResourceViewDesc.Format = renderTextureDesc.Format; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = 1; //Create the shader resource views for (int i = 0; i < BUFFER_COUNT; i++) { hResult = device->CreateShaderResourceView(this->m_deferredRenderTargetTextures[i], &shaderResourceViewDesc, &this->m_deferredShaderResources[i]); if (FAILED(hResult)) { return 1; } } return 0; } int DeferredShaderHandler::SetActive(ID3D11DeviceContext * deviceContext, ShaderLib::ShaderType shaderType) { return 0; } void DeferredShaderHandler::Shutdown() { ShaderHandler::Shutdown(); //Release the sampler state if (this->m_samplerState) { this->m_samplerState->Release(); this->m_samplerState = nullptr; } //Release the deferred render targets for (int i = 0; i < BUFFER_COUNT; i++) { if (this->m_deferredRenderTargetTextures[i]) { this->m_deferredRenderTargetTextures[i]->Release(); this->m_deferredRenderTargetTextures[i] = nullptr; } if (this->m_deferredRenderTargetViews[i]) { this->m_deferredRenderTargetViews[i]->Release(); this->m_deferredRenderTargetViews[i] = nullptr; } if (this->m_deferredShaderResources[i]) { this->m_deferredShaderResources[i]->Release(); this->m_deferredShaderResources[i] = nullptr; } } } int DeferredShaderHandler::SetShaderParameters(ID3D11DeviceContext * deviceContext, ShaderLib::DeferredConstantBuffer shaderParams) { return 0; } ID3D11ShaderResourceView ** DeferredShaderHandler::GetShaderResourceViews() { return nullptr; } <commit_msg>UPDATE DeferredShaderHandler implemented SetActive()<commit_after>#include "DeferredShaderHandler.h" DeferredShaderHandler::DeferredShaderHandler() : ShaderHandler() { this->m_samplerState = nullptr; for (int i = 0; i < BUFFER_COUNT; i++) { this->m_deferredRenderTargetTextures[i] = nullptr; this->m_deferredRenderTargetViews[i] = nullptr; this->m_deferredShaderResources[i] = nullptr; } } DeferredShaderHandler::~DeferredShaderHandler() { } int DeferredShaderHandler::Initialize(ID3D11Device * device, HWND * windowHandle, DirectX::XMFLOAT2 resolution) { HRESULT hResult; ID3D10Blob* vertexShaderBuffer[4] = { nullptr }; ID3D10Blob* geoShaderBuffer = nullptr; ID3D10Blob* pixelShaderBuffer = nullptr; //Insert shader path here WCHAR* vsFilename = L"../GraphicsDLL/DeferredVertexShader.hlsl"; WCHAR* gsFilename = L"../GraphicsDLL/DeferredGeometryShader.hlsl"; WCHAR* psFilename = L"../GraphicsDLL/DeferredPixelShader.hlsl"; // Compile the shaders \\ hResult = D3DCompileFromFile(vsFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &vertexShaderBuffer[0], NULL); if (FAILED(hResult)) { return 1; } hResult = D3DCompileFromFile(gsFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &geoShaderBuffer, NULL); if (FAILED(hResult)) { return 1; } hResult = D3DCompileFromFile(psFilename, NULL, NULL, "main", "vs_5_0", D3D10_SHADER_DEBUG, 0, &pixelShaderBuffer, NULL); if (FAILED(hResult)) { return 1; } // Create the shaders \\ hResult = device->CreateVertexShader(vertexShaderBuffer[0]->GetBufferPointer(), vertexShaderBuffer[0]->GetBufferSize(), NULL, &this->m_vertexShader[0]); if (FAILED(hResult)) { return 1; } hResult = device->CreateGeometryShader(geoShaderBuffer->GetBufferPointer(), geoShaderBuffer->GetBufferSize(), NULL, &this->m_geoShader); if (FAILED(hResult)) { return 1; } hResult = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &this->m_pixelShader); if (FAILED(hResult)) { return 1; } // Create the input layout \\ D3D11_INPUT_ELEMENT_DESC polygonLayout[4]; polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "NORMAL"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; polygonLayout[2].SemanticName = "TANGENT"; polygonLayout[2].SemanticIndex = 0; polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[2].InputSlot = 0; polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[2].InstanceDataStepRate = 0; polygonLayout[3].SemanticName = "TEXCOORD"; polygonLayout[3].SemanticIndex = 0; polygonLayout[3].Format = DXGI_FORMAT_R32G32_FLOAT; polygonLayout[3].InputSlot = 0; polygonLayout[3].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[3].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[3].InstanceDataStepRate = 0; unsigned int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); //Create the vertex input layout. hResult = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer[0]->GetBufferPointer(), vertexShaderBuffer[0]->GetBufferSize(), &this->m_layout); if (FAILED(hResult)) { return 1; } //Release and nullptr the buffers as they are no longer needed vertexShaderBuffer[0]->Release(); vertexShaderBuffer[0] = nullptr; geoShaderBuffer->Release(); geoShaderBuffer = nullptr; pixelShaderBuffer->Release(); pixelShaderBuffer = nullptr; // Create the matrix buffer \\ D3D11_BUFFER_DESC matrixBufferDesc; ZeroMemory(&matrixBufferDesc, sizeof(matrixBufferDesc)); //Fill the description of the dynamic matrix constant buffer that is in the vertex shader matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(ShaderLib::DeferredConstantBuffer); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. hResult = device->CreateBuffer(&matrixBufferDesc, NULL, &this->m_matrixBuffer); if (FAILED(hResult)) { return 1; } // Create the sampler \\ D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); //Fill the texture sampler state description samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; //Create the texture sampler state hResult = device->CreateSamplerState(&samplerDesc, &this->m_samplerState); if (FAILED(hResult)) { return 1; } // Create the render target and shader resource views \\ D3D11_TEXTURE2D_DESC renderTextureDesc; D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc; D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc; //Initialize the render target texture description ZeroMemory(&renderTextureDesc, sizeof(renderTextureDesc)); //Setup the render target texture description renderTextureDesc.Width = resolution.x; renderTextureDesc.Height = resolution.y; renderTextureDesc.MipLevels = 1; renderTextureDesc.ArraySize = 1; renderTextureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; renderTextureDesc.SampleDesc.Count = 1; //No MSAA renderTextureDesc.SampleDesc.Quality = 0; renderTextureDesc.Usage = D3D11_USAGE_DEFAULT; renderTextureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; renderTextureDesc.CPUAccessFlags = 0; renderTextureDesc.MiscFlags = 0; //Create the render target textures for (int i = 0; i < BUFFER_COUNT; i++) { hResult = device->CreateTexture2D(&renderTextureDesc, NULL, &this->m_deferredRenderTargetTextures[i]); if (FAILED(hResult)) { return 1; } } //Setup the description of the render target views renderTargetViewDesc.Format = renderTextureDesc.Format; renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; renderTargetViewDesc.Texture2D.MipSlice = 0; //Create the render target views for (int i = 0; i<BUFFER_COUNT; i++) { hResult = device->CreateRenderTargetView(this->m_deferredRenderTargetTextures[i], &renderTargetViewDesc, &this->m_deferredRenderTargetViews[i]); if (FAILED(hResult)) { return 1; } } //Setup the description of the shader resource view shaderResourceViewDesc.Format = renderTextureDesc.Format; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = 1; //Create the shader resource views for (int i = 0; i < BUFFER_COUNT; i++) { hResult = device->CreateShaderResourceView(this->m_deferredRenderTargetTextures[i], &shaderResourceViewDesc, &this->m_deferredShaderResources[i]); if (FAILED(hResult)) { return 1; } } return 0; } int DeferredShaderHandler::SetActive(ID3D11DeviceContext * deviceContext, ShaderLib::ShaderType shaderType) { //Set the input layout for vertex deviceContext->IASetInputLayout(this->m_layout); //Set the vertex and pixel shaders that will be used to render this triangle deviceContext->VSSetShader(this->m_vertexShader[0], NULL, 0); deviceContext->PSSetShader(this->m_pixelShader, NULL, 0); deviceContext->GSSetShader(this->m_geoShader, NULL, 0); //Set the sampler state in pixel shader deviceContext->PSSetSamplers(0, 1, &this->m_samplerState); return 0; } void DeferredShaderHandler::Shutdown() { ShaderHandler::Shutdown(); //Release the sampler state if (this->m_samplerState) { this->m_samplerState->Release(); this->m_samplerState = nullptr; } //Release the deferred render targets for (int i = 0; i < BUFFER_COUNT; i++) { if (this->m_deferredRenderTargetTextures[i]) { this->m_deferredRenderTargetTextures[i]->Release(); this->m_deferredRenderTargetTextures[i] = nullptr; } if (this->m_deferredRenderTargetViews[i]) { this->m_deferredRenderTargetViews[i]->Release(); this->m_deferredRenderTargetViews[i] = nullptr; } if (this->m_deferredShaderResources[i]) { this->m_deferredShaderResources[i]->Release(); this->m_deferredShaderResources[i] = nullptr; } } } int DeferredShaderHandler::SetShaderParameters(ID3D11DeviceContext * deviceContext, ShaderLib::DeferredConstantBuffer shaderParams) { return 0; } ID3D11ShaderResourceView ** DeferredShaderHandler::GetShaderResourceViews() { return nullptr; } <|endoftext|>
<commit_before>/* * Copyright (c) 2005, 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. */ //--- standard modules used ---------------------------------------------------- #include "Anything.h" #include "Threads.h" #include "TestThread.h" #include "Dbg.h" //--- test modules used -------------------------------------------------------- #include "TestSuite.h" //--- module under test -------------------------------------------------------- #include "ThreadPools.h" //--- interface include -------------------------------------------------------- #include "WorkerPoolManagerTest.h" //---- WorkerPoolManagerTest ---------------------------------------------------------------- WorkerPoolManagerTest::WorkerPoolManagerTest(TString tname) : TestCase(tname), fCheckMutex("WorkerPoolManager") { StartTrace(WorkerPoolManagerTest.Ctor); } WorkerPoolManagerTest::~WorkerPoolManagerTest() { StartTrace(WorkerPoolManagerTest.Dtor); } // builds up a suite of testcases, add a line for each testmethod Test *WorkerPoolManagerTest::suite () { StartTrace(WorkerPoolManagerTest.suite); TestSuite *testSuite = new TestSuite; ADD_CASE(testSuite, WorkerPoolManagerTest, InitTest); ADD_CASE(testSuite, WorkerPoolManagerTest, EnterLeaveTests); return testSuite; } // setup for this TestCase void WorkerPoolManagerTest::setUp () { StartTrace(WorkerPoolManagerTest.setUp); } // setUp void WorkerPoolManagerTest::tearDown () { StartTrace(WorkerPoolManagerTest.tearDown); } // tearDown void WorkerPoolManagerTest::InitTest() { StartTrace(WorkerPoolManagerTest.InitTest); SamplePoolManager wpm("InitTestPool"); Anything config; config["timeout"] = 1; config["test"] = Anything((IFAObject *)this); t_assert(wpm.Init(0, 0, 0, 0, ROAnything(config)) == 0); // always allocate at least one worker t_assert(wpm.MaxRequests2Run() == 1); t_assert(wpm.NumOfRequestsRunning() == 0); t_assert(wpm.Init(-1, 0, 0, 0, ROAnything(config)) == 0); t_assert(wpm.MaxRequests2Run() == 1); t_assert(wpm.NumOfRequestsRunning() == 0); t_assert(wpm.Init(1, 0, 0, 0, ROAnything(config)) == 0); t_assert(wpm.MaxRequests2Run() == 1); t_assert(wpm.NumOfRequestsRunning() == 0); t_assert(wpm.Init(10, 0, 0, 0, ROAnything(config)) == 0); t_assert(wpm.MaxRequests2Run() == 10); t_assert(wpm.NumOfRequestsRunning() == 0); for (long i = 0; i < 10; i++) { t_assertm(wpm.DoGetWorker(i) != 0, "expected 10 Workers to be there"); } } void WorkerPoolManagerTest::EnterLeaveTests() { StartTrace(WorkerPoolManagerTest.EnterLeaveTests); const long cPoolSz = 2; SamplePoolManager wpm("EnterLeaveTestsPool"); Anything config; config["timeout"] = 1; config["test"] = Anything((IFAObject *)this); t_assert(wpm.Init(cPoolSz, 0, 0, 0, ROAnything(config)) == 0); t_assert(wpm.MaxRequests2Run() == cPoolSz); t_assert(wpm.NumOfRequestsRunning() == 0); Anything work; for (long i = 0; i < 2 * cPoolSz; i++) { wpm.Enter(ROAnything(work)); } t_assert(wpm.AwaitEmpty(5)); t_assert(wpm.Terminate()); Anything expected; Anything statistic; wpm.Statistic(statistic); expected["PoolSize"] = 2; expected["CurrentParallelRequests"] = 0; expected["MaxParallelRequests"] = 2; expected["TotalRequests"] = 4; statistic.Remove("TotalTime"); // since varies statistic.Remove("AverageTime"); // since varies statistic.Remove("TRX/sec"); // since varies assertAnyEqualm(expected, statistic, "statistic differs"); } void WorkerPoolManagerTest::CheckPrepare2Run(bool isReady, bool wasPrepared) { MutexEntry me(fCheckMutex); me.Use(); t_assertm(isReady, "Worker must be in ready state"); t_assertm(!wasPrepared, "Worker must not be prepared"); } void WorkerPoolManagerTest::CheckProcessWorkload(bool isWorking, bool wasPrepared) { MutexEntry me(fCheckMutex); me.Use(); t_assertm(isWorking, "Worker must be in working state"); t_assertm(wasPrepared, "Worker must have been prepared"); } <commit_msg>renamed some WorkerPool functions<commit_after>/* * Copyright (c) 2005, 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. */ //--- standard modules used ---------------------------------------------------- #include "Anything.h" #include "Threads.h" #include "TestThread.h" #include "Dbg.h" //--- test modules used -------------------------------------------------------- #include "TestSuite.h" //--- module under test -------------------------------------------------------- #include "ThreadPools.h" //--- interface include -------------------------------------------------------- #include "WorkerPoolManagerTest.h" //---- WorkerPoolManagerTest ---------------------------------------------------------------- WorkerPoolManagerTest::WorkerPoolManagerTest(TString tname) : TestCase(tname), fCheckMutex("WorkerPoolManager") { StartTrace(WorkerPoolManagerTest.Ctor); } WorkerPoolManagerTest::~WorkerPoolManagerTest() { StartTrace(WorkerPoolManagerTest.Dtor); } // builds up a suite of testcases, add a line for each testmethod Test *WorkerPoolManagerTest::suite () { StartTrace(WorkerPoolManagerTest.suite); TestSuite *testSuite = new TestSuite; ADD_CASE(testSuite, WorkerPoolManagerTest, InitTest); ADD_CASE(testSuite, WorkerPoolManagerTest, EnterLeaveTests); return testSuite; } // setup for this TestCase void WorkerPoolManagerTest::setUp () { StartTrace(WorkerPoolManagerTest.setUp); } // setUp void WorkerPoolManagerTest::tearDown () { StartTrace(WorkerPoolManagerTest.tearDown); } // tearDown void WorkerPoolManagerTest::InitTest() { StartTrace(WorkerPoolManagerTest.InitTest); SamplePoolManager wpm("InitTestPool"); Anything config; config["timeout"] = 1; config["test"] = Anything((IFAObject *)this); t_assert(wpm.Init(0, 0, 0, 0, ROAnything(config)) == 0); // always allocate at least one worker t_assert(wpm.GetPoolSize() == 1); t_assert(wpm.ResourcesUsed() == 0); t_assert(wpm.Init(-1, 0, 0, 0, ROAnything(config)) == 0); t_assert(wpm.GetPoolSize() == 1); t_assert(wpm.ResourcesUsed() == 0); t_assert(wpm.Init(1, 0, 0, 0, ROAnything(config)) == 0); t_assert(wpm.GetPoolSize() == 1); t_assert(wpm.ResourcesUsed() == 0); t_assert(wpm.Init(10, 0, 0, 0, ROAnything(config)) == 0); t_assert(wpm.GetPoolSize() == 10); t_assert(wpm.ResourcesUsed() == 0); for (long i = 0; i < 10; i++) { t_assertm(wpm.DoGetWorker(i) != 0, "expected 10 Workers to be there"); } } void WorkerPoolManagerTest::EnterLeaveTests() { StartTrace(WorkerPoolManagerTest.EnterLeaveTests); const long cPoolSz = 2; SamplePoolManager wpm("EnterLeaveTestsPool"); Anything config; config["timeout"] = 1; config["test"] = Anything((IFAObject *)this); t_assert(wpm.Init(cPoolSz, 0, 0, 0, ROAnything(config)) == 0); t_assert(wpm.GetPoolSize() == cPoolSz); t_assert(wpm.ResourcesUsed() == 0); Anything work; for (long i = 0; i < 2 * cPoolSz; i++) { wpm.Enter(ROAnything(work)); } t_assert(wpm.AwaitEmpty(5)); t_assert(wpm.Terminate()); Anything expected; Anything statistic; wpm.Statistic(statistic); expected["PoolSize"] = 2; expected["CurrentParallelRequests"] = 0; expected["MaxParallelRequests"] = 2; expected["TotalRequests"] = 4; statistic.Remove("TotalTime"); // since varies statistic.Remove("AverageTime"); // since varies statistic.Remove("TRX/sec"); // since varies assertAnyEqualm(expected, statistic, "statistic differs"); } void WorkerPoolManagerTest::CheckPrepare2Run(bool isReady, bool wasPrepared) { MutexEntry me(fCheckMutex); me.Use(); t_assertm(isReady, "Worker must be in ready state"); t_assertm(!wasPrepared, "Worker must not be prepared"); } void WorkerPoolManagerTest::CheckProcessWorkload(bool isWorking, bool wasPrepared) { MutexEntry me(fCheckMutex); me.Use(); t_assertm(isWorking, "Worker must be in working state"); t_assertm(wasPrepared, "Worker must have been prepared"); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: zoomitem.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2007-06-27 18:31:54 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef __SBX_SBXVARIABLE_HXX #include <basic/sbxvar.hxx> #endif #include <svx/zoomitem.hxx> #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif // ----------------------------------------------------------------------- TYPEINIT1_FACTORY(SvxZoomItem,SfxUInt16Item, new SvxZoomItem); #define ZOOM_PARAM_VALUE "Value" #define ZOOM_PARAM_VALUESET "ValueSet" #define ZOOM_PARAM_TYPE "Type" #define ZOOM_PARAMS 3 // ----------------------------------------------------------------------- SvxZoomItem::SvxZoomItem ( SvxZoomType eZoomType, sal_uInt16 nVal, sal_uInt16 _nWhich ) : SfxUInt16Item( _nWhich, nVal ), nValueSet( SVX_ZOOM_ENABLE_ALL ), eType( eZoomType ) { } // ----------------------------------------------------------------------- SvxZoomItem::SvxZoomItem( const SvxZoomItem& rOrig ) : SfxUInt16Item( rOrig.Which(), rOrig.GetValue() ), nValueSet( rOrig.GetValueSet() ), eType( rOrig.GetType() ) { } // ----------------------------------------------------------------------- SvxZoomItem::~SvxZoomItem() { } // ----------------------------------------------------------------------- SfxPoolItem* SvxZoomItem::Clone( SfxItemPool * /*pPool*/ ) const { return new SvxZoomItem( *this ); } // ----------------------------------------------------------------------- SfxPoolItem* SvxZoomItem::Create( SvStream& rStrm, sal_uInt16 /*nVersion*/ ) const { sal_uInt16 nValue; sal_uInt16 nValSet; sal_Int8 nType; rStrm >> nValue >> nValSet >> nType; SvxZoomItem* pNew = new SvxZoomItem( (SvxZoomType)nType, nValue, Which() ); pNew->SetValueSet( nValSet ); return pNew; } // ----------------------------------------------------------------------- SvStream& SvxZoomItem::Store( SvStream& rStrm, sal_uInt16 /*nItemVersion*/ ) const { rStrm << (sal_uInt16)GetValue() << nValueSet << (sal_Int8)eType; return rStrm; } // ----------------------------------------------------------------------- int SvxZoomItem::operator==( const SfxPoolItem& rAttr ) const { DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" ); SvxZoomItem& rItem = (SvxZoomItem&)rAttr; return ( GetValue() == rItem.GetValue() && nValueSet == rItem.GetValueSet() && eType == rItem.GetType() ); } sal_Bool SvxZoomItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const { // sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS); nMemberId &= ~CONVERT_TWIPS; switch ( nMemberId ) { case 0 : { ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq( ZOOM_PARAMS ); aSeq[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUE )); aSeq[0].Value <<= sal_Int32( GetValue() ); aSeq[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUESET )); aSeq[1].Value <<= sal_Int16( nValueSet ); aSeq[2].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_TYPE )); aSeq[2].Value <<= sal_Int16( eType ); rVal <<= aSeq; } break; case MID_VALUE: rVal <<= (sal_Int32) GetValue(); break; case MID_VALUESET: rVal <<= (sal_Int16) nValueSet; break; case MID_TYPE: rVal <<= (sal_Int16) eType; break; default: DBG_ERROR("svx::SvxZoomItem::QueryValue(), Wrong MemberId!"); return sal_False; } return sal_True; } sal_Bool SvxZoomItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId ) { // sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS); nMemberId &= ~CONVERT_TWIPS; switch ( nMemberId ) { case 0 : { ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq; if (( rVal >>= aSeq ) && ( aSeq.getLength() == ZOOM_PARAMS )) { sal_Int32 nValueTmp( 0 ); sal_Int16 nValueSetTmp( 0 ); sal_Int16 nTypeTmp( 0 ); sal_Bool bAllConverted( sal_True ); sal_Int16 nConvertedCount( 0 ); for ( sal_Int32 i = 0; i < aSeq.getLength(); i++ ) { if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUE )) { bAllConverted &= ( aSeq[i].Value >>= nValueTmp ); ++nConvertedCount; } else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUESET )) { bAllConverted &= ( aSeq[i].Value >>= nValueSetTmp ); ++nConvertedCount; } else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_TYPE )) { bAllConverted &= ( aSeq[i].Value >>= nTypeTmp ); ++nConvertedCount; } } if ( bAllConverted && nConvertedCount == ZOOM_PARAMS ) { SetValue( (UINT16)nValueTmp ); nValueSet = nValueSetTmp; eType = SvxZoomType( nTypeTmp ); return sal_True; } } return sal_False; } case MID_VALUE: { sal_Int32 nVal = 0; if ( rVal >>= nVal ) { SetValue( (UINT16)nVal ); return sal_True; } else return sal_False; } case MID_VALUESET: case MID_TYPE: { sal_Int16 nVal = sal_Int16(); if ( rVal >>= nVal ) { if ( nMemberId == MID_VALUESET ) nValueSet = (sal_Int16) nVal; else if ( nMemberId == MID_TYPE ) eType = SvxZoomType( (sal_Int16) nVal ); return sal_True; } else return sal_False; } default: DBG_ERROR("svx::SvxZoomItem::PutValue(), Wrong MemberId!"); return sal_False; } return sal_True; } <commit_msg>INTEGRATION: CWS changefileheader (1.12.368); FILE MERGED 2008/04/01 15:51:19 thb 1.12.368.3: #i85898# Stripping all external header guards 2008/04/01 12:49:16 thb 1.12.368.2: #i85898# Stripping all external header guards 2008/03/31 14:22:39 rt 1.12.368.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: zoomitem.cxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <tools/stream.hxx> #ifndef __SBX_SBXVARIABLE_HXX #include <basic/sbxvar.hxx> #endif #include <svx/zoomitem.hxx> #include <com/sun/star/uno/Sequence.hxx> #include <com/sun/star/beans/PropertyValue.hpp> // ----------------------------------------------------------------------- TYPEINIT1_FACTORY(SvxZoomItem,SfxUInt16Item, new SvxZoomItem); #define ZOOM_PARAM_VALUE "Value" #define ZOOM_PARAM_VALUESET "ValueSet" #define ZOOM_PARAM_TYPE "Type" #define ZOOM_PARAMS 3 // ----------------------------------------------------------------------- SvxZoomItem::SvxZoomItem ( SvxZoomType eZoomType, sal_uInt16 nVal, sal_uInt16 _nWhich ) : SfxUInt16Item( _nWhich, nVal ), nValueSet( SVX_ZOOM_ENABLE_ALL ), eType( eZoomType ) { } // ----------------------------------------------------------------------- SvxZoomItem::SvxZoomItem( const SvxZoomItem& rOrig ) : SfxUInt16Item( rOrig.Which(), rOrig.GetValue() ), nValueSet( rOrig.GetValueSet() ), eType( rOrig.GetType() ) { } // ----------------------------------------------------------------------- SvxZoomItem::~SvxZoomItem() { } // ----------------------------------------------------------------------- SfxPoolItem* SvxZoomItem::Clone( SfxItemPool * /*pPool*/ ) const { return new SvxZoomItem( *this ); } // ----------------------------------------------------------------------- SfxPoolItem* SvxZoomItem::Create( SvStream& rStrm, sal_uInt16 /*nVersion*/ ) const { sal_uInt16 nValue; sal_uInt16 nValSet; sal_Int8 nType; rStrm >> nValue >> nValSet >> nType; SvxZoomItem* pNew = new SvxZoomItem( (SvxZoomType)nType, nValue, Which() ); pNew->SetValueSet( nValSet ); return pNew; } // ----------------------------------------------------------------------- SvStream& SvxZoomItem::Store( SvStream& rStrm, sal_uInt16 /*nItemVersion*/ ) const { rStrm << (sal_uInt16)GetValue() << nValueSet << (sal_Int8)eType; return rStrm; } // ----------------------------------------------------------------------- int SvxZoomItem::operator==( const SfxPoolItem& rAttr ) const { DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" ); SvxZoomItem& rItem = (SvxZoomItem&)rAttr; return ( GetValue() == rItem.GetValue() && nValueSet == rItem.GetValueSet() && eType == rItem.GetType() ); } sal_Bool SvxZoomItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const { // sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS); nMemberId &= ~CONVERT_TWIPS; switch ( nMemberId ) { case 0 : { ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq( ZOOM_PARAMS ); aSeq[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUE )); aSeq[0].Value <<= sal_Int32( GetValue() ); aSeq[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_VALUESET )); aSeq[1].Value <<= sal_Int16( nValueSet ); aSeq[2].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ZOOM_PARAM_TYPE )); aSeq[2].Value <<= sal_Int16( eType ); rVal <<= aSeq; } break; case MID_VALUE: rVal <<= (sal_Int32) GetValue(); break; case MID_VALUESET: rVal <<= (sal_Int16) nValueSet; break; case MID_TYPE: rVal <<= (sal_Int16) eType; break; default: DBG_ERROR("svx::SvxZoomItem::QueryValue(), Wrong MemberId!"); return sal_False; } return sal_True; } sal_Bool SvxZoomItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId ) { // sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS); nMemberId &= ~CONVERT_TWIPS; switch ( nMemberId ) { case 0 : { ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSeq; if (( rVal >>= aSeq ) && ( aSeq.getLength() == ZOOM_PARAMS )) { sal_Int32 nValueTmp( 0 ); sal_Int16 nValueSetTmp( 0 ); sal_Int16 nTypeTmp( 0 ); sal_Bool bAllConverted( sal_True ); sal_Int16 nConvertedCount( 0 ); for ( sal_Int32 i = 0; i < aSeq.getLength(); i++ ) { if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUE )) { bAllConverted &= ( aSeq[i].Value >>= nValueTmp ); ++nConvertedCount; } else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_VALUESET )) { bAllConverted &= ( aSeq[i].Value >>= nValueSetTmp ); ++nConvertedCount; } else if ( aSeq[i].Name.equalsAscii( ZOOM_PARAM_TYPE )) { bAllConverted &= ( aSeq[i].Value >>= nTypeTmp ); ++nConvertedCount; } } if ( bAllConverted && nConvertedCount == ZOOM_PARAMS ) { SetValue( (UINT16)nValueTmp ); nValueSet = nValueSetTmp; eType = SvxZoomType( nTypeTmp ); return sal_True; } } return sal_False; } case MID_VALUE: { sal_Int32 nVal = 0; if ( rVal >>= nVal ) { SetValue( (UINT16)nVal ); return sal_True; } else return sal_False; } case MID_VALUESET: case MID_TYPE: { sal_Int16 nVal = sal_Int16(); if ( rVal >>= nVal ) { if ( nMemberId == MID_VALUESET ) nValueSet = (sal_Int16) nVal; else if ( nMemberId == MID_TYPE ) eType = SvxZoomType( (sal_Int16) nVal ); return sal_True; } else return sal_False; } default: DBG_ERROR("svx::SvxZoomItem::PutValue(), Wrong MemberId!"); return sal_False; } return sal_True; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: svdoutl.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-03-30 15:39:29 $ * * 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 _SVDOUTL_HXX //autogen #include "svdoutl.hxx" #endif #ifndef _OUTLINER_HXX //autogen #include "outliner.hxx" #endif #ifndef _SVDOTEXT_HXX //autogen #include "svdotext.hxx" #endif #ifndef _EDITSTAT_HXX //autogen wg. EE_CNTRL_STRETCHING #include <editstat.hxx> #endif #ifndef _SVDMODEL_HXX //autogen wg. SdrModel #include <svdmodel.hxx> #endif #ifndef _EEITEM_HXX //autogen wg. EE_ITEMS_START #include <eeitem.hxx> #endif #ifndef _SFXITEMPOOL_HXX //autogen wg. SfxItemPool #include <svtools/itempool.hxx> #endif //TYPEINIT1( SdrOutliner, Outliner ); /************************************************************************* |* |* Ctor |* \************************************************************************/ SdrOutliner::SdrOutliner( SfxItemPool* pItemPool, USHORT nMode ): Outliner( pItemPool, nMode ), pTextObj( NULL ), mpPaintInfoRec( NULL ) { } /************************************************************************* |* |* Dtor |* \************************************************************************/ SdrOutliner::~SdrOutliner() { } /************************************************************************* |* |* |* \************************************************************************/ void SdrOutliner::SetTextObj( const SdrTextObj* pObj ) { if( pObj && pObj != pTextObj ) { SetUpdateMode(FALSE); USHORT nOutlinerMode = OUTLINERMODE_OUTLINEOBJECT; if ( !pObj->IsOutlText() ) nOutlinerMode = OUTLINERMODE_TEXTOBJECT; Init( nOutlinerMode ); SetGlobalCharStretching(100,100); ULONG nStat = GetControlWord(); nStat &= ~( EE_CNTRL_STRETCHING | EE_CNTRL_AUTOPAGESIZE ); SetControlWord(nStat); Size aNullSize; Size aMaxSize( 100000,100000 ); SetMinAutoPaperSize( aNullSize ); SetMaxAutoPaperSize( aMaxSize ); SetPaperSize( aMaxSize ); ClearPolygon(); } pTextObj = pObj; } /************************************************************************* |* |* |* \************************************************************************/ void SdrOutliner::SetTextObjNoInit( const SdrTextObj* pObj ) { pTextObj = pObj; } /************************************************************************* |* |* |* \************************************************************************/ XubString SdrOutliner::CalcFieldValue(const SvxFieldItem& rField, USHORT nPara, USHORT nPos, Color*& rpTxtColor, Color*& rpFldColor) { FASTBOOL bOk = FALSE; XubString aRet; if (pTextObj) bOk = pTextObj->CalcFieldValue(rField, nPara, nPos, FALSE, rpTxtColor, rpFldColor, aRet); if (!bOk) aRet = Outliner::CalcFieldValue(rField, nPara, nPos, rpTxtColor, rpFldColor); return aRet; } <commit_msg>INTEGRATION: CWS ooo19126 (1.3.952); FILE MERGED 2005/09/05 14:27:20 rt 1.3.952.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: svdoutl.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:37:42 $ * * 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 _SVDOUTL_HXX //autogen #include "svdoutl.hxx" #endif #ifndef _OUTLINER_HXX //autogen #include "outliner.hxx" #endif #ifndef _SVDOTEXT_HXX //autogen #include "svdotext.hxx" #endif #ifndef _EDITSTAT_HXX //autogen wg. EE_CNTRL_STRETCHING #include <editstat.hxx> #endif #ifndef _SVDMODEL_HXX //autogen wg. SdrModel #include <svdmodel.hxx> #endif #ifndef _EEITEM_HXX //autogen wg. EE_ITEMS_START #include <eeitem.hxx> #endif #ifndef _SFXITEMPOOL_HXX //autogen wg. SfxItemPool #include <svtools/itempool.hxx> #endif //TYPEINIT1( SdrOutliner, Outliner ); /************************************************************************* |* |* Ctor |* \************************************************************************/ SdrOutliner::SdrOutliner( SfxItemPool* pItemPool, USHORT nMode ): Outliner( pItemPool, nMode ), pTextObj( NULL ), mpPaintInfoRec( NULL ) { } /************************************************************************* |* |* Dtor |* \************************************************************************/ SdrOutliner::~SdrOutliner() { } /************************************************************************* |* |* |* \************************************************************************/ void SdrOutliner::SetTextObj( const SdrTextObj* pObj ) { if( pObj && pObj != pTextObj ) { SetUpdateMode(FALSE); USHORT nOutlinerMode = OUTLINERMODE_OUTLINEOBJECT; if ( !pObj->IsOutlText() ) nOutlinerMode = OUTLINERMODE_TEXTOBJECT; Init( nOutlinerMode ); SetGlobalCharStretching(100,100); ULONG nStat = GetControlWord(); nStat &= ~( EE_CNTRL_STRETCHING | EE_CNTRL_AUTOPAGESIZE ); SetControlWord(nStat); Size aNullSize; Size aMaxSize( 100000,100000 ); SetMinAutoPaperSize( aNullSize ); SetMaxAutoPaperSize( aMaxSize ); SetPaperSize( aMaxSize ); ClearPolygon(); } pTextObj = pObj; } /************************************************************************* |* |* |* \************************************************************************/ void SdrOutliner::SetTextObjNoInit( const SdrTextObj* pObj ) { pTextObj = pObj; } /************************************************************************* |* |* |* \************************************************************************/ XubString SdrOutliner::CalcFieldValue(const SvxFieldItem& rField, USHORT nPara, USHORT nPos, Color*& rpTxtColor, Color*& rpFldColor) { FASTBOOL bOk = FALSE; XubString aRet; if (pTextObj) bOk = pTextObj->CalcFieldValue(rField, nPara, nPos, FALSE, rpTxtColor, rpFldColor, aRet); if (!bOk) aRet = Outliner::CalcFieldValue(rField, nPara, nPos, rpTxtColor, rpFldColor); return aRet; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dpage.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2003-04-17 13:58:52 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _BASMGR_HXX #include <basic/basmgr.hxx> #endif #ifndef _GOODIES_IMAPOBJ_HXX #include <svtools/imapobj.hxx> #endif #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #ifndef _URLOBJ_HXX //autogen #include <tools/urlobj.hxx> #endif #ifndef _SV_HELP_HXX //autogen #include <vcl/help.hxx> #endif #ifndef _SVDVIEW_HXX //autogen #include <svx/svdview.hxx> #endif #ifndef _FMTURL_HXX //autogen #include <fmturl.hxx> #endif #ifndef _FRMFMT_HXX //autogen #include <frmfmt.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _DOCSH_HXX #include <docsh.hxx> #endif #ifndef _VIEWIMP_HXX #include <viewimp.hxx> #endif #ifndef _PAGEFRM_HXX #include <pagefrm.hxx> #endif #ifndef _CNTFRM_HXX #include <cntfrm.hxx> #endif #ifndef _ROOTFRM_HXX #include <rootfrm.hxx> #endif #ifndef _ERRHDL_HXX #include <errhdl.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _FRMATR_HXX #include <frmatr.hxx> #endif #ifndef _VIEWSH_HXX #include <viewsh.hxx> #endif #ifndef _DRAWDOC_HXX #include <drawdoc.hxx> #endif #ifndef _DPAGE_HXX #include <dpage.hxx> #endif #ifndef _DCONTACT_HXX #include <dcontact.hxx> #endif #ifndef _DFLYOBJ_HXX #include <dflyobj.hxx> #endif #ifndef _DOCSH_HXX #include <docsh.hxx> #endif #ifndef _USRFLD_HXX #include <usrfld.hxx> #endif #ifndef _FLYFRM_HXX #include <flyfrm.hxx> #endif #ifndef _NDNOTXT_HXX #include <ndnotxt.hxx> #endif #ifndef _GRFATR_HXX #include <grfatr.hxx> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESUPPLIER_HPP_ #include <com/sun/star/drawing/XDrawPageSupplier.hpp> #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::frame; SwDPage::SwDPage(SwDrawDocument& rNewModel, BOOL bMasterPage) : FmFormPage(rNewModel, 0, bMasterPage), pGridLst( 0 ), rDoc(rNewModel.GetDoc()) { } SwDPage::~SwDPage() { delete pGridLst; } // #i3694# // This GetOffset() method is not needed anymore, it even leads to errors. //Point SwDPage::GetOffset() const //{ // return Point( DOCUMENTBORDER, DOCUMENTBORDER ); //} /************************************************************************* |* |* SwDPage::ReplaceObject() |* |* Ersterstellung MA 07. Aug. 95 |* Letzte Aenderung MA 07. Aug. 95 |* *************************************************************************/ SdrObject* SwDPage::ReplaceObject( SdrObject* pNewObj, ULONG nObjNum ) { SdrObject *pOld = GetObj( nObjNum ); ASSERT( pOld, "Oups, Object not replaced" ); SdrObjUserCall* pContact; if ( 0 != ( pContact = GetUserCall(pOld) ) && RES_DRAWFRMFMT == ((SwContact*)pContact)->GetFmt()->Which()) ((SwDrawContact*)pContact)->ChangeMasterObject( pNewObj ); return FmFormPage::ReplaceObject( pNewObj, nObjNum ); } /************************************************************************* |* |* SwDPage::GetGridFrameList() |* |* Ersterstellung MA 04. Sep. 95 |* Letzte Aenderung MA 15. Feb. 96 |* *************************************************************************/ void InsertGridFrame( SdrPageGridFrameList *pLst, const SwFrm *pPg ) { SwRect aPrt( pPg->Prt() ); aPrt += pPg->Frm().Pos(); const Rectangle aUser( aPrt.SVRect() ); const Rectangle aPaper( pPg->Frm().SVRect() ); pLst->Insert( SdrPageGridFrame( aPaper, aUser ) ); } const SdrPageGridFrameList* SwDPage::GetGridFrameList( const SdrPageView* pPV, const Rectangle *pRect ) const { ViewShell *pSh = ((SwDrawDocument*)GetModel())->GetDoc().GetRootFrm()->GetCurrShell(); if ( pSh ) { while ( pSh->Imp()->GetPageView() != pPV ) pSh = (ViewShell*)pSh->GetNext(); if ( pSh ) { if ( pGridLst ) ((SwDPage*)this)->pGridLst->Clear(); else ((SwDPage*)this)->pGridLst = new SdrPageGridFrameList; if ( pRect ) { //Das Drawing verlang alle Seiten, die mit dem Rect ueberlappen. const SwRect aRect( *pRect ); const SwFrm *pPg = pSh->GetLayout()->Lower(); do { if ( pPg->Frm().IsOver( aRect ) ) ::InsertGridFrame( ((SwDPage*)this)->pGridLst, pPg ); pPg = pPg->GetNext(); } while ( pPg ); } else { //Das Drawing verlangt alle sichbaren Seiten const SwFrm *pPg = pSh->Imp()->GetFirstVisPage(); if ( pPg ) do { ::InsertGridFrame( ((SwDPage*)this)->pGridLst, pPg ); pPg = pPg->GetNext(); } while ( pPg && pPg->Frm().IsOver( pSh->VisArea() ) ); } } } return pGridLst; } /************************************************************************* |* |* String SwDPage::GetLinkData( const String& ) |* void SwDPage::SetLinkData( const String&, const String& ) |* void SwDPage::UpdateLinkData( const String&, const String& ) |* |* Ersterstellung JP 04.09.95 |* Letzte Aenderung JP 04.09.95 |* *************************************************************************/ String SwDPage::GetLinkData( const String& rLinkName ) { SwDoc& rDoc = ((SwDrawDocument*)GetModel())->GetDoc(); SwFieldType* pFTyp = rDoc.GetFldType( RES_USERFLD, rLinkName ); if( pFTyp ) return ((SwUserFieldType*)pFTyp)->GetContent(); return aEmptyStr; } void SwDPage::SetLinkData( const String& rLinkName, const String& rLinkData ) { SwDoc& rDoc = ((SwDrawDocument*)GetModel())->GetDoc(); SwFieldType* pFTyp = rDoc.GetFldType( RES_USERFLD, rLinkName ); if( pFTyp ) ((SwUserFieldType*)pFTyp)->CtrlSetContent( rLinkData ); } void SwDPage::RequestBasic() { SwDoc& rDoc = ((SwDrawDocument*)GetModel())->GetDoc(); if( rDoc.GetDocShell() ) { BasicManager *pBasicMgr = rDoc.GetDocShell()->GetBasicManager(); ASSERT( pBasicMgr, "wo ist mein BasicManager" ) SetBasic( pBasicMgr->GetLib( 0 ) ); } else ASSERT( !this, "wo ist meine DocShell" ) } BOOL SwDPage::RequestHelp( Window* pWindow, SdrView* pView, const HelpEvent& rEvt ) { BOOL bWeiter = TRUE; if( rEvt.GetMode() & ( HELPMODE_QUICK | HELPMODE_BALLOON )) { Point aPos( rEvt.GetMousePosPixel() ); aPos = pWindow->ScreenToOutputPixel( aPos ); aPos = pWindow->PixelToLogic( aPos ); SdrPageView* pPV; SdrObject* pObj; if( pView->PickObj( aPos, 0, pObj, pPV, SDRSEARCH_PICKMACRO ) && pObj->IsWriterFlyFrame() ) { SwFlyFrm *pFly = ((SwVirtFlyDrawObj*)pObj)->GetFlyFrm(); const SwFmtURL &rURL = pFly->GetFmt()->GetURL(); String sTxt; if( rURL.GetMap() ) { IMapObject *pObj = pFly->GetFmt()->GetIMapObject( aPos, pFly ); if( pObj ) { sTxt = pObj->GetDescription(); if ( !sTxt.Len() ) sTxt = URIHelper::removePassword( pObj->GetURL(), INetURLObject::WAS_ENCODED, INetURLObject::DECODE_UNAMBIGUOUS); } } else if ( rURL.GetURL().Len() ) { sTxt = URIHelper::removePassword( rURL.GetURL(), INetURLObject::WAS_ENCODED, INetURLObject::DECODE_UNAMBIGUOUS); if( rURL.IsServerMap() ) { // dann die rel. Pixel Position anhaengen !! Point aPt( aPos ); aPt -= pFly->Frm().Pos(); // ohne MapMode-Offset !!!!! // ohne MapMode-Offset, ohne Offset, o ... !!!!! aPt = (Point&)(Size&)pWindow->LogicToPixel( (Size&)aPt, MapMode( MAP_TWIP ) ); ((( sTxt += '?' ) += String::CreateFromInt32( aPt.X() )) += ',' ) += String::CreateFromInt32( aPt.Y() ); } } if ( sTxt.Len() ) { if( rEvt.GetMode() & HELPMODE_QUICK ) { // dann zeige die Hilfe mal an: Rectangle aRect( rEvt.GetMousePosPixel(), Size(1,1) ); /* Bug 29593: QuickHelp immer an der MausPosition anzeigen (besonders unter OS/2) Rectangle aRect( pObj->GetSnapRect() ); Point aPt( pWindow->OutputToScreenPixel( pWindow->LogicToPixel( aRect.TopLeft() ))); aRect.Left() = aPt.X(); aRect.Top() = aPt.Y(); aPt = pWindow->OutputToScreenPixel( pWindow->LogicToPixel( aRect.BottomRight() )); aRect.Right() = aPt.X(); aRect.Bottom() = aPt.Y(); */ Help::ShowQuickHelp( pWindow, aRect, sTxt ); } else Help::ShowBalloon( pWindow, rEvt.GetMousePosPixel(), sTxt ); bWeiter = FALSE; } } } if( bWeiter ) bWeiter = !FmFormPage::RequestHelp( pWindow, pView, rEvt ); return bWeiter; } /* -----------------------------27.11.00 07:35-------------------------------- ---------------------------------------------------------------------------*/ Reference< XInterface > SwDPage::createUnoPage() { Reference<XModel> xModel = rDoc.GetDocShell()->GetBaseModel(); Reference<XDrawPageSupplier> xPageSupp(xModel, UNO_QUERY); return xPageSupp->getDrawPage(); } <commit_msg>INTEGRATION: CWS aw003 (1.5.6); FILE MERGED 2003/06/30 13:38:20 aw 1.5.6.1: #110094#<commit_after>/************************************************************************* * * $RCSfile: dpage.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2003-11-24 16:02:16 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _BASMGR_HXX #include <basic/basmgr.hxx> #endif #ifndef _GOODIES_IMAPOBJ_HXX #include <svtools/imapobj.hxx> #endif #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #ifndef _URLOBJ_HXX //autogen #include <tools/urlobj.hxx> #endif #ifndef _SV_HELP_HXX //autogen #include <vcl/help.hxx> #endif #ifndef _SVDVIEW_HXX //autogen #include <svx/svdview.hxx> #endif #ifndef _FMTURL_HXX //autogen #include <fmturl.hxx> #endif #ifndef _FRMFMT_HXX //autogen #include <frmfmt.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _DOCSH_HXX #include <docsh.hxx> #endif #ifndef _VIEWIMP_HXX #include <viewimp.hxx> #endif #ifndef _PAGEFRM_HXX #include <pagefrm.hxx> #endif #ifndef _CNTFRM_HXX #include <cntfrm.hxx> #endif #ifndef _ROOTFRM_HXX #include <rootfrm.hxx> #endif #ifndef _ERRHDL_HXX #include <errhdl.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _FRMATR_HXX #include <frmatr.hxx> #endif #ifndef _VIEWSH_HXX #include <viewsh.hxx> #endif #ifndef _DRAWDOC_HXX #include <drawdoc.hxx> #endif #ifndef _DPAGE_HXX #include <dpage.hxx> #endif #ifndef _DCONTACT_HXX #include <dcontact.hxx> #endif #ifndef _DFLYOBJ_HXX #include <dflyobj.hxx> #endif #ifndef _DOCSH_HXX #include <docsh.hxx> #endif #ifndef _USRFLD_HXX #include <usrfld.hxx> #endif #ifndef _FLYFRM_HXX #include <flyfrm.hxx> #endif #ifndef _NDNOTXT_HXX #include <ndnotxt.hxx> #endif #ifndef _GRFATR_HXX #include <grfatr.hxx> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESUPPLIER_HPP_ #include <com/sun/star/drawing/XDrawPageSupplier.hpp> #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::frame; SwDPage::SwDPage(SwDrawDocument& rNewModel, BOOL bMasterPage) : FmFormPage(rNewModel, 0, bMasterPage), pGridLst( 0 ), rDoc(rNewModel.GetDoc()) { } SwDPage::~SwDPage() { delete pGridLst; } // #i3694# // This GetOffset() method is not needed anymore, it even leads to errors. //Point SwDPage::GetOffset() const //{ // return Point( DOCUMENTBORDER, DOCUMENTBORDER ); //} /************************************************************************* |* |* SwDPage::ReplaceObject() |* |* Ersterstellung MA 07. Aug. 95 |* Letzte Aenderung MA 07. Aug. 95 |* *************************************************************************/ SdrObject* SwDPage::ReplaceObject( SdrObject* pNewObj, ULONG nObjNum ) { SdrObject *pOld = GetObj( nObjNum ); ASSERT( pOld, "Oups, Object not replaced" ); SdrObjUserCall* pContact; if ( 0 != ( pContact = GetUserCall(pOld) ) && RES_DRAWFRMFMT == ((SwContact*)pContact)->GetFmt()->Which()) ((SwDrawContact*)pContact)->ChangeMasterObject( pNewObj ); return FmFormPage::ReplaceObject( pNewObj, nObjNum ); } /************************************************************************* |* |* SwDPage::GetGridFrameList() |* |* Ersterstellung MA 04. Sep. 95 |* Letzte Aenderung MA 15. Feb. 96 |* *************************************************************************/ void InsertGridFrame( SdrPageGridFrameList *pLst, const SwFrm *pPg ) { SwRect aPrt( pPg->Prt() ); aPrt += pPg->Frm().Pos(); const Rectangle aUser( aPrt.SVRect() ); const Rectangle aPaper( pPg->Frm().SVRect() ); pLst->Insert( SdrPageGridFrame( aPaper, aUser ) ); } const SdrPageGridFrameList* SwDPage::GetGridFrameList( const SdrPageView* pPV, const Rectangle *pRect ) const { ViewShell *pSh = ((SwDrawDocument*)GetModel())->GetDoc().GetRootFrm()->GetCurrShell(); if ( pSh ) { while ( pSh->Imp()->GetPageView() != pPV ) pSh = (ViewShell*)pSh->GetNext(); if ( pSh ) { if ( pGridLst ) ((SwDPage*)this)->pGridLst->Clear(); else ((SwDPage*)this)->pGridLst = new SdrPageGridFrameList; if ( pRect ) { //Das Drawing verlang alle Seiten, die mit dem Rect ueberlappen. const SwRect aRect( *pRect ); const SwFrm *pPg = pSh->GetLayout()->Lower(); do { if ( pPg->Frm().IsOver( aRect ) ) ::InsertGridFrame( ((SwDPage*)this)->pGridLst, pPg ); pPg = pPg->GetNext(); } while ( pPg ); } else { //Das Drawing verlangt alle sichbaren Seiten const SwFrm *pPg = pSh->Imp()->GetFirstVisPage(); if ( pPg ) do { ::InsertGridFrame( ((SwDPage*)this)->pGridLst, pPg ); pPg = pPg->GetNext(); } while ( pPg && pPg->Frm().IsOver( pSh->VisArea() ) ); } } } return pGridLst; } /************************************************************************* |* |* String SwDPage::GetLinkData( const String& ) |* void SwDPage::SetLinkData( const String&, const String& ) |* void SwDPage::UpdateLinkData( const String&, const String& ) |* |* Ersterstellung JP 04.09.95 |* Letzte Aenderung JP 04.09.95 |* *************************************************************************/ String SwDPage::GetLinkData( const String& rLinkName ) { SwDoc& rDoc = ((SwDrawDocument*)GetModel())->GetDoc(); SwFieldType* pFTyp = rDoc.GetFldType( RES_USERFLD, rLinkName ); if( pFTyp ) return ((SwUserFieldType*)pFTyp)->GetContent(); return aEmptyStr; } void SwDPage::SetLinkData( const String& rLinkName, const String& rLinkData ) { SwDoc& rDoc = ((SwDrawDocument*)GetModel())->GetDoc(); SwFieldType* pFTyp = rDoc.GetFldType( RES_USERFLD, rLinkName ); if( pFTyp ) ((SwUserFieldType*)pFTyp)->CtrlSetContent( rLinkData ); } void SwDPage::RequestBasic() { SwDoc& rDoc = ((SwDrawDocument*)GetModel())->GetDoc(); if( rDoc.GetDocShell() ) { BasicManager *pBasicMgr = rDoc.GetDocShell()->GetBasicManager(); ASSERT( pBasicMgr, "wo ist mein BasicManager" ) SetBasic( pBasicMgr->GetLib( 0 ) ); } else ASSERT( !this, "wo ist meine DocShell" ) } BOOL SwDPage::RequestHelp( Window* pWindow, SdrView* pView, const HelpEvent& rEvt ) { BOOL bWeiter = TRUE; if( rEvt.GetMode() & ( HELPMODE_QUICK | HELPMODE_BALLOON )) { Point aPos( rEvt.GetMousePosPixel() ); aPos = pWindow->ScreenToOutputPixel( aPos ); aPos = pWindow->PixelToLogic( aPos ); SdrPageView* pPV; SdrObject* pObj; if( pView->PickObj( aPos, 0, pObj, pPV, SDRSEARCH_PICKMACRO ) && pObj->ISA(SwVirtFlyDrawObj) ) { SwFlyFrm *pFly = ((SwVirtFlyDrawObj*)pObj)->GetFlyFrm(); const SwFmtURL &rURL = pFly->GetFmt()->GetURL(); String sTxt; if( rURL.GetMap() ) { IMapObject *pObj = pFly->GetFmt()->GetIMapObject( aPos, pFly ); if( pObj ) { sTxt = pObj->GetDescription(); if ( !sTxt.Len() ) sTxt = URIHelper::removePassword( pObj->GetURL(), INetURLObject::WAS_ENCODED, INetURLObject::DECODE_UNAMBIGUOUS); } } else if ( rURL.GetURL().Len() ) { sTxt = URIHelper::removePassword( rURL.GetURL(), INetURLObject::WAS_ENCODED, INetURLObject::DECODE_UNAMBIGUOUS); if( rURL.IsServerMap() ) { // dann die rel. Pixel Position anhaengen !! Point aPt( aPos ); aPt -= pFly->Frm().Pos(); // ohne MapMode-Offset !!!!! // ohne MapMode-Offset, ohne Offset, o ... !!!!! aPt = (Point&)(Size&)pWindow->LogicToPixel( (Size&)aPt, MapMode( MAP_TWIP ) ); ((( sTxt += '?' ) += String::CreateFromInt32( aPt.X() )) += ',' ) += String::CreateFromInt32( aPt.Y() ); } } if ( sTxt.Len() ) { if( rEvt.GetMode() & HELPMODE_QUICK ) { // dann zeige die Hilfe mal an: Rectangle aRect( rEvt.GetMousePosPixel(), Size(1,1) ); /* Bug 29593: QuickHelp immer an der MausPosition anzeigen (besonders unter OS/2) Rectangle aRect( pObj->GetSnapRect() ); Point aPt( pWindow->OutputToScreenPixel( pWindow->LogicToPixel( aRect.TopLeft() ))); aRect.Left() = aPt.X(); aRect.Top() = aPt.Y(); aPt = pWindow->OutputToScreenPixel( pWindow->LogicToPixel( aRect.BottomRight() )); aRect.Right() = aPt.X(); aRect.Bottom() = aPt.Y(); */ Help::ShowQuickHelp( pWindow, aRect, sTxt ); } else Help::ShowBalloon( pWindow, rEvt.GetMousePosPixel(), sTxt ); bWeiter = FALSE; } } } if( bWeiter ) bWeiter = !FmFormPage::RequestHelp( pWindow, pView, rEvt ); return bWeiter; } /* -----------------------------27.11.00 07:35-------------------------------- ---------------------------------------------------------------------------*/ Reference< XInterface > SwDPage::createUnoPage() { Reference<XModel> xModel = rDoc.GetDocShell()->GetBaseModel(); Reference<XDrawPageSupplier> xPageSupp(xModel, UNO_QUERY); return xPageSupp->getDrawPage(); } <|endoftext|>
<commit_before><commit_msg>coverity#1257109 Unchecked dynamic_cast<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: flyfrm.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2003-04-24 09:51:35 $ * * 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 _FLYFRM_HXX #define _FLYFRM_HXX #include "layfrm.hxx" class SwPageFrm; class SwFlyFrmFmt; class SwFmtFrmSize; struct SwCrsrMoveState; class SwBorderAttrs; class SwVirtFlyDrawObj; class SwSpzFrmFmts; class SwAttrSetChg; class PolyPolygon; #include <orntenum.hxx> //Sucht ausgehend von pOldAnch einen Anker fuer Absatzgebundene Rahmen. //Wird beim Draggen von Absatzgebundenen Objekten zur Ankeranzeige sowie //fuer Ankerwechsel benoetigt. //implementiert in layout/flycnt.cxx const SwCntntFrm *FindAnchor( const SwFrm *pOldAnch, const Point &rNew, const BOOL bBody = FALSE ); // berechnet das Rechteck, in dem das Objekt bewegt bzw. resized werden darf BOOL CalcClipRect( const SdrObject *pSdrObj, SwRect &rRect, BOOL bMove = TRUE ); //allg. Basisklasse fuer alle Freifliegenden Rahmen class SwFlyFrm : public SwLayoutFrm { //darf Locken. Definiert in frmtool.cxx friend void AppendObjs ( const SwSpzFrmFmts *, ULONG, SwFrm *, SwPageFrm * ); friend void AppendAllObjs( const SwSpzFrmFmts * ); friend void Notify( SwFlyFrm *, SwPageFrm *pOld, const SwRect &rOld ); //darf die Pos berechnen (lassen) friend void lcl_MakeFlyPosition( SwFlyFrm *pFly ); void InitDrawObj( BOOL bNotify ); //Wird von den CToren gerufen. void FinitDrawObj(); //Wird vom CTor gerufen. void _UpdateAttr( SfxPoolItem*, SfxPoolItem*, BYTE &, SwAttrSetChg *pa = 0, SwAttrSetChg *pb = 0 ); protected: SwVirtFlyDrawObj *pDrawObj; // das Drawingobject zum Fly SwFrm *pAnchor; // An diesem LayoutFrm haengt der Frm, kann 0 sein SwFlyFrm *pPrevLink, // Vorgaenger/Nachfolger fuer Verkettung mit *pNextLink; // Textfluss Point aRelPos; //Die Relative Position zum Master private: BOOL bLocked :1; //Cntnt-gebundene Flys muessen derart blockiert werden //koennen, dass sie nicht Formatiert werden; :MakeAll //returnt dann sofort. Dies ist bei Seitenwechseln //waehrend der Formatierung notwendig. //Auch wahrend des RootCTors ist dies notwendig da //sonst der Anker formatiert wird obwohl die Root noch //nicht korrekt an der Shell haengt und weil sonst //initial zuviel Formatiert wuerde. BOOL bNotifyBack:1; //TRUE wenn am Ende eines MakeAll() der Background //vom NotifyDTor benachrichtigt werden muss. protected: BOOL bInvalid :1; //Pos, PrtArea od. SSize wurden Invalidiert, sie werden //gleich wieder Validiert, denn sie muessen _immer_ //gueltig sein. Damit in LayAction korrekt gearbeitet //werden kann muss hier festgehalten werden, dass sie //invalidiert wurden. Ausnahmen bestaetigen die Regelt! BOOL bMinHeight:1; //TRUE wenn die vom Attribut vorgegebene Hoehe eine //eine Minimalhoehe ist (der Frm also bei Bedarf //darueberhinaus wachsen kann). BOOL bHeightClipped :1; //TRUE wenn der Fly nicht die Pos/Size anhand der Attrs BOOL bWidthClipped :1; //formatieren konnte, weil z.B. nicht genug Raum vorh. //war. BOOL bFormatHeightOnly :1; //Damit nach einer Anpassung der Breite //(CheckClip) nur das Format aufgerufen wird; //nicht aber die Breite anhand der Attribute //wieder bestimmt wird. BOOL bInCnt :1; // FLY_IN_CNTNT, als Zeichen verankert BOOL bAtCnt :1; // FLY_AT_CNTNT, am Absatz verankert BOOL bLayout :1; // FLY_PAGE, FLY_AT_FLY, an Seite oder Rahmen BOOL bAutoPosition :1; // FLY_AUTO_CNTNT, im Text verankerter Rahmen BOOL bNoShrink :1; // temporary forbud of shrinking to avoid loops friend class SwNoTxtFrm; // Darf NotifyBackground rufen virtual void NotifyBackground( SwPageFrm *pPage, const SwRect& rRect, PrepareHint eHint) = 0; //Wird nur von SwXFrm::MakeAll() gerufen; wer es anders macht wird //in einen Sack gesteckt und muss zwei Tage drin hocken bleiben. virtual void MakeFlyPos(); virtual void Format( const SwBorderAttrs *pAttrs = 0 ); void MakePrtArea( const SwBorderAttrs &rAttrs ); void Lock() { bLocked = TRUE; } void Unlock() { bLocked = FALSE; } void SetMinHeight() { bMinHeight = TRUE; } void ResetMinHeight(){ bMinHeight = FALSE; } Size CalcRel( const SwFmtFrmSize &rSz ) const; SwFlyFrm( SwFlyFrmFmt*, SwFrm *pAnchor ); public: virtual ~SwFlyFrm(); virtual void Modify( SfxPoolItem*, SfxPoolItem* ); // erfrage vom Client Informationen virtual BOOL GetInfo( SfxPoolItem& ) const; virtual void Paint( const SwRect& ) const; virtual void ChgSize( const Size& aNewSize ); virtual BOOL GetCrsrOfst( SwPosition *, Point&, const SwCrsrMoveState* = 0 ) const; virtual void CheckDirection( BOOL bVert ); virtual void Cut(); #ifndef PRODUCT virtual void Paste( SwFrm* pParent, SwFrm* pSibling = 0 ); #endif SwTwips _Shrink( SwTwips, SZPTR BOOL bTst ); SwTwips _Grow ( SwTwips, SZPTR BOOL bTst ); void _Invalidate( SwPageFrm *pPage = 0 ); BOOL FrmSizeChg( const SwFmtFrmSize & ); const SwFrm *GetAnchor() const { return pAnchor; } SwFrm *GetAnchor() { return pAnchor; } void ChgAnchor( SwFrm *pNew ) { pAnchor = pNew; } SwFlyFrm *GetPrevLink() { return pPrevLink; } SwFlyFrm *GetNextLink() { return pNextLink; } static void ChainFrames( SwFlyFrm *pMaster, SwFlyFrm *pFollow ); static void UnchainFrames( SwFlyFrm *pMaster, SwFlyFrm *pFollow ); SwFlyFrm *FindChainNeighbour( SwFrmFmt &rFmt, SwFrm *pAnch = 0 ); const SwVirtFlyDrawObj *GetVirtDrawObj() const { return pDrawObj; } SwVirtFlyDrawObj *GetVirtDrawObj() { return pDrawObj; } void NotifyDrawObj(); const Point& GetCurRelPos() const { return aRelPos; } void ChgRelPos( const Point &rAbsPos ); BOOL IsInvalid() const { return bInvalid; } void Invalidate() const { ((SwFlyFrm*)this)->bInvalid = TRUE; } void Validate() const { ((SwFlyFrm*)this)->bInvalid = FALSE; } BOOL IsMinHeight() const { return bMinHeight; } BOOL IsLocked() const { return bLocked; } BOOL IsAutoPos() const { return bAutoPosition; } BOOL IsFlyInCntFrm() const { return bInCnt; } BOOL IsFlyFreeFrm() const { return bAtCnt || bLayout; } BOOL IsFlyLayFrm() const { return bLayout; } BOOL IsFlyAtCntFrm() const { return bAtCnt; } BOOL IsNotifyBack() const { return bNotifyBack; } void SetNotifyBack() { bNotifyBack = TRUE; } void ResetNotifyBack() { bNotifyBack = FALSE; } BOOL IsNoShrink() const { return bNoShrink; } void SetNoShrink( BOOL bNew ) { bNoShrink = bNew; } BOOL IsClipped() const { return bHeightClipped || bWidthClipped; } BOOL IsHeightClipped() const { return bHeightClipped; } BOOL IsWidthClipped() const { return bWidthClipped; } BOOL IsLowerOf( const SwLayoutFrm *pUpper ) const; inline BOOL IsUpperOf( const SwFlyFrm *pLower ) const; SwFrm *FindLastLower(); SwRect AddSpacesToFrm() const; // OD 16.04.2003 #i13147# - add parameter <_bForPaint> to avoid load of // the graphic during paint. Default value: sal_False BOOL GetContour( PolyPolygon& rContour, const sal_Bool _bForPaint = sal_False ) const; BOOL ConvertHoriTo40( SwHoriOrient &rHori, SwRelationOrient &rRel, SwTwips &rPos ) const; //Auf dieser Shell painten (PreView, Print-Flag usw. rekursiv beachten)?. static BOOL IsPaint( SdrObject *pObj, const ViewShell *pSh ); /** SwFlyFrm::IsBackgroundTransparent - for feature #99657# OD 12.08.2002 determines, if background of fly frame has to be drawn transparent definition found in /core/layout/paintfrm.cxx @author OD @return true, if background color is transparent or a existing background graphic is transparent. */ const sal_Bool IsBackgroundTransparent() const; /** SwFlyFrm::IsShadowTransparent - for feature #99657# OD 05.08.2002 determine, if shadow color of fly frame has to be drawn transparent definition found in /core/layout/paintfrm.cxx @author OD @return true, if shadow color is transparent. */ const sal_Bool IsShadowTransparent() const; }; inline BOOL SwFlyFrm::IsUpperOf( const SwFlyFrm *pLower ) const { return pLower->IsLowerOf( this ); } #endif <commit_msg>INTEGRATION: CWS swobjpos02 (1.7.142); FILE MERGED 2003/10/02 10:11:24 od 1.7.142.1: #110978# class <SwFlyFrm> - declare class <SwAnchoredObjectPosition> as friend.<commit_after>/************************************************************************* * * $RCSfile: flyfrm.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2004-02-02 18:18:30 $ * * 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 _FLYFRM_HXX #define _FLYFRM_HXX #include "layfrm.hxx" class SwPageFrm; class SwFlyFrmFmt; class SwFmtFrmSize; struct SwCrsrMoveState; class SwBorderAttrs; class SwVirtFlyDrawObj; class SwSpzFrmFmts; class SwAttrSetChg; class PolyPolygon; // OD 01.08.2003 #110978# namespace objectpositioning { class SwAnchoredObjectPosition; } #include <orntenum.hxx> //Sucht ausgehend von pOldAnch einen Anker fuer Absatzgebundene Rahmen. //Wird beim Draggen von Absatzgebundenen Objekten zur Ankeranzeige sowie //fuer Ankerwechsel benoetigt. //implementiert in layout/flycnt.cxx const SwCntntFrm *FindAnchor( const SwFrm *pOldAnch, const Point &rNew, const BOOL bBody = FALSE ); // berechnet das Rechteck, in dem das Objekt bewegt bzw. resized werden darf BOOL CalcClipRect( const SdrObject *pSdrObj, SwRect &rRect, BOOL bMove = TRUE ); //allg. Basisklasse fuer alle Freifliegenden Rahmen class SwFlyFrm : public SwLayoutFrm { //darf Locken. Definiert in frmtool.cxx friend void AppendObjs ( const SwSpzFrmFmts *, ULONG, SwFrm *, SwPageFrm * ); friend void AppendAllObjs( const SwSpzFrmFmts * ); friend void Notify( SwFlyFrm *, SwPageFrm *pOld, const SwRect &rOld ); //darf die Pos berechnen (lassen) friend void lcl_MakeFlyPosition( SwFlyFrm *pFly ); // OD 01.08.2003 #110978# - access for calculation of position friend class objectpositioning::SwAnchoredObjectPosition; void InitDrawObj( BOOL bNotify ); //Wird von den CToren gerufen. void FinitDrawObj(); //Wird vom CTor gerufen. void _UpdateAttr( SfxPoolItem*, SfxPoolItem*, BYTE &, SwAttrSetChg *pa = 0, SwAttrSetChg *pb = 0 ); protected: SwVirtFlyDrawObj *pDrawObj; // das Drawingobject zum Fly SwFrm *pAnchor; // An diesem LayoutFrm haengt der Frm, kann 0 sein SwFlyFrm *pPrevLink, // Vorgaenger/Nachfolger fuer Verkettung mit *pNextLink; // Textfluss Point aRelPos; //Die Relative Position zum Master private: BOOL bLocked :1; //Cntnt-gebundene Flys muessen derart blockiert werden //koennen, dass sie nicht Formatiert werden; :MakeAll //returnt dann sofort. Dies ist bei Seitenwechseln //waehrend der Formatierung notwendig. //Auch wahrend des RootCTors ist dies notwendig da //sonst der Anker formatiert wird obwohl die Root noch //nicht korrekt an der Shell haengt und weil sonst //initial zuviel Formatiert wuerde. BOOL bNotifyBack:1; //TRUE wenn am Ende eines MakeAll() der Background //vom NotifyDTor benachrichtigt werden muss. protected: BOOL bInvalid :1; //Pos, PrtArea od. SSize wurden Invalidiert, sie werden //gleich wieder Validiert, denn sie muessen _immer_ //gueltig sein. Damit in LayAction korrekt gearbeitet //werden kann muss hier festgehalten werden, dass sie //invalidiert wurden. Ausnahmen bestaetigen die Regelt! BOOL bMinHeight:1; //TRUE wenn die vom Attribut vorgegebene Hoehe eine //eine Minimalhoehe ist (der Frm also bei Bedarf //darueberhinaus wachsen kann). BOOL bHeightClipped :1; //TRUE wenn der Fly nicht die Pos/Size anhand der Attrs BOOL bWidthClipped :1; //formatieren konnte, weil z.B. nicht genug Raum vorh. //war. BOOL bFormatHeightOnly :1; //Damit nach einer Anpassung der Breite //(CheckClip) nur das Format aufgerufen wird; //nicht aber die Breite anhand der Attribute //wieder bestimmt wird. BOOL bInCnt :1; // FLY_IN_CNTNT, als Zeichen verankert BOOL bAtCnt :1; // FLY_AT_CNTNT, am Absatz verankert BOOL bLayout :1; // FLY_PAGE, FLY_AT_FLY, an Seite oder Rahmen BOOL bAutoPosition :1; // FLY_AUTO_CNTNT, im Text verankerter Rahmen BOOL bNoShrink :1; // temporary forbud of shrinking to avoid loops friend class SwNoTxtFrm; // Darf NotifyBackground rufen virtual void NotifyBackground( SwPageFrm *pPage, const SwRect& rRect, PrepareHint eHint) = 0; //Wird nur von SwXFrm::MakeAll() gerufen; wer es anders macht wird //in einen Sack gesteckt und muss zwei Tage drin hocken bleiben. virtual void MakeFlyPos(); virtual void Format( const SwBorderAttrs *pAttrs = 0 ); void MakePrtArea( const SwBorderAttrs &rAttrs ); void Lock() { bLocked = TRUE; } void Unlock() { bLocked = FALSE; } void SetMinHeight() { bMinHeight = TRUE; } void ResetMinHeight(){ bMinHeight = FALSE; } Size CalcRel( const SwFmtFrmSize &rSz ) const; SwFlyFrm( SwFlyFrmFmt*, SwFrm *pAnchor ); public: virtual ~SwFlyFrm(); virtual void Modify( SfxPoolItem*, SfxPoolItem* ); // erfrage vom Client Informationen virtual BOOL GetInfo( SfxPoolItem& ) const; virtual void Paint( const SwRect& ) const; virtual void ChgSize( const Size& aNewSize ); virtual BOOL GetCrsrOfst( SwPosition *, Point&, const SwCrsrMoveState* = 0 ) const; virtual void CheckDirection( BOOL bVert ); virtual void Cut(); #ifndef PRODUCT virtual void Paste( SwFrm* pParent, SwFrm* pSibling = 0 ); #endif SwTwips _Shrink( SwTwips, SZPTR BOOL bTst ); SwTwips _Grow ( SwTwips, SZPTR BOOL bTst ); void _Invalidate( SwPageFrm *pPage = 0 ); BOOL FrmSizeChg( const SwFmtFrmSize & ); const SwFrm *GetAnchor() const { return pAnchor; } SwFrm *GetAnchor() { return pAnchor; } void ChgAnchor( SwFrm *pNew ) { pAnchor = pNew; } SwFlyFrm *GetPrevLink() { return pPrevLink; } SwFlyFrm *GetNextLink() { return pNextLink; } static void ChainFrames( SwFlyFrm *pMaster, SwFlyFrm *pFollow ); static void UnchainFrames( SwFlyFrm *pMaster, SwFlyFrm *pFollow ); SwFlyFrm *FindChainNeighbour( SwFrmFmt &rFmt, SwFrm *pAnch = 0 ); const SwVirtFlyDrawObj *GetVirtDrawObj() const { return pDrawObj; } SwVirtFlyDrawObj *GetVirtDrawObj() { return pDrawObj; } void NotifyDrawObj(); const Point& GetCurRelPos() const { return aRelPos; } void ChgRelPos( const Point &rAbsPos ); BOOL IsInvalid() const { return bInvalid; } void Invalidate() const { ((SwFlyFrm*)this)->bInvalid = TRUE; } void Validate() const { ((SwFlyFrm*)this)->bInvalid = FALSE; } BOOL IsMinHeight() const { return bMinHeight; } BOOL IsLocked() const { return bLocked; } BOOL IsAutoPos() const { return bAutoPosition; } BOOL IsFlyInCntFrm() const { return bInCnt; } BOOL IsFlyFreeFrm() const { return bAtCnt || bLayout; } BOOL IsFlyLayFrm() const { return bLayout; } BOOL IsFlyAtCntFrm() const { return bAtCnt; } BOOL IsNotifyBack() const { return bNotifyBack; } void SetNotifyBack() { bNotifyBack = TRUE; } void ResetNotifyBack() { bNotifyBack = FALSE; } BOOL IsNoShrink() const { return bNoShrink; } void SetNoShrink( BOOL bNew ) { bNoShrink = bNew; } BOOL IsClipped() const { return bHeightClipped || bWidthClipped; } BOOL IsHeightClipped() const { return bHeightClipped; } BOOL IsWidthClipped() const { return bWidthClipped; } BOOL IsLowerOf( const SwLayoutFrm *pUpper ) const; inline BOOL IsUpperOf( const SwFlyFrm *pLower ) const; SwFrm *FindLastLower(); SwRect AddSpacesToFrm() const; // OD 16.04.2003 #i13147# - add parameter <_bForPaint> to avoid load of // the graphic during paint. Default value: sal_False BOOL GetContour( PolyPolygon& rContour, const sal_Bool _bForPaint = sal_False ) const; BOOL ConvertHoriTo40( SwHoriOrient &rHori, SwRelationOrient &rRel, SwTwips &rPos ) const; //Auf dieser Shell painten (PreView, Print-Flag usw. rekursiv beachten)?. static BOOL IsPaint( SdrObject *pObj, const ViewShell *pSh ); /** SwFlyFrm::IsBackgroundTransparent - for feature #99657# OD 12.08.2002 determines, if background of fly frame has to be drawn transparent definition found in /core/layout/paintfrm.cxx @author OD @return true, if background color is transparent or a existing background graphic is transparent. */ const sal_Bool IsBackgroundTransparent() const; /** SwFlyFrm::IsShadowTransparent - for feature #99657# OD 05.08.2002 determine, if shadow color of fly frame has to be drawn transparent definition found in /core/layout/paintfrm.cxx @author OD @return true, if shadow color is transparent. */ const sal_Bool IsShadowTransparent() const; }; inline BOOL SwFlyFrm::IsUpperOf( const SwFlyFrm *pLower ) const { return pLower->IsLowerOf( this ); } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2006, MassaRoddel, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/peer_connection.hpp" #include "libtorrent/bt_peer_connection.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/extensions.hpp" #include "libtorrent/extensions/ut_pex.hpp" namespace libtorrent { namespace { const char extension_name[] = "ut_pex"; enum { extension_index = 1, max_peer_entries = 100 }; bool send_peer(peer_connection const& p) { // don't send out peers that we haven't connected to // (that have connected to us) if (!p.is_local()) return false; // don't send out peers that we haven't successfully connected to if (p.is_connecting()) return false; return true; } struct ut_pex_plugin: torrent_plugin { ut_pex_plugin(torrent& t): m_torrent(t), m_1_minute(0) {} virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection* pc); std::vector<char>& get_ut_pex_msg() { return m_ut_pex_msg; } // the second tick of the torrent // each minute the new lists of "added" + "added.f" and "dropped" // are calculated here and the pex message is created // each peer connection will use this message // max_peer_entries limits the packet size virtual void tick() { if (++m_1_minute < 60) return; m_1_minute = 0; entry pex; std::string& pla = pex["added"].string(); std::string& pld = pex["dropped"].string(); std::string& plf = pex["added.f"].string(); std::string& pla6 = pex["added6"].string(); std::string& pld6 = pex["dropped6"].string(); std::string& plf6 = pex["added6.f"].string(); std::back_insert_iterator<std::string> pla_out(pla); std::back_insert_iterator<std::string> pld_out(pld); std::back_insert_iterator<std::string> plf_out(plf); std::back_insert_iterator<std::string> pla6_out(pla6); std::back_insert_iterator<std::string> pld6_out(pld6); std::back_insert_iterator<std::string> plf6_out(plf6); std::set<tcp::endpoint> dropped; m_old_peers.swap(dropped); int num_added = 0; for (torrent::peer_iterator i = m_torrent.begin() , end(m_torrent.end()); i != end; ++i) { peer_connection* peer = *i; if (!send_peer(*peer)) continue; tcp::endpoint const& remote = peer->remote(); m_old_peers.insert(remote); std::set<tcp::endpoint>::iterator di = dropped.find(remote); if (di == dropped.end()) { // don't write too big of a package if (num_added >= max_peer_entries) break; // only send proper bittorrent peers bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer); if (!p) continue; // no supported flags to set yet // 0x01 - peer supports encryption // 0x02 - peer is a seed int flags = p->is_seed() ? 2 : 0; #ifndef TORRENT_DISABLE_ENCRYPTION flags |= p->supports_encryption() ? 1 : 0; #endif // i->first was added since the last time if (remote.address().is_v4()) { detail::write_endpoint(remote, pla_out); detail::write_uint8(flags, plf_out); } else { detail::write_endpoint(remote, pla6_out); detail::write_uint8(flags, plf6_out); } ++num_added; } else { // this was in the previous message // so, it wasn't dropped dropped.erase(di); } } for (std::set<tcp::endpoint>::const_iterator i = dropped.begin() , end(dropped.end()); i != end; ++i) { if (i->address().is_v4()) detail::write_endpoint(*i, pld_out); else detail::write_endpoint(*i, pld6_out); } m_ut_pex_msg.clear(); bencode(std::back_inserter(m_ut_pex_msg), pex); } private: torrent& m_torrent; std::set<tcp::endpoint> m_old_peers; int m_1_minute; std::vector<char> m_ut_pex_msg; }; struct ut_pex_peer_plugin : peer_plugin { ut_pex_peer_plugin(torrent& t, peer_connection& pc, ut_pex_plugin& tp) : m_torrent(t) , m_pc(pc) , m_tp(tp) , m_1_minute(0) , m_message_index(0) , m_first_time(true) {} virtual void add_handshake(entry& h) { entry& messages = h["m"]; messages[extension_name] = extension_index; } virtual bool on_extension_handshake(entry const& h) { entry const& messages = h["m"]; if (entry const* index = messages.find_key(extension_name)) { m_message_index = index->integer(); return true; } else { m_message_index = 0; return false; } } virtual bool on_extended(int length, int msg, buffer::const_interval body) { if (msg != extension_index) return false; if (m_message_index == 0) return false; if (length > 500 * 1024) throw protocol_error("uT peer exchange message larger than 500 kB"); if (body.left() < length) return true; try { entry pex_msg = bdecode(body.begin, body.end); std::string const& peers = pex_msg["added"].string(); std::string const& peer_flags = pex_msg["added.f"].string(); int num_peers = peers.length() / 6; char const* in = peers.c_str(); char const* fin = peer_flags.c_str(); if (int(peer_flags.size()) != num_peers) return true; peer_id pid(0); policy& p = m_torrent.get_policy(); for (int i = 0; i < num_peers; ++i) { tcp::endpoint adr = detail::read_v4_endpoint<tcp::endpoint>(in); char flags = detail::read_uint8(fin); p.peer_from_tracker(adr, pid, peer_info::pex, flags); } if (entry const* p6 = pex_msg.find_key("added6")) { std::string const& peers6 = p6->string(); std::string const& peer6_flags = pex_msg["added6.f"].string(); int num_peers = peers6.length() / 18; char const* in = peers6.c_str(); char const* fin = peer6_flags.c_str(); if (int(peer6_flags.size()) != num_peers) return true; peer_id pid(0); policy& p = m_torrent.get_policy(); for (int i = 0; i < num_peers; ++i) { tcp::endpoint adr = detail::read_v6_endpoint<tcp::endpoint>(in); char flags = detail::read_uint8(fin); p.peer_from_tracker(adr, pid, peer_info::pex, flags); } } } catch (std::exception&) { throw protocol_error("invalid uT peer exchange message"); } return true; } // the peers second tick // every minute we send a pex message virtual void tick() { if (!m_message_index) return; // no handshake yet if (++m_1_minute <= 60) return; if (m_first_time) { send_ut_peer_list(); m_first_time = false; } else { send_ut_peer_diff(); } m_1_minute = 0; } private: void send_ut_peer_diff() { std::vector<char> const& pex_msg = m_tp.get_ut_pex_msg(); buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size()); detail::write_uint32(1 + 1 + pex_msg.size(), i.begin); detail::write_uint8(bt_peer_connection::msg_extended, i.begin); detail::write_uint8(m_message_index, i.begin); std::copy(pex_msg.begin(), pex_msg.end(), i.begin); i.begin += pex_msg.size(); TORRENT_ASSERT(i.begin == i.end); m_pc.setup_send(); } void send_ut_peer_list() { entry pex; // leave the dropped string empty pex["dropped"].string(); std::string& pla = pex["added"].string(); std::string& plf = pex["added.f"].string(); pex["dropped6"].string(); std::string& pla6 = pex["added6"].string(); std::string& plf6 = pex["added6.f"].string(); std::back_insert_iterator<std::string> pla_out(pla); std::back_insert_iterator<std::string> plf_out(plf); std::back_insert_iterator<std::string> pla6_out(pla6); std::back_insert_iterator<std::string> plf6_out(plf6); int num_added = 0; for (torrent::peer_iterator i = m_torrent.begin() , end(m_torrent.end()); i != end; ++i) { peer_connection* peer = *i; if (!send_peer(*peer)) continue; // don't write too big of a package if (num_added >= max_peer_entries) break; // only send proper bittorrent peers bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer); if (!p) continue; // no supported flags to set yet // 0x01 - peer supports encryption // 0x02 - peer is a seed int flags = p->is_seed() ? 2 : 0; #ifndef TORRENT_DISABLE_ENCRYPTION flags |= p->supports_encryption() ? 1 : 0; #endif tcp::endpoint const& remote = peer->remote(); // i->first was added since the last time if (remote.address().is_v4()) { detail::write_endpoint(remote, pla_out); detail::write_uint8(flags, plf_out); } else { detail::write_endpoint(remote, pla6_out); detail::write_uint8(flags, plf6_out); } ++num_added; } std::vector<char> pex_msg; bencode(std::back_inserter(pex_msg), pex); buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size()); detail::write_uint32(1 + 1 + pex_msg.size(), i.begin); detail::write_uint8(bt_peer_connection::msg_extended, i.begin); detail::write_uint8(m_message_index, i.begin); std::copy(pex_msg.begin(), pex_msg.end(), i.begin); i.begin += pex_msg.size(); TORRENT_ASSERT(i.begin == i.end); m_pc.setup_send(); } torrent& m_torrent; peer_connection& m_pc; ut_pex_plugin& m_tp; int m_1_minute; int m_message_index; // this is initialized to true, and set to // false after the first pex message has been sent. // it is used to know if a diff message or a full // message should be sent. bool m_first_time; }; boost::shared_ptr<peer_plugin> ut_pex_plugin::new_connection(peer_connection* pc) { bt_peer_connection* c = dynamic_cast<bt_peer_connection*>(pc); if (!c) return boost::shared_ptr<peer_plugin>(); return boost::shared_ptr<peer_plugin>(new ut_pex_peer_plugin(m_torrent , *pc, *this)); } }} namespace libtorrent { boost::shared_ptr<torrent_plugin> create_ut_pex_plugin(torrent* t, void*) { if (t->torrent_file().priv()) { return boost::shared_ptr<torrent_plugin>(); } return boost::shared_ptr<torrent_plugin>(new ut_pex_plugin(*t)); } } <commit_msg>ut_pex sends peers sooner<commit_after>/* Copyright (c) 2006, MassaRoddel, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/peer_connection.hpp" #include "libtorrent/bt_peer_connection.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/extensions.hpp" #include "libtorrent/extensions/ut_pex.hpp" namespace libtorrent { namespace { const char extension_name[] = "ut_pex"; enum { extension_index = 1, max_peer_entries = 100 }; bool send_peer(peer_connection const& p) { // don't send out peers that we haven't connected to // (that have connected to us) if (!p.is_local()) return false; // don't send out peers that we haven't successfully connected to if (p.is_connecting()) return false; return true; } struct ut_pex_plugin: torrent_plugin { ut_pex_plugin(torrent& t): m_torrent(t), m_1_minute(55) {} virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection* pc); std::vector<char>& get_ut_pex_msg() { return m_ut_pex_msg; } // the second tick of the torrent // each minute the new lists of "added" + "added.f" and "dropped" // are calculated here and the pex message is created // each peer connection will use this message // max_peer_entries limits the packet size virtual void tick() { if (++m_1_minute < 60) return; m_1_minute = 0; entry pex; std::string& pla = pex["added"].string(); std::string& pld = pex["dropped"].string(); std::string& plf = pex["added.f"].string(); std::string& pla6 = pex["added6"].string(); std::string& pld6 = pex["dropped6"].string(); std::string& plf6 = pex["added6.f"].string(); std::back_insert_iterator<std::string> pla_out(pla); std::back_insert_iterator<std::string> pld_out(pld); std::back_insert_iterator<std::string> plf_out(plf); std::back_insert_iterator<std::string> pla6_out(pla6); std::back_insert_iterator<std::string> pld6_out(pld6); std::back_insert_iterator<std::string> plf6_out(plf6); std::set<tcp::endpoint> dropped; m_old_peers.swap(dropped); int num_added = 0; for (torrent::peer_iterator i = m_torrent.begin() , end(m_torrent.end()); i != end; ++i) { peer_connection* peer = *i; if (!send_peer(*peer)) continue; tcp::endpoint const& remote = peer->remote(); m_old_peers.insert(remote); std::set<tcp::endpoint>::iterator di = dropped.find(remote); if (di == dropped.end()) { // don't write too big of a package if (num_added >= max_peer_entries) break; // only send proper bittorrent peers bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer); if (!p) continue; // no supported flags to set yet // 0x01 - peer supports encryption // 0x02 - peer is a seed int flags = p->is_seed() ? 2 : 0; #ifndef TORRENT_DISABLE_ENCRYPTION flags |= p->supports_encryption() ? 1 : 0; #endif // i->first was added since the last time if (remote.address().is_v4()) { detail::write_endpoint(remote, pla_out); detail::write_uint8(flags, plf_out); } else { detail::write_endpoint(remote, pla6_out); detail::write_uint8(flags, plf6_out); } ++num_added; } else { // this was in the previous message // so, it wasn't dropped dropped.erase(di); } } for (std::set<tcp::endpoint>::const_iterator i = dropped.begin() , end(dropped.end()); i != end; ++i) { if (i->address().is_v4()) detail::write_endpoint(*i, pld_out); else detail::write_endpoint(*i, pld6_out); } m_ut_pex_msg.clear(); bencode(std::back_inserter(m_ut_pex_msg), pex); } private: torrent& m_torrent; std::set<tcp::endpoint> m_old_peers; int m_1_minute; std::vector<char> m_ut_pex_msg; }; struct ut_pex_peer_plugin : peer_plugin { ut_pex_peer_plugin(torrent& t, peer_connection& pc, ut_pex_plugin& tp) : m_torrent(t) , m_pc(pc) , m_tp(tp) , m_1_minute(55) , m_message_index(0) , m_first_time(true) {} virtual void add_handshake(entry& h) { entry& messages = h["m"]; messages[extension_name] = extension_index; } virtual bool on_extension_handshake(entry const& h) { entry const& messages = h["m"]; if (entry const* index = messages.find_key(extension_name)) { m_message_index = index->integer(); return true; } else { m_message_index = 0; return false; } } virtual bool on_extended(int length, int msg, buffer::const_interval body) { if (msg != extension_index) return false; if (m_message_index == 0) return false; if (length > 500 * 1024) throw protocol_error("uT peer exchange message larger than 500 kB"); if (body.left() < length) return true; try { entry pex_msg = bdecode(body.begin, body.end); std::string const& peers = pex_msg["added"].string(); std::string const& peer_flags = pex_msg["added.f"].string(); int num_peers = peers.length() / 6; char const* in = peers.c_str(); char const* fin = peer_flags.c_str(); if (int(peer_flags.size()) != num_peers) return true; peer_id pid(0); policy& p = m_torrent.get_policy(); for (int i = 0; i < num_peers; ++i) { tcp::endpoint adr = detail::read_v4_endpoint<tcp::endpoint>(in); char flags = detail::read_uint8(fin); p.peer_from_tracker(adr, pid, peer_info::pex, flags); } if (entry const* p6 = pex_msg.find_key("added6")) { std::string const& peers6 = p6->string(); std::string const& peer6_flags = pex_msg["added6.f"].string(); int num_peers = peers6.length() / 18; char const* in = peers6.c_str(); char const* fin = peer6_flags.c_str(); if (int(peer6_flags.size()) != num_peers) return true; peer_id pid(0); policy& p = m_torrent.get_policy(); for (int i = 0; i < num_peers; ++i) { tcp::endpoint adr = detail::read_v6_endpoint<tcp::endpoint>(in); char flags = detail::read_uint8(fin); p.peer_from_tracker(adr, pid, peer_info::pex, flags); } } } catch (std::exception&) { throw protocol_error("invalid uT peer exchange message"); } return true; } // the peers second tick // every minute we send a pex message virtual void tick() { if (!m_message_index) return; // no handshake yet if (++m_1_minute <= 60) return; if (m_first_time) { send_ut_peer_list(); m_first_time = false; } else { send_ut_peer_diff(); } m_1_minute = 0; } private: void send_ut_peer_diff() { std::vector<char> const& pex_msg = m_tp.get_ut_pex_msg(); buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size()); detail::write_uint32(1 + 1 + pex_msg.size(), i.begin); detail::write_uint8(bt_peer_connection::msg_extended, i.begin); detail::write_uint8(m_message_index, i.begin); std::copy(pex_msg.begin(), pex_msg.end(), i.begin); i.begin += pex_msg.size(); TORRENT_ASSERT(i.begin == i.end); m_pc.setup_send(); } void send_ut_peer_list() { entry pex; // leave the dropped string empty pex["dropped"].string(); std::string& pla = pex["added"].string(); std::string& plf = pex["added.f"].string(); pex["dropped6"].string(); std::string& pla6 = pex["added6"].string(); std::string& plf6 = pex["added6.f"].string(); std::back_insert_iterator<std::string> pla_out(pla); std::back_insert_iterator<std::string> plf_out(plf); std::back_insert_iterator<std::string> pla6_out(pla6); std::back_insert_iterator<std::string> plf6_out(plf6); int num_added = 0; for (torrent::peer_iterator i = m_torrent.begin() , end(m_torrent.end()); i != end; ++i) { peer_connection* peer = *i; if (!send_peer(*peer)) continue; // don't write too big of a package if (num_added >= max_peer_entries) break; // only send proper bittorrent peers bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer); if (!p) continue; // no supported flags to set yet // 0x01 - peer supports encryption // 0x02 - peer is a seed int flags = p->is_seed() ? 2 : 0; #ifndef TORRENT_DISABLE_ENCRYPTION flags |= p->supports_encryption() ? 1 : 0; #endif tcp::endpoint const& remote = peer->remote(); // i->first was added since the last time if (remote.address().is_v4()) { detail::write_endpoint(remote, pla_out); detail::write_uint8(flags, plf_out); } else { detail::write_endpoint(remote, pla6_out); detail::write_uint8(flags, plf6_out); } ++num_added; } std::vector<char> pex_msg; bencode(std::back_inserter(pex_msg), pex); buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size()); detail::write_uint32(1 + 1 + pex_msg.size(), i.begin); detail::write_uint8(bt_peer_connection::msg_extended, i.begin); detail::write_uint8(m_message_index, i.begin); std::copy(pex_msg.begin(), pex_msg.end(), i.begin); i.begin += pex_msg.size(); TORRENT_ASSERT(i.begin == i.end); m_pc.setup_send(); } torrent& m_torrent; peer_connection& m_pc; ut_pex_plugin& m_tp; int m_1_minute; int m_message_index; // this is initialized to true, and set to // false after the first pex message has been sent. // it is used to know if a diff message or a full // message should be sent. bool m_first_time; }; boost::shared_ptr<peer_plugin> ut_pex_plugin::new_connection(peer_connection* pc) { bt_peer_connection* c = dynamic_cast<bt_peer_connection*>(pc); if (!c) return boost::shared_ptr<peer_plugin>(); return boost::shared_ptr<peer_plugin>(new ut_pex_peer_plugin(m_torrent , *pc, *this)); } }} namespace libtorrent { boost::shared_ptr<torrent_plugin> create_ut_pex_plugin(torrent* t, void*) { if (t->torrent_file().priv()) { return boost::shared_ptr<torrent_plugin>(); } return boost::shared_ptr<torrent_plugin>(new ut_pex_plugin(*t)); } } <|endoftext|>
<commit_before>/* Copyright (C) 2007-2008 Tanguy Krotoff <[email protected]> Copyright (C) 2008 Lukas Durfina <[email protected]> Copyright (C) 2009 Fathi Boudra <[email protected]> Copyright (C) 2009-2011 vlc-phonon AUTHORS Copyright (C) 2011 Harald Sitter <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "backend.h" #include <QtCore/QCoreApplication> #include <QtCore/QLatin1Literal> #include <QtCore/QtPlugin> #include <QtCore/QVariant> #include <QMessageBox> #include <phonon/GlobalDescriptionContainer> #include <phonon/pulsesupport.h> #include <vlc/libvlc_version.h> #include "audio/audiooutput.h" #include "audio/audiodataoutput.h" #include "audio/volumefadereffect.h" #include "devicemanager.h" #include "effect.h" #include "effectmanager.h" #include "mediaobject.h" #include "sinknode.h" #include "utils/debug.h" #include "utils/libvlc.h" #include "utils/mime.h" #ifdef PHONON_EXPERIMENTAL #include "video/videodataoutput.h" #endif #ifndef PHONON_NO_GRAPHICSVIEW #include "video/videographicsobject.h" #endif #include "video/videowidget.h" #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(phonon_vlc, Phonon::VLC::Backend) #endif namespace Phonon { namespace VLC { Backend *Backend::self; Backend::Backend(QObject *parent, const QVariantList &) : QObject(parent) , m_deviceManager(0) , m_effectManager(0) { self = this; // Backend information properties setProperty("identifier", QLatin1String("phonon_vlc")); setProperty("backendName", QLatin1String("VLC")); setProperty("backendComment", QLatin1String("VLC backend for Phonon")); setProperty("backendVersion", QLatin1String(PHONON_VLC_VERSION)); setProperty("backendIcon", QLatin1String("vlc")); setProperty("backendWebsite", QLatin1String("https://projects.kde.org/projects/kdesupport/phonon/phonon-vlc")); // Check if we should enable debug output int debugLevel = qgetenv("PHONON_BACKEND_DEBUG").toInt(); if (debugLevel > 3) // 3 is maximum debugLevel = 3; Debug::setMinimumDebugLevel((Debug::DebugLevel)((int) Debug::DEBUG_NONE - 1 - debugLevel)); // Actual libVLC initialisation if (LibVLC::init()) { debug() << "Using VLC version" << libvlc_get_version(); QString userAgent = QString("%0/%1 (Phonon/%2; Phonon-VLC/%3)").arg( QCoreApplication::applicationName(), QCoreApplication::applicationVersion(), PHONON_VERSION_STR, PHONON_VLC_VERSION); libvlc_set_user_agent(libvlc, QCoreApplication::applicationName().toUtf8().constData(), userAgent.toUtf8().constData()); } else { #ifdef __GNUC__ #warning TODO - this error message is about as useful as a cooling unit in the arctic #endif QMessageBox msg; msg.setIcon(QMessageBox::Critical); msg.setWindowTitle(tr("LibVLC Failed to Initialize")); msg.setText(tr("Phonon's VLC backend failed to start." "\n\n" "This usually means a problem with your VLC installation," " please report a bug with your distributor.")); msg.setDetailedText(LibVLC::errorMessage()); msg.exec(); fatal() << "Phonon::VLC::vlcInit: Failed to initialize VLC"; } // Initialise PulseAudio support PulseSupport *pulse = PulseSupport::getInstance(); pulse->enable(); connect(pulse, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SIGNAL(objectDescriptionChanged(ObjectDescriptionType))); m_deviceManager = new DeviceManager(this); m_effectManager = new EffectManager(this); } Backend::~Backend() { if (LibVLC::self) delete LibVLC::self; if (GlobalAudioChannels::self) delete GlobalAudioChannels::self; if (GlobalSubtitles::self) delete GlobalSubtitles::self; PulseSupport::shutdown(); } QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &/*args*/) { if (!LibVLC::self || !libvlc) return 0; switch (c) { case MediaObjectClass: return new MediaObject(parent); case AudioOutputClass: return new AudioOutput(parent); #ifdef __GNUC__ #warning using sout in VLC2 breaks libvlcs vout functions, see vlc bug 6992 // https://trac.videolan.org/vlc/ticket/6992 #endif #if (LIBVLC_VERSION_INT < LIBVLC_VERSION(2, 0, 0, 0)) // FWIW: the case is inside the if because that gives clear indication which // frontend objects are not supported! case AudioDataOutputClass: return new AudioDataOutput(parent); #endif #ifdef PHONON_EXPERIMENTAL case VideoDataOutputClass: return new VideoDataOutput(parent); #endif #ifndef PHONON_NO_GRAPHICSVIEW case VideoGraphicsObjectClass: return new VideoGraphicsObject(parent); #endif case VideoWidgetClass: return new VideoWidget(qobject_cast<QWidget *>(parent)); case VolumeFaderEffectClass: return new VolumeFaderEffect(parent); } warning() << "Backend class" << c << "is not supported by Phonon VLC :("; return 0; } QStringList Backend::availableMimeTypes() const { if (m_supportedMimeTypes.isEmpty()) const_cast<Backend *>(this)->m_supportedMimeTypes = mimeTypeList(); return m_supportedMimeTypes; } QList<int> Backend::objectDescriptionIndexes(ObjectDescriptionType type) const { QList<int> list; switch (type) { case Phonon::AudioChannelType: { list << GlobalAudioChannels::instance()->globalIndexes(); } break; case Phonon::AudioOutputDeviceType: case Phonon::AudioCaptureDeviceType: case Phonon::VideoCaptureDeviceType: { return deviceManager()->deviceIds(type); } break; case Phonon::EffectType: { QList<EffectInfo *> effectList = effectManager()->effects(); for (int eff = 0; eff < effectList.size(); ++eff) { list.append(eff); } } break; case Phonon::SubtitleType: { list << GlobalSubtitles::instance()->globalIndexes(); } break; } return list; } QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(ObjectDescriptionType type, int index) const { QHash<QByteArray, QVariant> ret; switch (type) { case Phonon::AudioChannelType: { const AudioChannelDescription description = GlobalAudioChannels::instance()->fromIndex(index); ret.insert("name", description.name()); ret.insert("description", description.description()); } break; case Phonon::AudioOutputDeviceType: case Phonon::AudioCaptureDeviceType: case Phonon::VideoCaptureDeviceType: { // Index should be unique, even for different categories return deviceManager()->deviceProperties(index); } break; case Phonon::EffectType: { QList<EffectInfo *> effectList = effectManager()->effects(); if (index >= 0 && index <= effectList.size()) { const EffectInfo *effect = effectList[ index ]; ret.insert("name", effect->name()); ret.insert("description", effect->description()); ret.insert("author", effect->author()); } else { Q_ASSERT(1); // Since we use list position as ID, this should not happen } } break; case Phonon::SubtitleType: { const SubtitleDescription description = GlobalSubtitles::instance()->fromIndex(index); ret.insert("name", description.name()); ret.insert("description", description.description()); ret.insert("type", description.property("type")); } break; } return ret; } bool Backend::startConnectionChange(QSet<QObject *> objects) { //FIXME foreach(QObject * object, objects) { debug() << "Object:" << object->metaObject()->className(); } // There is nothing we can do but hope the connection changes will not take too long // so that buffers would underrun // But we should be pretty safe the way xine works by not doing anything here. return true; } bool Backend::connectNodes(QObject *source, QObject *sink) { debug() << "Backend connected" << source->metaObject()->className() << "to" << sink->metaObject()->className(); SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink); if (sinkNode) { MediaObject *mediaObject = qobject_cast<MediaObject *>(source); if (mediaObject) { // Connect the SinkNode to a MediaObject sinkNode->connectToMediaObject(mediaObject); return true; } VolumeFaderEffect *effect = qobject_cast<VolumeFaderEffect *>(source); if (effect) { sinkNode->connectToMediaObject(effect->mediaObject()); return true; } } warning() << "Linking" << source->metaObject()->className() << "to" << sink->metaObject()->className() << "failed"; return false; } bool Backend::disconnectNodes(QObject *source, QObject *sink) { SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink); if (sinkNode) { MediaObject *const mediaObject = qobject_cast<MediaObject *>(source); if (mediaObject) { // Disconnect the SinkNode from a MediaObject sinkNode->disconnectFromMediaObject(mediaObject); return true; } /* Effect *effect = qobject_cast<Effect *>(source); if (effect) { // FIXME disconnect the effect return true; } */ } return false; } bool Backend::endConnectionChange(QSet<QObject *> objects) { foreach(QObject *object, objects) { debug() << "Object:" << object->metaObject()->className(); } return true; } DeviceManager *Backend::deviceManager() const { return m_deviceManager; } EffectManager *Backend::effectManager() const { return m_effectManager; } } // namespace VLC } // namespace Phonon <commit_msg>don't set useragent when applicationName is empty<commit_after>/* Copyright (C) 2007-2008 Tanguy Krotoff <[email protected]> Copyright (C) 2008 Lukas Durfina <[email protected]> Copyright (C) 2009 Fathi Boudra <[email protected]> Copyright (C) 2009-2011 vlc-phonon AUTHORS Copyright (C) 2011 Harald Sitter <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "backend.h" #include <QtCore/QCoreApplication> #include <QtCore/QLatin1Literal> #include <QtCore/QtPlugin> #include <QtCore/QVariant> #include <QMessageBox> #include <phonon/GlobalDescriptionContainer> #include <phonon/pulsesupport.h> #include <vlc/libvlc_version.h> #include "audio/audiooutput.h" #include "audio/audiodataoutput.h" #include "audio/volumefadereffect.h" #include "devicemanager.h" #include "effect.h" #include "effectmanager.h" #include "mediaobject.h" #include "sinknode.h" #include "utils/debug.h" #include "utils/libvlc.h" #include "utils/mime.h" #ifdef PHONON_EXPERIMENTAL #include "video/videodataoutput.h" #endif #ifndef PHONON_NO_GRAPHICSVIEW #include "video/videographicsobject.h" #endif #include "video/videowidget.h" #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(phonon_vlc, Phonon::VLC::Backend) #endif namespace Phonon { namespace VLC { Backend *Backend::self; Backend::Backend(QObject *parent, const QVariantList &) : QObject(parent) , m_deviceManager(0) , m_effectManager(0) { self = this; // Backend information properties setProperty("identifier", QLatin1String("phonon_vlc")); setProperty("backendName", QLatin1String("VLC")); setProperty("backendComment", QLatin1String("VLC backend for Phonon")); setProperty("backendVersion", QLatin1String(PHONON_VLC_VERSION)); setProperty("backendIcon", QLatin1String("vlc")); setProperty("backendWebsite", QLatin1String("https://projects.kde.org/projects/kdesupport/phonon/phonon-vlc")); // Check if we should enable debug output int debugLevel = qgetenv("PHONON_BACKEND_DEBUG").toInt(); if (debugLevel > 3) // 3 is maximum debugLevel = 3; Debug::setMinimumDebugLevel((Debug::DebugLevel)((int) Debug::DEBUG_NONE - 1 - debugLevel)); // Actual libVLC initialisation if (LibVLC::init()) { debug() << "Using VLC version" << libvlc_get_version(); if (!QCoreApplication::applicationName().isEmpty()) { QString userAgent = QString("%0/%1 (Phonon/%2; Phonon-VLC/%3)").arg( QCoreApplication::applicationName(), QCoreApplication::applicationVersion(), PHONON_VERSION_STR, PHONON_VLC_VERSION); libvlc_set_user_agent(libvlc, QCoreApplication::applicationName().toUtf8().constData(), userAgent.toUtf8().constData()); } else { qWarning("WARNING: Setting the user agent for streaming and PulseAudio requires you to set QCoreApplication::applicationName()"); } } else { #ifdef __GNUC__ #warning TODO - this error message is about as useful as a cooling unit in the arctic #endif QMessageBox msg; msg.setIcon(QMessageBox::Critical); msg.setWindowTitle(tr("LibVLC Failed to Initialize")); msg.setText(tr("Phonon's VLC backend failed to start." "\n\n" "This usually means a problem with your VLC installation," " please report a bug with your distributor.")); msg.setDetailedText(LibVLC::errorMessage()); msg.exec(); fatal() << "Phonon::VLC::vlcInit: Failed to initialize VLC"; } // Initialise PulseAudio support PulseSupport *pulse = PulseSupport::getInstance(); pulse->enable(); connect(pulse, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SIGNAL(objectDescriptionChanged(ObjectDescriptionType))); m_deviceManager = new DeviceManager(this); m_effectManager = new EffectManager(this); } Backend::~Backend() { if (LibVLC::self) delete LibVLC::self; if (GlobalAudioChannels::self) delete GlobalAudioChannels::self; if (GlobalSubtitles::self) delete GlobalSubtitles::self; PulseSupport::shutdown(); } QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &/*args*/) { if (!LibVLC::self || !libvlc) return 0; switch (c) { case MediaObjectClass: return new MediaObject(parent); case AudioOutputClass: return new AudioOutput(parent); #ifdef __GNUC__ #warning using sout in VLC2 breaks libvlcs vout functions, see vlc bug 6992 // https://trac.videolan.org/vlc/ticket/6992 #endif #if (LIBVLC_VERSION_INT < LIBVLC_VERSION(2, 0, 0, 0)) // FWIW: the case is inside the if because that gives clear indication which // frontend objects are not supported! case AudioDataOutputClass: return new AudioDataOutput(parent); #endif #ifdef PHONON_EXPERIMENTAL case VideoDataOutputClass: return new VideoDataOutput(parent); #endif #ifndef PHONON_NO_GRAPHICSVIEW case VideoGraphicsObjectClass: return new VideoGraphicsObject(parent); #endif case VideoWidgetClass: return new VideoWidget(qobject_cast<QWidget *>(parent)); case VolumeFaderEffectClass: return new VolumeFaderEffect(parent); } warning() << "Backend class" << c << "is not supported by Phonon VLC :("; return 0; } QStringList Backend::availableMimeTypes() const { if (m_supportedMimeTypes.isEmpty()) const_cast<Backend *>(this)->m_supportedMimeTypes = mimeTypeList(); return m_supportedMimeTypes; } QList<int> Backend::objectDescriptionIndexes(ObjectDescriptionType type) const { QList<int> list; switch (type) { case Phonon::AudioChannelType: { list << GlobalAudioChannels::instance()->globalIndexes(); } break; case Phonon::AudioOutputDeviceType: case Phonon::AudioCaptureDeviceType: case Phonon::VideoCaptureDeviceType: { return deviceManager()->deviceIds(type); } break; case Phonon::EffectType: { QList<EffectInfo *> effectList = effectManager()->effects(); for (int eff = 0; eff < effectList.size(); ++eff) { list.append(eff); } } break; case Phonon::SubtitleType: { list << GlobalSubtitles::instance()->globalIndexes(); } break; } return list; } QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(ObjectDescriptionType type, int index) const { QHash<QByteArray, QVariant> ret; switch (type) { case Phonon::AudioChannelType: { const AudioChannelDescription description = GlobalAudioChannels::instance()->fromIndex(index); ret.insert("name", description.name()); ret.insert("description", description.description()); } break; case Phonon::AudioOutputDeviceType: case Phonon::AudioCaptureDeviceType: case Phonon::VideoCaptureDeviceType: { // Index should be unique, even for different categories return deviceManager()->deviceProperties(index); } break; case Phonon::EffectType: { QList<EffectInfo *> effectList = effectManager()->effects(); if (index >= 0 && index <= effectList.size()) { const EffectInfo *effect = effectList[ index ]; ret.insert("name", effect->name()); ret.insert("description", effect->description()); ret.insert("author", effect->author()); } else { Q_ASSERT(1); // Since we use list position as ID, this should not happen } } break; case Phonon::SubtitleType: { const SubtitleDescription description = GlobalSubtitles::instance()->fromIndex(index); ret.insert("name", description.name()); ret.insert("description", description.description()); ret.insert("type", description.property("type")); } break; } return ret; } bool Backend::startConnectionChange(QSet<QObject *> objects) { //FIXME foreach(QObject * object, objects) { debug() << "Object:" << object->metaObject()->className(); } // There is nothing we can do but hope the connection changes will not take too long // so that buffers would underrun // But we should be pretty safe the way xine works by not doing anything here. return true; } bool Backend::connectNodes(QObject *source, QObject *sink) { debug() << "Backend connected" << source->metaObject()->className() << "to" << sink->metaObject()->className(); SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink); if (sinkNode) { MediaObject *mediaObject = qobject_cast<MediaObject *>(source); if (mediaObject) { // Connect the SinkNode to a MediaObject sinkNode->connectToMediaObject(mediaObject); return true; } VolumeFaderEffect *effect = qobject_cast<VolumeFaderEffect *>(source); if (effect) { sinkNode->connectToMediaObject(effect->mediaObject()); return true; } } warning() << "Linking" << source->metaObject()->className() << "to" << sink->metaObject()->className() << "failed"; return false; } bool Backend::disconnectNodes(QObject *source, QObject *sink) { SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink); if (sinkNode) { MediaObject *const mediaObject = qobject_cast<MediaObject *>(source); if (mediaObject) { // Disconnect the SinkNode from a MediaObject sinkNode->disconnectFromMediaObject(mediaObject); return true; } /* Effect *effect = qobject_cast<Effect *>(source); if (effect) { // FIXME disconnect the effect return true; } */ } return false; } bool Backend::endConnectionChange(QSet<QObject *> objects) { foreach(QObject *object, objects) { debug() << "Object:" << object->metaObject()->className(); } return true; } DeviceManager *Backend::deviceManager() const { return m_deviceManager; } EffectManager *Backend::effectManager() const { return m_effectManager; } } // namespace VLC } // namespace Phonon <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. */ #include "clang/Lex/Lexer.h" #include "compat.hxx" #include "plugin.hxx" namespace { class LiteralToBoolConversion: public RecursiveASTVisitor<LiteralToBoolConversion>, public loplugin::RewritePlugin { public: explicit LiteralToBoolConversion(InstantiationData const & data): RewritePlugin(data) {} virtual void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); } bool VisitImplicitCastExpr(ImplicitCastExpr const * expr); private: bool isFromCIncludeFile(SourceLocation spellingLocation) const; }; bool LiteralToBoolConversion::VisitImplicitCastExpr( ImplicitCastExpr const * expr) { if (ignoreLocation(expr)) { return true; } if (!expr->getType()->isBooleanType()) { return true; } Expr const * sub = expr->getSubExpr()->IgnoreParenCasts(); Expr const * expr2 = expr; for (;;) { BinaryOperator const * op = dyn_cast<BinaryOperator>(sub); if (op == nullptr || op->getOpcode() != BO_Comma) { break; } expr2 = op->getRHS()->IgnoreParenCasts(); sub = expr2; } if (sub->getType()->isBooleanType()) { return true; } APSInt res; if (!sub->isValueDependent() && sub->isIntegerConstantExpr(res, compiler.getASTContext()) && res.getLimitedValue() <= 1) { SourceLocation loc { sub->getLocStart() }; while (compiler.getSourceManager().isMacroArgExpansion(loc)) { loc = compiler.getSourceManager().getImmediateMacroCallerLoc(loc); } if (compat::isMacroBodyExpansion(compiler, loc)) { StringRef name { Lexer::getImmediateMacroName( loc, compiler.getSourceManager(), compiler.getLangOpts()) }; if (name == "sal_False" || name == "sal_True") { loc = compiler.getSourceManager().getImmediateExpansionRange( loc).first; } if (isFromCIncludeFile( compiler.getSourceManager().getSpellingLoc(loc))) { return true; } } } if (isa<StringLiteral>(sub)) { SourceLocation loc { sub->getLocStart() }; if (compiler.getSourceManager().isMacroArgExpansion(loc) && (Lexer::getImmediateMacroName( loc, compiler.getSourceManager(), compiler.getLangOpts()) == "assert")) { return true; } } if (isa<IntegerLiteral>(sub) || isa<CharacterLiteral>(sub) || isa<FloatingLiteral>(sub) || isa<ImaginaryLiteral>(sub) || isa<StringLiteral>(sub)) { bool rewritten = false; if (rewriter != nullptr) { SourceLocation loc { compiler.getSourceManager().getExpansionLoc( expr->getLocStart()) }; if (compiler.getSourceManager().getExpansionLoc(expr->getLocEnd()) == loc) { char const * s = compiler.getSourceManager().getCharacterData( loc); unsigned n = Lexer::MeasureTokenLength( expr->getLocEnd(), compiler.getSourceManager(), compiler.getLangOpts()); std::string tok { s, n }; if (tok == "sal_False" || tok == "0") { rewritten = replaceText( compiler.getSourceManager().getExpansionLoc( expr->getLocStart()), n, "false"); } else if (tok == "sal_True" || tok == "1") { rewritten = replaceText( compiler.getSourceManager().getExpansionLoc( expr->getLocStart()), n, "true"); } } } if (!rewritten) { report( DiagnosticsEngine::Warning, "implicit conversion (%0) of literal of type %1 to %2", expr2->getLocStart()) << expr->getCastKindName() << expr->getSubExpr()->getType() << expr->getType() << expr2->getSourceRange(); } } else if (sub->isNullPointerConstant( compiler.getASTContext(), Expr::NPC_ValueDependentIsNull) > Expr::NPCK_ZeroExpression) { // The test above originally checked for != Expr::NPCK_NotNull, but in non-C++11 // mode we can get also Expr::NPCK_ZeroExpression inside templates, even though // the expression is actually not a null pointer. Clang bug or C++98 misfeature? // See Clang's NPCK_ZeroExpression declaration and beginning of isNullPointerConstant(). static_assert( Expr::NPCK_NotNull == 0 && Expr::NPCK_ZeroExpression == 1, "Clang API change" ); report( DiagnosticsEngine::Warning, ("implicit conversion (%0) of null pointer constant of type %1 to" " %2"), expr2->getLocStart()) << expr->getCastKindName() << expr->getSubExpr()->getType() << expr->getType() << expr2->getSourceRange(); } else if (!sub->isValueDependent() && sub->isIntegerConstantExpr(res, compiler.getASTContext())) { report( DiagnosticsEngine::Warning, ("implicit conversion (%0) of integer constant expression of type" " %1 with value %2 to %3"), expr2->getLocStart()) << expr->getCastKindName() << expr->getSubExpr()->getType() << res.toString(10) << expr->getType() << expr2->getSourceRange(); } return true; } bool LiteralToBoolConversion::isFromCIncludeFile( SourceLocation spellingLocation) const { return !compat::isInMainFile(compiler.getSourceManager(), spellingLocation) && (StringRef( compiler.getSourceManager().getPresumedLoc(spellingLocation) .getFilename()) .endswith(".h")); } loplugin::Plugin::Registration<LiteralToBoolConversion> X( "literaltoboolconversion", true); } <commit_msg>Improved loplugin:literaltoboolconversion looking into cond. exprs.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. */ #include "clang/Lex/Lexer.h" #include "compat.hxx" #include "plugin.hxx" namespace { class LiteralToBoolConversion: public RecursiveASTVisitor<LiteralToBoolConversion>, public loplugin::RewritePlugin { public: explicit LiteralToBoolConversion(InstantiationData const & data): RewritePlugin(data) {} virtual void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); } bool VisitImplicitCastExpr(ImplicitCastExpr const * expr); private: bool isFromCIncludeFile(SourceLocation spellingLocation) const; void handleImplicitCastSubExpr( ImplicitCastExpr const * castExpr, Expr const * subExpr); }; bool LiteralToBoolConversion::VisitImplicitCastExpr( ImplicitCastExpr const * expr) { if (ignoreLocation(expr)) { return true; } if (!expr->getType()->isBooleanType()) { return true; } handleImplicitCastSubExpr(expr, expr->getSubExpr()); return true; } bool LiteralToBoolConversion::isFromCIncludeFile( SourceLocation spellingLocation) const { return !compat::isInMainFile(compiler.getSourceManager(), spellingLocation) && (StringRef( compiler.getSourceManager().getPresumedLoc(spellingLocation) .getFilename()) .endswith(".h")); } void LiteralToBoolConversion::handleImplicitCastSubExpr( ImplicitCastExpr const * castExpr, Expr const * subExpr) { Expr const * expr2 = subExpr; // track sub-expr with potential parens, to e.g. rewrite all of expanded // // #define sal_False ((sal_Bool)0) // // including the parens subExpr = expr2->IgnoreParenCasts(); for (;;) { BinaryOperator const * op = dyn_cast<BinaryOperator>(subExpr); if (op == nullptr || op->getOpcode() != BO_Comma) { break; } expr2 = op->getRHS(); subExpr = expr2->IgnoreParenCasts(); } if (subExpr->getType()->isBooleanType()) { return; } ConditionalOperator const * op = dyn_cast<ConditionalOperator>(subExpr); if (op != nullptr) { handleImplicitCastSubExpr(castExpr, op->getTrueExpr()); handleImplicitCastSubExpr(castExpr, op->getFalseExpr()); return; } APSInt res; if (!subExpr->isValueDependent() && subExpr->isIntegerConstantExpr(res, compiler.getASTContext()) && res.getLimitedValue() <= 1) { SourceLocation loc { subExpr->getLocStart() }; while (compiler.getSourceManager().isMacroArgExpansion(loc)) { loc = compiler.getSourceManager().getImmediateMacroCallerLoc(loc); } if (compat::isMacroBodyExpansion(compiler, loc)) { StringRef name { Lexer::getImmediateMacroName( loc, compiler.getSourceManager(), compiler.getLangOpts()) }; if (name == "sal_False" || name == "sal_True") { loc = compiler.getSourceManager().getImmediateExpansionRange( loc).first; } if (isFromCIncludeFile( compiler.getSourceManager().getSpellingLoc(loc))) { return; } } } if (isa<StringLiteral>(subExpr)) { SourceLocation loc { subExpr->getLocStart() }; if (compiler.getSourceManager().isMacroArgExpansion(loc) && (Lexer::getImmediateMacroName( loc, compiler.getSourceManager(), compiler.getLangOpts()) == "assert")) { return; } } if (isa<IntegerLiteral>(subExpr) || isa<CharacterLiteral>(subExpr) || isa<FloatingLiteral>(subExpr) || isa<ImaginaryLiteral>(subExpr) || isa<StringLiteral>(subExpr)) { bool rewritten = false; if (rewriter != nullptr) { SourceLocation loc { compiler.getSourceManager().getExpansionLoc( expr2->getLocStart()) }; if (compiler.getSourceManager().getExpansionLoc(expr2->getLocEnd()) == loc) { char const * s = compiler.getSourceManager().getCharacterData( loc); unsigned n = Lexer::MeasureTokenLength( expr2->getLocEnd(), compiler.getSourceManager(), compiler.getLangOpts()); std::string tok { s, n }; if (tok == "sal_False" || tok == "0") { rewritten = replaceText( compiler.getSourceManager().getExpansionLoc( expr2->getLocStart()), n, "false"); } else if (tok == "sal_True" || tok == "1") { rewritten = replaceText( compiler.getSourceManager().getExpansionLoc( expr2->getLocStart()), n, "true"); } } } if (!rewritten) { report( DiagnosticsEngine::Warning, "implicit conversion (%0) of literal of type %1 to %2", expr2->getLocStart()) << castExpr->getCastKindName() << subExpr->getType() << castExpr->getType() << expr2->getSourceRange(); } } else if (subExpr->isNullPointerConstant( compiler.getASTContext(), Expr::NPC_ValueDependentIsNull) > Expr::NPCK_ZeroExpression) { // The test above originally checked for != Expr::NPCK_NotNull, but in non-C++11 // mode we can get also Expr::NPCK_ZeroExpression inside templates, even though // the expression is actually not a null pointer. Clang bug or C++98 misfeature? // See Clang's NPCK_ZeroExpression declaration and beginning of isNullPointerConstant(). static_assert( Expr::NPCK_NotNull == 0 && Expr::NPCK_ZeroExpression == 1, "Clang API change" ); report( DiagnosticsEngine::Warning, ("implicit conversion (%0) of null pointer constant of type %1 to" " %2"), expr2->getLocStart()) << castExpr->getCastKindName() << subExpr->getType() << castExpr->getType() << expr2->getSourceRange(); } else if (!subExpr->isValueDependent() && subExpr->isIntegerConstantExpr(res, compiler.getASTContext())) { report( DiagnosticsEngine::Warning, ("implicit conversion (%0) of integer constant expression of type" " %1 with value %2 to %3"), expr2->getLocStart()) << castExpr->getCastKindName() << subExpr->getType() << res.toString(10) << castExpr->getType() << expr2->getSourceRange(); } } loplugin::Plugin::Registration<LiteralToBoolConversion> X( "literaltoboolconversion", true); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: insrule.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2004-08-23 09:06:51 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #pragma hdrstop #include "uiparam.hxx" #include "hintids.hxx" #ifndef _GALLERY_HXX_ //autogen #include <svx/gallery.hxx> #endif #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SVX_BRSHITEM_HXX //autogen #include <svx/brshitem.hxx> #endif #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #include "swtypes.hxx" #include "docsh.hxx" #include "insrule.hxx" #include "swvset.hxx" #include "insrule.hrc" #include "misc.hrc" #include "helpid.h" /*------------------------------------------------------------------------ Beschreibung: ------------------------------------------------------------------------*/ SwInsertGrfRulerDlg::SwInsertGrfRulerDlg( Window* pParent ) : SfxModalDialog(pParent, SW_RES(DLG_INSERT_RULER)), aSelectionFL(this, ResId(FL_SEL )), pExampleVS (new SwRulerValueSet(this, ResId(VS_EXAMPLE ))), aOkPB (this, ResId(PB_OK )), aCancelPB (this, ResId(PB_CANCEL )), aHelpPB (this, ResId(PB_HELP )), sSimple (ResId(ST_SIMPLE)), nSelPos(USHRT_MAX) { FreeResource(); pExampleVS->SetLineCount(6); pExampleVS->SetColCount(1); pExampleVS->SetSelectHdl(LINK(this, SwInsertGrfRulerDlg, SelectHdl)); pExampleVS->SetDoubleClickHdl(LINK(this, SwInsertGrfRulerDlg, DoubleClickHdl)); pExampleVS->GrabFocus(); // Grafiknamen ermitteln GalleryExplorer::BeginLocking(GALLERY_THEME_RULERS); GalleryExplorer::FillObjList( GALLERY_THEME_RULERS, aGrfNames ); pExampleVS->SetHelpId(HID_VS_RULER); Color aColor(COL_WHITE); pExampleVS->InsertItem( 1, 1); pExampleVS->SetItemText( 1, sSimple); for(USHORT i = 1; i <= aGrfNames.Count(); i++) { pExampleVS->InsertItem( i + 1, i); pExampleVS->SetItemText( i + 1, *((String*)aGrfNames.GetObject(i-1))); } pExampleVS->Show(); } /*-----------------14.02.97 13.18------------------- --------------------------------------------------*/ SwInsertGrfRulerDlg::~SwInsertGrfRulerDlg() { GalleryExplorer::EndLocking(GALLERY_THEME_RULERS); delete pExampleVS; } /*-----------------14.02.97 13.17------------------- --------------------------------------------------*/ String SwInsertGrfRulerDlg::GetGraphicName() { String sRet; USHORT nSel = nSelPos - 2; //align selection position with ValueSet index if(nSel < aGrfNames.Count()) sRet = URIHelper::SmartRelToAbs(*(String*) aGrfNames.GetObject(nSel)); return sRet; } /*-----------------14.02.97 13.20------------------- --------------------------------------------------*/ IMPL_LINK(SwInsertGrfRulerDlg, SelectHdl, ValueSet*, pVS) { nSelPos = pVS->GetSelectItemId(); aOkPB.Enable(); return 0; } /*-----------------14.02.97 14.17------------------- --------------------------------------------------*/ SwRulerValueSet::SwRulerValueSet( Window* pParent, const ResId& rResId ) : SvxBmpNumValueSet(pParent, rResId) { SetStyle( GetStyle() & ~WB_ITEMBORDER ); } /*-----------------14.02.97 14.17------------------- --------------------------------------------------*/ SwRulerValueSet::~SwRulerValueSet() { } /*-----------------14.02.97 13.42------------------- --------------------------------------------------*/ void __EXPORT SwRulerValueSet::UserDraw( const UserDrawEvent& rUDEvt ) { Rectangle aRect = rUDEvt.GetRect(); OutputDevice* pDev = rUDEvt.GetDevice(); USHORT nItemId = rUDEvt.GetItemId(); Point aBLPos = aRect.TopLeft(); // Itemzaehlung beginnt bei 1, und die 1. ist die einfache Linie if(nItemId > 1) { Graphic aGraphic; if(GalleryExplorer::GetGraphicObj( GALLERY_THEME_RULERS, nItemId - 2, &aGraphic)) { Size aGrfSize = aGraphic.GetPrefSize(); if(aGrfSize.Width() && aGrfSize.Height()) { int nRelGrf = aGrfSize.Height() * 100 / aGrfSize.Width(); Size aWinSize = aRect.GetSize(); Size aPaintSize = aWinSize; int nRelWin = aWinSize.Height() * 100 / aWinSize.Width(); if(nRelGrf > nRelWin) { aPaintSize.Width() = aWinSize.Height() * 100 / nRelGrf; aBLPos.X() += (aWinSize.Width() - aPaintSize.Width()) /2; } else { aPaintSize.Height() = aWinSize.Width() * nRelGrf/100; aBLPos.Y() += (aWinSize.Height() - aPaintSize.Height()) /2; } aBLPos.X() -= aPaintSize.Width() /2; aBLPos.Y() -= aPaintSize.Height() /2; aPaintSize.Width() *= 2; aPaintSize.Height() *= 2; if(aPaintSize.Height() < 2) aPaintSize.Height() = 2; Region aRegion = pDev->GetClipRegion(); pDev->SetClipRegion(aRect); aGraphic.Draw(pDev, aBLPos, aPaintSize); pDev->SetClipRegion(aRegion); } } else { SetGrfNotFound(TRUE); } } else { // Text fuer einfache Linie painten Font aOldFont = pDev->GetFont(); Font aFont = pDev->GetFont(); Size aSize = aFont.GetSize(); int nRectHeight = aRect.GetHeight(); aSize.Height() = nRectHeight * 2 / 3; aFont.SetSize(aSize); pDev->SetFont(aFont); String aText(GetItemText(nItemId)); aSize.Width() = pDev->GetTextWidth(aText); aSize.Height() = pDev->GetTextHeight(); Point aPos(aBLPos); aPos.Y() += (nRectHeight - aSize.Height()) / 2; aPos.X() += (aRect.GetWidth() - aSize.Width()) / 2; pDev->DrawText(aPos, aText); pDev->SetFont(aOldFont); } } /*-----------------15.02.97 10.03------------------- --------------------------------------------------*/ IMPL_LINK(SwInsertGrfRulerDlg, DoubleClickHdl, ValueSet*, pVS) { EndDialog(RET_OK); return 0; } <commit_msg>INTEGRATION: CWS sb19 (1.6.480); FILE MERGED 2004/10/29 15:04:01 sb 1.6.480.3: #i110409# Fixed wrong conversions from URIHelper::SmartRelToAbs to URIHelper::SmartRel2Abs. 2004/10/11 14:36:36 sb 1.6.480.2: RESYNC: (1.6-1.7); FILE MERGED 2004/10/07 14:22:14 os 1.6.480.1: #110409# static base URL has gone<commit_after>/************************************************************************* * * $RCSfile: insrule.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-01-11 12:42:48 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #pragma hdrstop #include "uiparam.hxx" #include "hintids.hxx" #ifndef _GALLERY_HXX_ //autogen #include <svx/gallery.hxx> #endif #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SVX_BRSHITEM_HXX //autogen #include <svx/brshitem.hxx> #endif #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #include "swtypes.hxx" #include "docsh.hxx" #include "insrule.hxx" #include "swvset.hxx" #include "insrule.hrc" #include "misc.hrc" #include "helpid.h" /*------------------------------------------------------------------------ Beschreibung: ------------------------------------------------------------------------*/ SwInsertGrfRulerDlg::SwInsertGrfRulerDlg( Window* pParent ) : SfxModalDialog(pParent, SW_RES(DLG_INSERT_RULER)), aSelectionFL(this, ResId(FL_SEL )), pExampleVS (new SwRulerValueSet(this, ResId(VS_EXAMPLE ))), aOkPB (this, ResId(PB_OK )), aCancelPB (this, ResId(PB_CANCEL )), aHelpPB (this, ResId(PB_HELP )), sSimple (ResId(ST_SIMPLE)), nSelPos(USHRT_MAX) { FreeResource(); pExampleVS->SetLineCount(6); pExampleVS->SetColCount(1); pExampleVS->SetSelectHdl(LINK(this, SwInsertGrfRulerDlg, SelectHdl)); pExampleVS->SetDoubleClickHdl(LINK(this, SwInsertGrfRulerDlg, DoubleClickHdl)); pExampleVS->GrabFocus(); // Grafiknamen ermitteln GalleryExplorer::BeginLocking(GALLERY_THEME_RULERS); GalleryExplorer::FillObjList( GALLERY_THEME_RULERS, aGrfNames ); pExampleVS->SetHelpId(HID_VS_RULER); Color aColor(COL_WHITE); pExampleVS->InsertItem( 1, 1); pExampleVS->SetItemText( 1, sSimple); for(USHORT i = 1; i <= aGrfNames.Count(); i++) { pExampleVS->InsertItem( i + 1, i); pExampleVS->SetItemText( i + 1, *((String*)aGrfNames.GetObject(i-1))); } pExampleVS->Show(); } /*-----------------14.02.97 13.18------------------- --------------------------------------------------*/ SwInsertGrfRulerDlg::~SwInsertGrfRulerDlg() { GalleryExplorer::EndLocking(GALLERY_THEME_RULERS); delete pExampleVS; } /*-----------------14.02.97 13.17------------------- --------------------------------------------------*/ String SwInsertGrfRulerDlg::GetGraphicName() { String sRet; USHORT nSel = nSelPos - 2; //align selection position with ValueSet index if(nSel < aGrfNames.Count()) sRet = URIHelper::SmartRel2Abs( INetURLObject(), *(String*) aGrfNames.GetObject(nSel), URIHelper::GetMaybeFileHdl()); return sRet; } /*-----------------14.02.97 13.20------------------- --------------------------------------------------*/ IMPL_LINK(SwInsertGrfRulerDlg, SelectHdl, ValueSet*, pVS) { nSelPos = pVS->GetSelectItemId(); aOkPB.Enable(); return 0; } /*-----------------14.02.97 14.17------------------- --------------------------------------------------*/ SwRulerValueSet::SwRulerValueSet( Window* pParent, const ResId& rResId ) : SvxBmpNumValueSet(pParent, rResId) { SetStyle( GetStyle() & ~WB_ITEMBORDER ); } /*-----------------14.02.97 14.17------------------- --------------------------------------------------*/ SwRulerValueSet::~SwRulerValueSet() { } /*-----------------14.02.97 13.42------------------- --------------------------------------------------*/ void __EXPORT SwRulerValueSet::UserDraw( const UserDrawEvent& rUDEvt ) { Rectangle aRect = rUDEvt.GetRect(); OutputDevice* pDev = rUDEvt.GetDevice(); USHORT nItemId = rUDEvt.GetItemId(); Point aBLPos = aRect.TopLeft(); // Itemzaehlung beginnt bei 1, und die 1. ist die einfache Linie if(nItemId > 1) { Graphic aGraphic; if(GalleryExplorer::GetGraphicObj( GALLERY_THEME_RULERS, nItemId - 2, &aGraphic)) { Size aGrfSize = aGraphic.GetPrefSize(); if(aGrfSize.Width() && aGrfSize.Height()) { int nRelGrf = aGrfSize.Height() * 100 / aGrfSize.Width(); Size aWinSize = aRect.GetSize(); Size aPaintSize = aWinSize; int nRelWin = aWinSize.Height() * 100 / aWinSize.Width(); if(nRelGrf > nRelWin) { aPaintSize.Width() = aWinSize.Height() * 100 / nRelGrf; aBLPos.X() += (aWinSize.Width() - aPaintSize.Width()) /2; } else { aPaintSize.Height() = aWinSize.Width() * nRelGrf/100; aBLPos.Y() += (aWinSize.Height() - aPaintSize.Height()) /2; } aBLPos.X() -= aPaintSize.Width() /2; aBLPos.Y() -= aPaintSize.Height() /2; aPaintSize.Width() *= 2; aPaintSize.Height() *= 2; if(aPaintSize.Height() < 2) aPaintSize.Height() = 2; Region aRegion = pDev->GetClipRegion(); pDev->SetClipRegion(aRect); aGraphic.Draw(pDev, aBLPos, aPaintSize); pDev->SetClipRegion(aRegion); } } else { SetGrfNotFound(TRUE); } } else { // Text fuer einfache Linie painten Font aOldFont = pDev->GetFont(); Font aFont = pDev->GetFont(); Size aSize = aFont.GetSize(); int nRectHeight = aRect.GetHeight(); aSize.Height() = nRectHeight * 2 / 3; aFont.SetSize(aSize); pDev->SetFont(aFont); String aText(GetItemText(nItemId)); aSize.Width() = pDev->GetTextWidth(aText); aSize.Height() = pDev->GetTextHeight(); Point aPos(aBLPos); aPos.Y() += (nRectHeight - aSize.Height()) / 2; aPos.X() += (aRect.GetWidth() - aSize.Width()) / 2; pDev->DrawText(aPos, aText); pDev->SetFont(aOldFont); } } /*-----------------15.02.97 10.03------------------- --------------------------------------------------*/ IMPL_LINK(SwInsertGrfRulerDlg, DoubleClickHdl, ValueSet*, pVS) { EndDialog(RET_OK); return 0; } <|endoftext|>
<commit_before>// Copyright 2013 Google Inc. 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 "version.h" #include <stdlib.h> #include "util.h" const char* kNinjaVersion = "1.6.0.git"; void ParseVersion(const string& version, int* major, int* minor) { size_t end = version.find('.'); *major = atoi(version.substr(0, end).c_str()); *minor = 0; if (end != string::npos) { size_t start = end + 1; end = version.find('.', start); *minor = atoi(version.substr(start, end).c_str()); } } void CheckNinjaVersion(const string& version) { int bin_major, bin_minor; ParseVersion(kNinjaVersion, &bin_major, &bin_minor); int file_major, file_minor; ParseVersion(version, &file_major, &file_minor); if (bin_major > file_major) { Warning("ninja executable version (%s) greater than build file " "ninja_required_version (%s); versions may be incompatible.", kNinjaVersion, version.c_str()); return; } if ((bin_major == file_major && bin_minor < file_minor) || bin_major < file_major) { Fatal("ninja version (%s) incompatible with build file " "ninja_required_version version (%s).", kNinjaVersion, version.c_str()); } } <commit_msg>mark this 1.7.0.git<commit_after>// Copyright 2013 Google Inc. 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 "version.h" #include <stdlib.h> #include "util.h" const char* kNinjaVersion = "1.7.0.git"; void ParseVersion(const string& version, int* major, int* minor) { size_t end = version.find('.'); *major = atoi(version.substr(0, end).c_str()); *minor = 0; if (end != string::npos) { size_t start = end + 1; end = version.find('.', start); *minor = atoi(version.substr(start, end).c_str()); } } void CheckNinjaVersion(const string& version) { int bin_major, bin_minor; ParseVersion(kNinjaVersion, &bin_major, &bin_minor); int file_major, file_minor; ParseVersion(version, &file_major, &file_minor); if (bin_major > file_major) { Warning("ninja executable version (%s) greater than build file " "ninja_required_version (%s); versions may be incompatible.", kNinjaVersion, version.c_str()); return; } if ((bin_major == file_major && bin_minor < file_minor) || bin_major < file_major) { Fatal("ninja version (%s) incompatible with build file " "ninja_required_version version (%s).", kNinjaVersion, version.c_str()); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: staticdbtools_s.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: kz $ $Date: 2006-12-13 16:27:02 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #ifndef CONNECTIVITY_VIRTUAL_DBTOOLS_HXX #include <connectivity/virtualdbtools.hxx> #endif #ifndef CONNECTIVITY_STATIC_DBTOOLS_SIMPLE_HXX #include "staticdbtools_s.hxx" #endif #ifndef _DBHELPER_DBCONVERSION_HXX_ #include <connectivity/dbconversion.hxx> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif #ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_ #include <com/sun/star/sdb/SQLContext.hpp> #endif //........................................................................ namespace connectivity { //........................................................................ using namespace ::com::sun::star::util; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; //================================================================ //= ODataAccessStaticTools //================================================================ //---------------------------------------------------------------- ODataAccessStaticTools::ODataAccessStaticTools() { } //---------------------------------------------------------------- Date ODataAccessStaticTools::getStandardDate() const { return ::dbtools::DBTypeConversion::getStandardDate(); } //---------------------------------------------------------------- double ODataAccessStaticTools::getValue(const Reference< XColumn>& _rxVariant, const Date& rNullDate, sal_Int16 nKeyType) const { return ::dbtools::DBTypeConversion::getValue(_rxVariant, rNullDate, nKeyType); } //---------------------------------------------------------------- ::rtl::OUString ODataAccessStaticTools::getValue(const Reference< XColumn >& _rxColumn, const Reference< XNumberFormatter >& _rxFormatter, const Date& _rNullDate, sal_Int32 _nKey, sal_Int16 _nKeyType) const { return ::dbtools::DBTypeConversion::getValue(_rxColumn, _rxFormatter, _rNullDate, _nKey, _nKeyType); } //---------------------------------------------------------------- ::rtl::OUString ODataAccessStaticTools::getValue( const Reference< XPropertySet>& _rxColumn, const Reference< XNumberFormatter>& _rxFormatter, const Locale& _rLocale, const Date& _rNullDate ) const { return ::dbtools::DBTypeConversion::getValue( _rxColumn, _rxFormatter, _rLocale, _rNullDate ); } //---------------------------------------------------------------- oslInterlockedCount SAL_CALL ODataAccessStaticTools::acquire() { return ORefBase::acquire(); } //---------------------------------------------------------------- oslInterlockedCount SAL_CALL ODataAccessStaticTools::release() { return ORefBase::release(); } //---------------------------------------------------------------- Reference< XConnection> ODataAccessStaticTools::getConnection_withFeedback(const ::rtl::OUString& _rDataSourceName, const ::rtl::OUString& _rUser, const ::rtl::OUString& _rPwd, const Reference< XMultiServiceFactory>& _rxFactory) const SAL_THROW ( (SQLException) ) { return ::dbtools::getConnection_withFeedback(_rDataSourceName, _rUser, _rPwd, _rxFactory); } //---------------------------------------------------------------- Reference< XConnection> ODataAccessStaticTools::connectRowset(const Reference< XRowSet>& _rxRowSet, const Reference< XMultiServiceFactory>& _rxFactory, sal_Bool _bSetAsActiveConnection) const SAL_THROW ( (SQLException, WrappedTargetException, RuntimeException) ) { return ::dbtools::connectRowset( _rxRowSet, _rxFactory, _bSetAsActiveConnection); } // ------------------------------------------------ Reference< XConnection> ODataAccessStaticTools::getRowSetConnection( const Reference< XRowSet>& _rxRowSet) const SAL_THROW ( (RuntimeException) ) { return ::dbtools::getConnection(_rxRowSet); } //---------------------------------------------------------------- Reference< XNumberFormatsSupplier> ODataAccessStaticTools::getNumberFormats(const Reference< XConnection>& _rxConn, sal_Bool _bAllowDefault) const { return ::dbtools::getNumberFormats(_rxConn, _bAllowDefault); } //---------------------------------------------------------------- sal_Int32 ODataAccessStaticTools::getDefaultNumberFormat( const Reference< XPropertySet >& _rxColumn, const Reference< XNumberFormatTypes >& _rxTypes, const Locale& _rLocale ) const { return ::dbtools::getDefaultNumberFormat( _rxColumn, _rxTypes, _rLocale ); } //---------------------------------------------------------------- void ODataAccessStaticTools::TransferFormComponentProperties(const Reference< XPropertySet>& _rxOld, const Reference< XPropertySet>& _rxNew, const Locale& _rLocale) const { ::dbtools::TransferFormComponentProperties(_rxOld, _rxNew, _rLocale); } //---------------------------------------------------------------- ::rtl::OUString ODataAccessStaticTools::quoteName(const ::rtl::OUString& _rQuote, const ::rtl::OUString& _rName) const { return ::dbtools::quoteName(_rQuote, _rName); } //---------------------------------------------------------------- ::rtl::OUString ODataAccessStaticTools::composeTableNameForSelect( const Reference< XConnection >& _rxConnection, const ::rtl::OUString& _rCatalog, const ::rtl::OUString& _rSchema, const ::rtl::OUString& _rName ) const { return ::dbtools::composeTableNameForSelect( _rxConnection, _rCatalog, _rSchema, _rName ); } //---------------------------------------------------------------- ::rtl::OUString ODataAccessStaticTools::composeTableNameForSelect( const Reference< XConnection >& _rxConnection, const Reference< XPropertySet>& _xTable ) const { return ::dbtools::composeTableNameForSelect( _rxConnection, _xTable ); } //---------------------------------------------------------------- SQLContext ODataAccessStaticTools::prependContextInfo(SQLException& _rException, const Reference< XInterface >& _rxContext, const ::rtl::OUString& _rContextDescription, const ::rtl::OUString& _rContextDetails) const { return ::dbtools::prependContextInfo(_rException, _rxContext, _rContextDescription, _rContextDetails); } //---------------------------------------------------------------- Reference< XDataSource > ODataAccessStaticTools::getDataSource( const ::rtl::OUString& _rsRegisteredName, const Reference< XMultiServiceFactory>& _rxFactory ) const { return ::dbtools::getDataSource( _rsRegisteredName, _rxFactory ); } //---------------------------------------------------------------- sal_Bool ODataAccessStaticTools::canInsert(const Reference< XPropertySet>& _rxCursorSet) const { return ::dbtools::canInsert( _rxCursorSet ); } //---------------------------------------------------------------- sal_Bool ODataAccessStaticTools::canUpdate(const Reference< XPropertySet>& _rxCursorSet) const { return ::dbtools::canUpdate( _rxCursorSet ); } //---------------------------------------------------------------- sal_Bool ODataAccessStaticTools::canDelete(const Reference< XPropertySet>& _rxCursorSet) const { return ::dbtools::canDelete( _rxCursorSet ); } //---------------------------------------------------------------- Reference< XNameAccess > ODataAccessStaticTools::getFieldsByCommandDescriptor( const Reference< XConnection >& _rxConnection, const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand, Reference< XComponent >& _rxKeepFieldsAlive, ::dbtools::SQLExceptionInfo* _pErrorInfo ) SAL_THROW( ( ) ) { return ::dbtools::getFieldsByCommandDescriptor( _rxConnection, _nCommandType, _rCommand, _rxKeepFieldsAlive, _pErrorInfo ); } //---------------------------------------------------------------- Sequence< ::rtl::OUString > ODataAccessStaticTools::getFieldNamesByCommandDescriptor( const Reference< XConnection >& _rxConnection, const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand, ::dbtools::SQLExceptionInfo* _pErrorInfo ) SAL_THROW( ( ) ) { return ::dbtools::getFieldNamesByCommandDescriptor( _rxConnection, _nCommandType, _rCommand, _pErrorInfo ); } // ------------------------------------------------ bool ODataAccessStaticTools::isEmbeddedInDatabase( const Reference< XInterface >& _rxComponent, Reference< XConnection >& _rxActualConnection ) { return ::dbtools::isEmbeddedInDatabase( _rxComponent, _rxActualConnection ); } //........................................................................ } // namespace connectivity //........................................................................ <commit_msg>INTEGRATION: CWS changefileheader (1.12.180); FILE MERGED 2008/04/01 10:53:49 thb 1.12.180.2: #i85898# Stripping all external header guards 2008/03/28 15:24:41 rt 1.12.180.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: staticdbtools_s.cxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include <connectivity/virtualdbtools.hxx> #include "staticdbtools_s.hxx" #include <connectivity/dbconversion.hxx> #include <connectivity/dbtools.hxx> #include <com/sun/star/sdb/SQLContext.hpp> //........................................................................ namespace connectivity { //........................................................................ using namespace ::com::sun::star::util; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; //================================================================ //= ODataAccessStaticTools //================================================================ //---------------------------------------------------------------- ODataAccessStaticTools::ODataAccessStaticTools() { } //---------------------------------------------------------------- Date ODataAccessStaticTools::getStandardDate() const { return ::dbtools::DBTypeConversion::getStandardDate(); } //---------------------------------------------------------------- double ODataAccessStaticTools::getValue(const Reference< XColumn>& _rxVariant, const Date& rNullDate, sal_Int16 nKeyType) const { return ::dbtools::DBTypeConversion::getValue(_rxVariant, rNullDate, nKeyType); } //---------------------------------------------------------------- ::rtl::OUString ODataAccessStaticTools::getValue(const Reference< XColumn >& _rxColumn, const Reference< XNumberFormatter >& _rxFormatter, const Date& _rNullDate, sal_Int32 _nKey, sal_Int16 _nKeyType) const { return ::dbtools::DBTypeConversion::getValue(_rxColumn, _rxFormatter, _rNullDate, _nKey, _nKeyType); } //---------------------------------------------------------------- ::rtl::OUString ODataAccessStaticTools::getValue( const Reference< XPropertySet>& _rxColumn, const Reference< XNumberFormatter>& _rxFormatter, const Locale& _rLocale, const Date& _rNullDate ) const { return ::dbtools::DBTypeConversion::getValue( _rxColumn, _rxFormatter, _rLocale, _rNullDate ); } //---------------------------------------------------------------- oslInterlockedCount SAL_CALL ODataAccessStaticTools::acquire() { return ORefBase::acquire(); } //---------------------------------------------------------------- oslInterlockedCount SAL_CALL ODataAccessStaticTools::release() { return ORefBase::release(); } //---------------------------------------------------------------- Reference< XConnection> ODataAccessStaticTools::getConnection_withFeedback(const ::rtl::OUString& _rDataSourceName, const ::rtl::OUString& _rUser, const ::rtl::OUString& _rPwd, const Reference< XMultiServiceFactory>& _rxFactory) const SAL_THROW ( (SQLException) ) { return ::dbtools::getConnection_withFeedback(_rDataSourceName, _rUser, _rPwd, _rxFactory); } //---------------------------------------------------------------- Reference< XConnection> ODataAccessStaticTools::connectRowset(const Reference< XRowSet>& _rxRowSet, const Reference< XMultiServiceFactory>& _rxFactory, sal_Bool _bSetAsActiveConnection) const SAL_THROW ( (SQLException, WrappedTargetException, RuntimeException) ) { return ::dbtools::connectRowset( _rxRowSet, _rxFactory, _bSetAsActiveConnection); } // ------------------------------------------------ Reference< XConnection> ODataAccessStaticTools::getRowSetConnection( const Reference< XRowSet>& _rxRowSet) const SAL_THROW ( (RuntimeException) ) { return ::dbtools::getConnection(_rxRowSet); } //---------------------------------------------------------------- Reference< XNumberFormatsSupplier> ODataAccessStaticTools::getNumberFormats(const Reference< XConnection>& _rxConn, sal_Bool _bAllowDefault) const { return ::dbtools::getNumberFormats(_rxConn, _bAllowDefault); } //---------------------------------------------------------------- sal_Int32 ODataAccessStaticTools::getDefaultNumberFormat( const Reference< XPropertySet >& _rxColumn, const Reference< XNumberFormatTypes >& _rxTypes, const Locale& _rLocale ) const { return ::dbtools::getDefaultNumberFormat( _rxColumn, _rxTypes, _rLocale ); } //---------------------------------------------------------------- void ODataAccessStaticTools::TransferFormComponentProperties(const Reference< XPropertySet>& _rxOld, const Reference< XPropertySet>& _rxNew, const Locale& _rLocale) const { ::dbtools::TransferFormComponentProperties(_rxOld, _rxNew, _rLocale); } //---------------------------------------------------------------- ::rtl::OUString ODataAccessStaticTools::quoteName(const ::rtl::OUString& _rQuote, const ::rtl::OUString& _rName) const { return ::dbtools::quoteName(_rQuote, _rName); } //---------------------------------------------------------------- ::rtl::OUString ODataAccessStaticTools::composeTableNameForSelect( const Reference< XConnection >& _rxConnection, const ::rtl::OUString& _rCatalog, const ::rtl::OUString& _rSchema, const ::rtl::OUString& _rName ) const { return ::dbtools::composeTableNameForSelect( _rxConnection, _rCatalog, _rSchema, _rName ); } //---------------------------------------------------------------- ::rtl::OUString ODataAccessStaticTools::composeTableNameForSelect( const Reference< XConnection >& _rxConnection, const Reference< XPropertySet>& _xTable ) const { return ::dbtools::composeTableNameForSelect( _rxConnection, _xTable ); } //---------------------------------------------------------------- SQLContext ODataAccessStaticTools::prependContextInfo(SQLException& _rException, const Reference< XInterface >& _rxContext, const ::rtl::OUString& _rContextDescription, const ::rtl::OUString& _rContextDetails) const { return ::dbtools::prependContextInfo(_rException, _rxContext, _rContextDescription, _rContextDetails); } //---------------------------------------------------------------- Reference< XDataSource > ODataAccessStaticTools::getDataSource( const ::rtl::OUString& _rsRegisteredName, const Reference< XMultiServiceFactory>& _rxFactory ) const { return ::dbtools::getDataSource( _rsRegisteredName, _rxFactory ); } //---------------------------------------------------------------- sal_Bool ODataAccessStaticTools::canInsert(const Reference< XPropertySet>& _rxCursorSet) const { return ::dbtools::canInsert( _rxCursorSet ); } //---------------------------------------------------------------- sal_Bool ODataAccessStaticTools::canUpdate(const Reference< XPropertySet>& _rxCursorSet) const { return ::dbtools::canUpdate( _rxCursorSet ); } //---------------------------------------------------------------- sal_Bool ODataAccessStaticTools::canDelete(const Reference< XPropertySet>& _rxCursorSet) const { return ::dbtools::canDelete( _rxCursorSet ); } //---------------------------------------------------------------- Reference< XNameAccess > ODataAccessStaticTools::getFieldsByCommandDescriptor( const Reference< XConnection >& _rxConnection, const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand, Reference< XComponent >& _rxKeepFieldsAlive, ::dbtools::SQLExceptionInfo* _pErrorInfo ) SAL_THROW( ( ) ) { return ::dbtools::getFieldsByCommandDescriptor( _rxConnection, _nCommandType, _rCommand, _rxKeepFieldsAlive, _pErrorInfo ); } //---------------------------------------------------------------- Sequence< ::rtl::OUString > ODataAccessStaticTools::getFieldNamesByCommandDescriptor( const Reference< XConnection >& _rxConnection, const sal_Int32 _nCommandType, const ::rtl::OUString& _rCommand, ::dbtools::SQLExceptionInfo* _pErrorInfo ) SAL_THROW( ( ) ) { return ::dbtools::getFieldNamesByCommandDescriptor( _rxConnection, _nCommandType, _rCommand, _pErrorInfo ); } // ------------------------------------------------ bool ODataAccessStaticTools::isEmbeddedInDatabase( const Reference< XInterface >& _rxComponent, Reference< XConnection >& _rxActualConnection ) { return ::dbtools::isEmbeddedInDatabase( _rxComponent, _rxActualConnection ); } //........................................................................ } // namespace connectivity //........................................................................ <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <nan.h> #include <gfcpp/GemfireCppCache.hpp> #include "v8_object_formatter.hpp" #include "NodeCacheListener.hpp" #include <sstream> #include "event.hpp" using namespace v8; using namespace gemfire; CachePtr cachePtr; RegionPtr regionPtr; Persistent<Object> callbacks; uv_mutex_t * eventMutex; bool cacheListenerSet = false; CacheablePtr gemfireValueFromV8(Handle<Value> v8Value) { CacheablePtr gemfireValuePtr; if(v8Value->IsString()) { gemfireValuePtr = CacheableString::create(*String::Utf8Value(v8Value)); } else if(v8Value->IsBoolean()) { gemfireValuePtr = CacheableBoolean::create(v8Value->ToBoolean()->Value()); } else if(v8Value->IsNumber()) { gemfireValuePtr = CacheableDouble::create(v8Value->ToNumber()->Value()); } else if(v8Value->IsDate()) { long millisecondsSinceEpoch = Date::Cast(*v8Value)->NumberValue(); timeval timeSinceEpoch; timeSinceEpoch.tv_sec = millisecondsSinceEpoch / 1000; timeSinceEpoch.tv_usec = (millisecondsSinceEpoch % 1000) * 1000; gemfireValuePtr = CacheableDate::create(timeSinceEpoch); } else if(v8Value->IsObject()) { gemfireValuePtr = V8ObjectFormatter::toPdxInstance(regionPtr->getCache(), v8Value->ToObject()); } else if(v8Value->IsNull()) { gemfireValuePtr = CacheableUndefined::create(); } else { gemfireValuePtr = NULLPTR; } return gemfireValuePtr; }; Handle<Value> v8ValueFromGemfire(CacheablePtr valuePtr) { NanScope(); if(valuePtr == NULLPTR) { NanReturnUndefined(); } int typeId = valuePtr->typeId(); if(typeId == GemfireTypeIds::CacheableASCIIString) { NanReturnValue(NanNew<String>(((CacheableStringPtr) valuePtr)->asChar())); } if(typeId == GemfireTypeIds::CacheableBoolean) { NanReturnValue(NanNew<Boolean>(((CacheableBooleanPtr) valuePtr)->value())); } if(typeId == GemfireTypeIds::CacheableDouble) { NanReturnValue(NanNew<Number>(((CacheableDoublePtr) valuePtr)->value())); } if(typeId == GemfireTypeIds::CacheableDate) { NanReturnValue(NanNew<Date>((double) ((CacheableDatePtr) valuePtr)->milliseconds())); } if(typeId == GemfireTypeIds::CacheableUndefined) { NanReturnNull(); } else if(typeId > GemfireTypeIds::CacheableStringHuge) { //We are assuming these are Pdx NanReturnValue(V8ObjectFormatter::fromPdxInstance(valuePtr)); } else { std::stringstream errorMessageStream; errorMessageStream << "Unknown typeId: " << typeId; NanThrowError(errorMessageStream.str().c_str()); NanReturnUndefined(); } } static void callPutCallbacks(event * incomingEvent) { const char * key = incomingEvent->key; const char * newValue = incomingEvent->value; NanScope(); Local<Value> putCallbacksValue = callbacks->Get(NanNew<String>("put")); Local<Array> putCallbacks = Local<Array>::Cast(putCallbacksValue); for (unsigned int i = 0; i < putCallbacks->Length(); i++) { Local<Value> functionValue = putCallbacks->Get(i); Local<Function> putCallback = Local<Function>::Cast(functionValue); static const int argc = 2; Local<Value> argv[] = { NanNew<String>(key), NanNew<String>(newValue) }; Local<Context> ctx = NanGetCurrentContext(); NanMakeCallback(ctx->Global(), putCallback, argc, argv); } } static void doWork(uv_async_t * async, int status) { uv_mutex_lock(eventMutex); event * incomingEvent = (event *) async->data; callPutCallbacks(incomingEvent); uv_mutex_unlock(eventMutex); } static void setCacheListener() { if(!cacheListenerSet) { uv_async_t * async = new uv_async_t(); async->data = new event; uv_async_init(uv_default_loop(), async, doWork); eventMutex = new uv_mutex_t(); uv_mutex_init(eventMutex); NodeCacheListener * nodeCacheListener = new NodeCacheListener(async, eventMutex); AttributesMutatorPtr attrMutatorPtr = regionPtr->getAttributesMutator(); attrMutatorPtr->setCacheListener(CacheListenerPtr(nodeCacheListener)); cacheListenerSet = true; } } NAN_METHOD(version) { NanScope(); NanReturnValue(NanNew<String>(CacheFactory::getVersion())); } NAN_METHOD(put) { NanScope(); if(args.Length() != 2) { NanThrowError("put must be called with a key and a value"); NanReturnUndefined(); } String::Utf8Value key(args[0]->ToString()); CacheableKeyPtr keyPtr = CacheableString::create(*key); CacheablePtr valuePtr = gemfireValueFromV8(args[1]); if(valuePtr == NULLPTR) { std::stringstream errorMessageStream; errorMessageStream << "Unable to put value " << *String::Utf8Value(args[1]->ToDetailString()); NanThrowError(errorMessageStream.str().c_str()); NanReturnUndefined(); } regionPtr->put(keyPtr, valuePtr); NanReturnValue(args[1]); } NAN_METHOD(get) { NanScope(); String::Utf8Value key(args[0]->ToString()); CacheableKeyPtr keyPtr = CacheableString::create(*key); CacheablePtr valuePtr = regionPtr->get(keyPtr); NanReturnValue(v8ValueFromGemfire(valuePtr)); } NAN_METHOD(clear) { NanScope(); regionPtr->clear(); NanReturnValue(NanTrue()); } NAN_METHOD(onPut) { setCacheListener(); NanScope(); Local<Function> callback = Local<Function>::Cast(args[0]); Local<Array> putCallbacks = Local<Array>::Cast(callbacks->Get(NanNew<String>("put"))); putCallbacks->Set(putCallbacks->Length(), callback); NanReturnValue(NanNew<Boolean>(true)); } NAN_METHOD(executeQuery) { NanScope(); String::Utf8Value queryString(args[0]); QueryServicePtr queryServicePtr = cachePtr->getQueryService(); QueryPtr queryPtr = queryServicePtr->newQuery(*queryString); SelectResultsPtr resultsPtr; try { resultsPtr = queryPtr->execute(); } catch(const QueryException & exception) { NanThrowError(exception.getMessage()); NanReturnUndefined(); } Local<Array> array = NanNew<Array>(); SelectResultsIterator iterator = resultsPtr->getIterator(); while (iterator.hasNext()) { const SerializablePtr result = iterator.next(); Handle<Value> v8Value = v8ValueFromGemfire(result); array->Set(array->Length(), v8Value); } NanReturnValue(array); } NAN_METHOD(close) { NanScope(); cachePtr->close(); NanReturnValue(NanTrue()); } NAN_METHOD(registerAllKeys) { NanScope(); regionPtr->registerAllKeys(); NanReturnValue(NanTrue()); } NAN_METHOD(unregisterAllKeys) { NanScope(); regionPtr->unregisterAllKeys(); NanReturnValue(NanTrue()); } static void Initialize(Handle<Object> exports) { NanScope(); Local<Object> callbacksObj = NanNew<Object>(); callbacksObj->Set(NanNew<String>("put"), NanNew<Array>()); NanAssignPersistent(callbacks, callbacksObj); CacheFactoryPtr cacheFactory = CacheFactory::createCacheFactory(); cachePtr = cacheFactory ->setPdxReadSerialized(true) ->set("log-level", "warning") ->set("cache-xml-file", "benchmark/xml/BenchmarkClient.xml") ->create(); regionPtr = cachePtr->getRegion("exampleRegion"); NODE_SET_METHOD(exports, "version", version); NODE_SET_METHOD(exports, "put", put); NODE_SET_METHOD(exports, "get", get); NODE_SET_METHOD(exports, "onPut", onPut); NODE_SET_METHOD(exports, "close", close); NODE_SET_METHOD(exports, "clear", clear); NODE_SET_METHOD(exports, "registerAllKeys", registerAllKeys); NODE_SET_METHOD(exports, "unregisterAllKeys", unregisterAllKeys); NODE_SET_METHOD(exports, "executeQuery", executeQuery); } NODE_MODULE(pivotal_gemfire, Initialize) <commit_msg>Remove unnecessary ToString calls<commit_after>#include <v8.h> #include <node.h> #include <nan.h> #include <gfcpp/GemfireCppCache.hpp> #include "v8_object_formatter.hpp" #include "NodeCacheListener.hpp" #include <sstream> #include "event.hpp" using namespace v8; using namespace gemfire; CachePtr cachePtr; RegionPtr regionPtr; Persistent<Object> callbacks; uv_mutex_t * eventMutex; bool cacheListenerSet = false; CacheablePtr gemfireValueFromV8(Handle<Value> v8Value) { CacheablePtr gemfireValuePtr; if(v8Value->IsString()) { gemfireValuePtr = CacheableString::create(*String::Utf8Value(v8Value)); } else if(v8Value->IsBoolean()) { gemfireValuePtr = CacheableBoolean::create(v8Value->ToBoolean()->Value()); } else if(v8Value->IsNumber()) { gemfireValuePtr = CacheableDouble::create(v8Value->ToNumber()->Value()); } else if(v8Value->IsDate()) { long millisecondsSinceEpoch = Date::Cast(*v8Value)->NumberValue(); timeval timeSinceEpoch; timeSinceEpoch.tv_sec = millisecondsSinceEpoch / 1000; timeSinceEpoch.tv_usec = (millisecondsSinceEpoch % 1000) * 1000; gemfireValuePtr = CacheableDate::create(timeSinceEpoch); } else if(v8Value->IsObject()) { gemfireValuePtr = V8ObjectFormatter::toPdxInstance(regionPtr->getCache(), v8Value->ToObject()); } else if(v8Value->IsNull()) { gemfireValuePtr = CacheableUndefined::create(); } else { gemfireValuePtr = NULLPTR; } return gemfireValuePtr; }; Handle<Value> v8ValueFromGemfire(CacheablePtr valuePtr) { NanScope(); if(valuePtr == NULLPTR) { NanReturnUndefined(); } int typeId = valuePtr->typeId(); if(typeId == GemfireTypeIds::CacheableASCIIString) { NanReturnValue(NanNew<String>(((CacheableStringPtr) valuePtr)->asChar())); } if(typeId == GemfireTypeIds::CacheableBoolean) { NanReturnValue(NanNew<Boolean>(((CacheableBooleanPtr) valuePtr)->value())); } if(typeId == GemfireTypeIds::CacheableDouble) { NanReturnValue(NanNew<Number>(((CacheableDoublePtr) valuePtr)->value())); } if(typeId == GemfireTypeIds::CacheableDate) { NanReturnValue(NanNew<Date>((double) ((CacheableDatePtr) valuePtr)->milliseconds())); } if(typeId == GemfireTypeIds::CacheableUndefined) { NanReturnNull(); } else if(typeId > GemfireTypeIds::CacheableStringHuge) { //We are assuming these are Pdx NanReturnValue(V8ObjectFormatter::fromPdxInstance(valuePtr)); } else { std::stringstream errorMessageStream; errorMessageStream << "Unknown typeId: " << typeId; NanThrowError(errorMessageStream.str().c_str()); NanReturnUndefined(); } } static void callPutCallbacks(event * incomingEvent) { const char * key = incomingEvent->key; const char * newValue = incomingEvent->value; NanScope(); Local<Value> putCallbacksValue = callbacks->Get(NanNew<String>("put")); Local<Array> putCallbacks = Local<Array>::Cast(putCallbacksValue); for (unsigned int i = 0; i < putCallbacks->Length(); i++) { Local<Value> functionValue = putCallbacks->Get(i); Local<Function> putCallback = Local<Function>::Cast(functionValue); static const int argc = 2; Local<Value> argv[] = { NanNew<String>(key), NanNew<String>(newValue) }; Local<Context> ctx = NanGetCurrentContext(); NanMakeCallback(ctx->Global(), putCallback, argc, argv); } } static void doWork(uv_async_t * async, int status) { uv_mutex_lock(eventMutex); event * incomingEvent = (event *) async->data; callPutCallbacks(incomingEvent); uv_mutex_unlock(eventMutex); } static void setCacheListener() { if(!cacheListenerSet) { uv_async_t * async = new uv_async_t(); async->data = new event; uv_async_init(uv_default_loop(), async, doWork); eventMutex = new uv_mutex_t(); uv_mutex_init(eventMutex); NodeCacheListener * nodeCacheListener = new NodeCacheListener(async, eventMutex); AttributesMutatorPtr attrMutatorPtr = regionPtr->getAttributesMutator(); attrMutatorPtr->setCacheListener(CacheListenerPtr(nodeCacheListener)); cacheListenerSet = true; } } NAN_METHOD(version) { NanScope(); NanReturnValue(NanNew<String>(CacheFactory::getVersion())); } NAN_METHOD(put) { NanScope(); if(args.Length() != 2) { NanThrowError("put must be called with a key and a value"); NanReturnUndefined(); } String::Utf8Value key(args[0]); CacheableKeyPtr keyPtr = CacheableString::create(*key); CacheablePtr valuePtr = gemfireValueFromV8(args[1]); if(valuePtr == NULLPTR) { std::stringstream errorMessageStream; errorMessageStream << "Unable to put value " << *String::Utf8Value(args[1]->ToDetailString()); NanThrowError(errorMessageStream.str().c_str()); NanReturnUndefined(); } regionPtr->put(keyPtr, valuePtr); NanReturnValue(args[1]); } NAN_METHOD(get) { NanScope(); String::Utf8Value key(args[0]); CacheableKeyPtr keyPtr = CacheableString::create(*key); CacheablePtr valuePtr = regionPtr->get(keyPtr); NanReturnValue(v8ValueFromGemfire(valuePtr)); } NAN_METHOD(clear) { NanScope(); regionPtr->clear(); NanReturnValue(NanTrue()); } NAN_METHOD(onPut) { setCacheListener(); NanScope(); Local<Function> callback = Local<Function>::Cast(args[0]); Local<Array> putCallbacks = Local<Array>::Cast(callbacks->Get(NanNew<String>("put"))); putCallbacks->Set(putCallbacks->Length(), callback); NanReturnValue(NanNew<Boolean>(true)); } NAN_METHOD(executeQuery) { NanScope(); String::Utf8Value queryString(args[0]); QueryServicePtr queryServicePtr = cachePtr->getQueryService(); QueryPtr queryPtr = queryServicePtr->newQuery(*queryString); SelectResultsPtr resultsPtr; try { resultsPtr = queryPtr->execute(); } catch(const QueryException & exception) { NanThrowError(exception.getMessage()); NanReturnUndefined(); } Local<Array> array = NanNew<Array>(); SelectResultsIterator iterator = resultsPtr->getIterator(); while (iterator.hasNext()) { const SerializablePtr result = iterator.next(); Handle<Value> v8Value = v8ValueFromGemfire(result); array->Set(array->Length(), v8Value); } NanReturnValue(array); } NAN_METHOD(close) { NanScope(); cachePtr->close(); NanReturnValue(NanTrue()); } NAN_METHOD(registerAllKeys) { NanScope(); regionPtr->registerAllKeys(); NanReturnValue(NanTrue()); } NAN_METHOD(unregisterAllKeys) { NanScope(); regionPtr->unregisterAllKeys(); NanReturnValue(NanTrue()); } static void Initialize(Handle<Object> exports) { NanScope(); Local<Object> callbacksObj = NanNew<Object>(); callbacksObj->Set(NanNew<String>("put"), NanNew<Array>()); NanAssignPersistent(callbacks, callbacksObj); CacheFactoryPtr cacheFactory = CacheFactory::createCacheFactory(); cachePtr = cacheFactory ->setPdxReadSerialized(true) ->set("log-level", "warning") ->set("cache-xml-file", "benchmark/xml/BenchmarkClient.xml") ->create(); regionPtr = cachePtr->getRegion("exampleRegion"); NODE_SET_METHOD(exports, "version", version); NODE_SET_METHOD(exports, "put", put); NODE_SET_METHOD(exports, "get", get); NODE_SET_METHOD(exports, "onPut", onPut); NODE_SET_METHOD(exports, "close", close); NODE_SET_METHOD(exports, "clear", clear); NODE_SET_METHOD(exports, "registerAllKeys", registerAllKeys); NODE_SET_METHOD(exports, "unregisterAllKeys", unregisterAllKeys); NODE_SET_METHOD(exports, "executeQuery", executeQuery); } NODE_MODULE(pivotal_gemfire, Initialize) <|endoftext|>
<commit_before>/* * Smithsonian Astrophysical Observatory, Cambridge, MA, USA * This code has been modified under the terms listed below and is made * available under the same terms. */ /* * Copyright 1997-2008 George A Howlett. * * 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 <tclInt.h> #include "bltNsUtil.h" using namespace Blt; Tcl_Namespace* Blt::GetCommandNamespace(Tcl_Command cmdToken) { Command* cmdPtr = (Command*)cmdToken; return (Tcl_Namespace *)cmdPtr->nsPtr; } int Blt::ParseObjectName(Tcl_Interp* interp, const char *path, Blt_ObjectName *namePtr, unsigned int flags) { namePtr->nsPtr = NULL; namePtr->name = NULL; char* colon = NULL; /* Find the last namespace separator in the qualified name. */ char* last = (char *)(path + strlen(path)); while (--last > path) { if ((*last == ':') && (*(last - 1) == ':')) { last++; /* just after the last "::" */ colon = last - 2; break; } } if (colon == NULL) { namePtr->name = path; if ((flags & BLT_NO_DEFAULT_NS) == 0) { namePtr->nsPtr = Tcl_GetCurrentNamespace(interp); } return 1; /* No namespace designated in name. */ } /* Separate the namespace and the object name. */ *colon = '\0'; if (path[0] == '\0') { namePtr->nsPtr = Tcl_GetGlobalNamespace(interp); } else { namePtr->nsPtr = Tcl_FindNamespace(interp, (char *)path, NULL, (flags & BLT_NO_ERROR_MSG) ? 0 : TCL_LEAVE_ERR_MSG); } /* Repair the string. */ *colon = ':'; if (namePtr->nsPtr == NULL) { return 0; /* Namespace doesn't exist. */ } namePtr->name =last; return 1; } char* Blt::MakeQualifiedName(Blt_ObjectName *namePtr, Tcl_DString *resultPtr) { Tcl_DStringInit(resultPtr); if ((namePtr->nsPtr->fullName[0] != ':') || (namePtr->nsPtr->fullName[1] != ':') || (namePtr->nsPtr->fullName[2] != '\0')) { Tcl_DStringAppend(resultPtr, namePtr->nsPtr->fullName, -1); } Tcl_DStringAppend(resultPtr, "::", -1); Tcl_DStringAppend(resultPtr, (char *)namePtr->name, -1); return Tcl_DStringValue(resultPtr); } static Tcl_Namespace* NamespaceOfVariable(Var *varPtr) { if (varPtr->flags & VAR_IN_HASHTABLE) { VarInHash *vhashPtr = (VarInHash *)varPtr; TclVarHashTable *vtablePtr; vtablePtr = (TclVarHashTable *)vhashPtr->entry.tablePtr; return (Tcl_Namespace*)(vtablePtr->nsPtr); } return NULL; } Tcl_Namespace* Blt::GetVariableNamespace(Tcl_Interp* interp, const char *path) { Blt_ObjectName objName; if (!ParseObjectName(interp, path, &objName, BLT_NO_DEFAULT_NS)) return NULL; if (objName.nsPtr == NULL) { Var*varPtr = (Var*)Tcl_FindNamespaceVar(interp, (char *)path, (Tcl_Namespace *)NULL, TCL_GLOBAL_ONLY); if (varPtr) return NamespaceOfVariable(varPtr); } return objName.nsPtr; } <commit_msg>*** empty log message ***<commit_after>/* * Smithsonian Astrophysical Observatory, Cambridge, MA, USA * This code has been modified under the terms listed below and is made * available under the same terms. */ /* * Copyright 1997-2008 George A Howlett. * * 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. */ #ifdef __CYGWIN__ extern "C" { #include <tclInt.h> } #else #include <tclInt.h> #endif #include "bltNsUtil.h" using namespace Blt; Tcl_Namespace* Blt::GetCommandNamespace(Tcl_Command cmdToken) { Command* cmdPtr = (Command*)cmdToken; return (Tcl_Namespace *)cmdPtr->nsPtr; } int Blt::ParseObjectName(Tcl_Interp* interp, const char *path, Blt_ObjectName *namePtr, unsigned int flags) { namePtr->nsPtr = NULL; namePtr->name = NULL; char* colon = NULL; /* Find the last namespace separator in the qualified name. */ char* last = (char *)(path + strlen(path)); while (--last > path) { if ((*last == ':') && (*(last - 1) == ':')) { last++; /* just after the last "::" */ colon = last - 2; break; } } if (colon == NULL) { namePtr->name = path; if ((flags & BLT_NO_DEFAULT_NS) == 0) { namePtr->nsPtr = Tcl_GetCurrentNamespace(interp); } return 1; /* No namespace designated in name. */ } /* Separate the namespace and the object name. */ *colon = '\0'; if (path[0] == '\0') { namePtr->nsPtr = Tcl_GetGlobalNamespace(interp); } else { namePtr->nsPtr = Tcl_FindNamespace(interp, (char *)path, NULL, (flags & BLT_NO_ERROR_MSG) ? 0 : TCL_LEAVE_ERR_MSG); } /* Repair the string. */ *colon = ':'; if (namePtr->nsPtr == NULL) { return 0; /* Namespace doesn't exist. */ } namePtr->name =last; return 1; } char* Blt::MakeQualifiedName(Blt_ObjectName *namePtr, Tcl_DString *resultPtr) { Tcl_DStringInit(resultPtr); if ((namePtr->nsPtr->fullName[0] != ':') || (namePtr->nsPtr->fullName[1] != ':') || (namePtr->nsPtr->fullName[2] != '\0')) { Tcl_DStringAppend(resultPtr, namePtr->nsPtr->fullName, -1); } Tcl_DStringAppend(resultPtr, "::", -1); Tcl_DStringAppend(resultPtr, (char *)namePtr->name, -1); return Tcl_DStringValue(resultPtr); } static Tcl_Namespace* NamespaceOfVariable(Var *varPtr) { if (varPtr->flags & VAR_IN_HASHTABLE) { VarInHash *vhashPtr = (VarInHash *)varPtr; TclVarHashTable *vtablePtr; vtablePtr = (TclVarHashTable *)vhashPtr->entry.tablePtr; return (Tcl_Namespace*)(vtablePtr->nsPtr); } return NULL; } Tcl_Namespace* Blt::GetVariableNamespace(Tcl_Interp* interp, const char *path) { Blt_ObjectName objName; if (!ParseObjectName(interp, path, &objName, BLT_NO_DEFAULT_NS)) return NULL; if (objName.nsPtr == NULL) { Var*varPtr = (Var*)Tcl_FindNamespaceVar(interp, (char *)path, (Tcl_Namespace *)NULL, TCL_GLOBAL_ONLY); if (varPtr) return NamespaceOfVariable(varPtr); } return objName.nsPtr; } <|endoftext|>
<commit_before>#pragma once #include "fly/types/string/detail/string_traits.hpp" #include "fly/types/string/detail/string_unicode.hpp" #include "fly/types/string/string_literal.hpp" #include <cctype> #include <cmath> #include <cstdint> #include <ios> #include <locale> #include <type_traits> namespace fly::detail { /** * Helper struct to stream generic values into a std::basic_ostream. * * For std::string and std::wstring, the "normal" stream types are used (std::ostream and * std::wostream, and their children, respectively). * * For std::u8string, std::u16string, and std::u32string, the STL does not provide stream types. For * a general solution, std::ostream is used, and any string value is converted to UTF-8. * * @author Timothy Flynn ([email protected]) * @version March 21, 2019 */ template <typename StringType> struct BasicStringStreamer { using traits = BasicStringTraits<StringType>; using ostream_type = typename traits::ostream_type; using streamed_type = typename traits::streamed_type; using streamed_char_type = typename traits::streamed_char_type; /** * Stream the given value into the given stream. * * For all string-like types, if the type corresponds to the stream type, then the string is * streamed as-is. Other string-like types are converted to the Unicode encoding used by the * stream type. * * For all character types, the character is case to the character type used by the stream type. * * For any other type which has an operator<< overload defined, the value is streamed using that * overload. * * All other types are dropped. * * @tparam T The type of the value to stream. * @tparam PreferredPresentationType If given, the type T will be cast to this type. * * @param stream The stream to insert the value into. * @param value The value to stream. */ template <typename T, typename PreferredPresentationType = T> static void stream_value(ostream_type &stream, T &&value); /** * Stream a string-like value into the given stream. If the type corresponds to the stream type, * then the string is streamed as-is. Other string-like types are converted to the Unicode * encoding used by the stream type. * * @tparam T The type of the string-like value to stream. * * @param stream The stream to insert the value into. * @param value The string-like value to stream. * @param max_string_length The maximum number of characters from the string to stream. */ template <typename T> static void stream_string(ostream_type &stream, T &&value, std::size_t max_string_length); }; /** * RAII helper class to make formatting modifications to a stream and ensure those modifications * are reset upon destruction. * * @author Timothy Flynn ([email protected]) * @version January 3, 2021 */ template <typename StringType> class BasicStreamModifiers { using traits = BasicStringTraits<StringType>; using ostream_type = typename traits::ostream_type; using streamed_char_type = typename traits::streamed_char_type; public: /** * Constructor. Store the stream's current state to be restored upon destruction. * * @param stream The stream to be modified. */ explicit BasicStreamModifiers(ostream_type &stream) noexcept; /** * Destructor. Restore the stream's orginal state. */ ~BasicStreamModifiers(); /** * Sets a formatting flag on the stream. * * @param flag The new formatting setting. */ void setf(std::ios_base::fmtflags flag); /** * Clears a mask of formatting flags on the stream and sets a specific flag. * * @param flag The new formatting setting. * @param mask The formatting mask to clear. */ void setf(std::ios_base::fmtflags flag, std::ios_base::fmtflags mask); /** * Imbue a new locale onto the stream with a specific facet. * * @tparam Facet The type of facet to imbue. */ template <typename Facet> void locale(); /** * Set the fill character of the stream. * * @param ch The new fill setting. */ void fill(streamed_char_type ch); /** * Set the width of the stream. * * @param size The new width setting. */ void width(std::streamsize size); /** * Set the precision of the stream. * * @param size The new precision setting. */ void precision(std::streamsize size); private: BasicStreamModifiers(const BasicStreamModifiers &) = delete; BasicStreamModifiers &operator=(const BasicStreamModifiers &) = delete; ostream_type &m_stream; const std::ios_base::fmtflags m_flags; bool m_changed_flags {false}; const std::locale m_locale; bool m_changed_locale {false}; const streamed_char_type m_fill; bool m_changed_fill {false}; const std::streamsize m_width; bool m_changed_width {false}; const std::streamsize m_precision; bool m_changed_precision {false}; }; /** * Helper facet to support BasicFormatSpecifier::Sign::NegativeOnlyWithPositivePadding. Overrides * std::ctype to replace the positive sign character with a space. * * @author Timothy Flynn ([email protected]) * @version January 3, 2021 */ template <typename CharType> class PositivePaddingFacet : public std::ctype<CharType> { protected: CharType do_widen(char ch) const override; const char *do_widen(const char *begin, const char *end, CharType *dest) const override; private: static constexpr const auto s_plus_sign = FLY_CHR(char, '+'); static constexpr const auto s_space = FLY_CHR(CharType, ' '); }; /** * Helper facet to support BasicFormatSpecifier::Type::Binary. Overrides std::num_put::do_put for * all integral types to write a value in a binary format, respecting any specified stream width, * alignment, and alternate form. * * @author Timothy Flynn ([email protected]) * @version January 3, 2021 */ template <typename CharType> class BinaryFacet : public std::num_put<CharType> { using iter_type = typename std::num_put<CharType>::iter_type; protected: iter_type do_put(iter_type out, std::ios_base &stream, CharType fill, std::intmax_t value) const override; iter_type do_put(iter_type out, std::ios_base &stream, CharType fill, std::uintmax_t value) const override; private: /** * Concrete implementation of the facet. Writes the minimum number of bits required to represent * the given value. If the stream's alternate form is specified, the bits are prefixed with * either '0b' or '0B', depending on whether the stream has specified uppercase formatting. * Space permitting, if a stream width is specified, padding is inserted using the provided fill * character. The location on the padding depends on whether left, right, or internal alignment * are specified. */ template <typename T> iter_type do_put_impl(iter_type out, std::ios_base &stream, CharType fill, T value) const; /** * Count the number of significant bits in the given value. This is the total number of bits in * the value excluding any leading zero bits. * * @tparam T Type of the value. Must be an unsigned, integral type. * * @param value The value to count. * * @return The number of significant bits counted. */ template <typename T> static constexpr std::size_t count_bits(T value); /** * Potentially insert padding symbols into the output iterator. */ void maybe_fill( iter_type out, std::ios_base &stream, CharType fill, std::ios_base::fmtflags alignment, std::size_t bits) const; static constexpr const auto s_zero = FLY_CHR(CharType, '0'); static constexpr const auto s_one = FLY_CHR(CharType, '1'); static constexpr const auto s_upper_b = FLY_CHR(CharType, 'B'); static constexpr const auto s_lower_b = FLY_CHR(CharType, 'b'); }; //================================================================================================== template <typename StringType> template <typename T, typename PreferredPresentationType> void BasicStringStreamer<StringType>::stream_value(ostream_type &stream, T &&value) { using U = std::remove_cvref_t<T>; using P = std::remove_cvref_t<PreferredPresentationType>; if constexpr (!std::is_same_v<U, P>) { if constexpr (std::is_convertible_v<U, P>) { stream << static_cast<PreferredPresentationType>(std::forward<T>(value)); } } else if constexpr (detail::is_like_supported_string_v<U>) { stream_string(stream, std::forward<T>(value), StringType::npos); } else if constexpr (detail::is_supported_character_v<T>) { // TODO: Validate the value fits into streamed_char_type / convert Unicode encoding. stream << static_cast<streamed_char_type>(std::forward<T>(value)); } else if constexpr (traits::OstreamTraits::template is_declared_v<U>) { stream << std::forward<T>(value); } } //================================================================================================== template <typename StringType> template <typename T> void BasicStringStreamer<StringType>::stream_string( ostream_type &stream, T &&value, std::size_t max_string_length) { using string_like_type = detail::is_like_supported_string_t<T>; using string_like_traits = BasicStringTraits<string_like_type>; typename string_like_traits::view_type view(std::forward<T>(value)); if constexpr (std::is_same_v<streamed_type, string_like_type>) { stream << view.substr(0, max_string_length); } else { using unicode = BasicStringUnicode<string_like_type>; using streamer = BasicStringStreamer<streamed_type>; auto it = view.cbegin(); const auto end = view.cend(); if (auto converted = unicode::template convert_encoding<streamed_type>(it, end); converted) { streamer::stream_string(stream, *std::move(converted), max_string_length); } } } //================================================================================================== template <typename StringType> BasicStreamModifiers<StringType>::BasicStreamModifiers(ostream_type &stream) noexcept : m_stream(stream), m_flags(stream.flags()), m_locale(stream.getloc()), m_fill(stream.fill()), m_width(stream.width()), m_precision(stream.precision()) { } //================================================================================================== template <typename StringType> BasicStreamModifiers<StringType>::~BasicStreamModifiers() { if (m_changed_flags) { m_stream.flags(m_flags); } if (m_changed_locale) { m_stream.imbue(m_locale); } if (m_changed_fill) { m_stream.fill(m_fill); } if (m_changed_width) { m_stream.width(m_width); } if (m_changed_precision) { m_stream.precision(m_precision); } } //================================================================================================== template <typename StringType> inline void BasicStreamModifiers<StringType>::setf(std::ios_base::fmtflags flag) { m_stream.setf(flag); m_changed_flags = true; } //================================================================================================== template <typename StringType> inline void BasicStreamModifiers<StringType>::setf(std::ios_base::fmtflags flag, std::ios_base::fmtflags mask) { m_stream.setf(flag, mask); m_changed_flags = true; } //================================================================================================== template <typename StringType> template <typename Facet> inline void BasicStreamModifiers<StringType>::locale() { m_stream.imbue({m_stream.getloc(), new Facet()}); m_changed_locale = true; } //================================================================================================== template <typename StringType> inline void BasicStreamModifiers<StringType>::fill(streamed_char_type ch) { m_stream.fill(ch); m_changed_fill = true; } //================================================================================================== template <typename StringType> inline void BasicStreamModifiers<StringType>::width(std::streamsize size) { m_stream.width(size); m_changed_width = true; } //================================================================================================== template <typename StringType> inline void BasicStreamModifiers<StringType>::precision(std::streamsize size) { m_stream.precision(size); m_changed_precision = true; } //================================================================================================== template <typename CharType> CharType PositivePaddingFacet<CharType>::do_widen(char ch) const { return (ch == s_plus_sign) ? s_space : static_cast<CharType>(ch); } //================================================================================================== template <typename CharType> const char * PositivePaddingFacet<CharType>::do_widen(const char *begin, const char *end, CharType *dest) const { while (begin != end) { *dest++ = do_widen(*begin++); } return end; } //================================================================================================== template <typename CharType> inline auto BinaryFacet<CharType>::do_put( iter_type out, std::ios_base &stream, CharType fill, std::intmax_t value) const -> iter_type { return do_put_impl(out, stream, fill, value); } //================================================================================================== template <typename CharType> inline auto BinaryFacet<CharType>::do_put( iter_type out, std::ios_base &stream, CharType fill, std::uintmax_t value) const -> iter_type { return do_put_impl(out, stream, fill, value); } //================================================================================================== template <typename CharType> template <typename T> auto BinaryFacet<CharType>::do_put_impl( iter_type out, std::ios_base &stream, CharType fill, T value) const -> iter_type { using unsigned_type = std::make_unsigned_t<T>; const auto unsigned_value = static_cast<unsigned_type>(value); const auto bits = count_bits(unsigned_value); maybe_fill(out, stream, fill, std::ios_base::right, bits); if (stream.flags() & std::ios_base::showbase) { *out++ = s_zero; *out++ = (stream.flags() & std::ios_base::uppercase) ? s_upper_b : s_lower_b; } maybe_fill(out, stream, fill, std::ios_base::internal, bits); for (std::size_t bit = bits; bit > 0; --bit) { *out++ = ((unsigned_value >> (bit - 1)) & 0x1) ? s_one : s_zero; } maybe_fill(out, stream, fill, std::ios_base::left, bits); return out; } //================================================================================================== template <typename CharType> template <typename T> inline constexpr std::size_t BinaryFacet<CharType>::count_bits(T value) { static_assert( std::is_unsigned_v<T> && std::is_integral_v<T>, "An unsigned integral type is required for count_bits"); std::size_t bits = 0; do { ++bits; } while ((value >>= 1) != 0); return bits; } //================================================================================================== template <typename CharType> void BinaryFacet<CharType>::maybe_fill( iter_type out, std::ios_base &stream, CharType fill, std::ios_base::fmtflags alignment, std::size_t bits) const { if ((stream.flags() & std::ios_base::adjustfield) == alignment) { std::streamsize fill_bits = stream.width() - static_cast<std::streamsize>(bits); fill_bits -= (stream.flags() & std::ios_base::showbase) ? 2 : 0; for (std::streamsize i = 0; i < fill_bits; ++i) { *out++ = fill; } } } } // namespace fly::detail <commit_msg>Remove unused BasicStringStreamer functionality<commit_after>#pragma once #include "fly/types/string/detail/string_traits.hpp" #include "fly/types/string/detail/string_unicode.hpp" #include "fly/types/string/string_literal.hpp" #include <cctype> #include <cstdint> #include <ios> #include <locale> #include <type_traits> namespace fly::detail { /** * Helper struct to stream generic values into a std::basic_ostream. * * For std::string and std::wstring, the "normal" stream types are used (std::ostream and * std::wostream, and their children, respectively). * * For std::u8string, std::u16string, and std::u32string, the STL does not provide stream types. For * a general solution, std::ostream is used, and any string value is converted to UTF-8. * * @author Timothy Flynn ([email protected]) * @version March 21, 2019 */ template <typename StringType> struct BasicStringStreamer { using traits = BasicStringTraits<StringType>; using ostream_type = typename traits::ostream_type; using streamed_type = typename traits::streamed_type; using streamed_char_type = typename traits::streamed_char_type; /** * Stream the given value into the given stream. * * For all string-like types, if the type corresponds to the stream type, then the string is * streamed as-is. Other string-like types are converted to the Unicode encoding used by the * stream type. * * For all character types, the character is case to the character type used by the stream type. * * For any other type which has an operator<< overload defined, the value is streamed using that * overload. * * All other types are dropped. * * @tparam T The type of the value to stream. * * @param stream The stream to insert the value into. * @param value The value to stream. */ template <typename T> static void stream_value(ostream_type &stream, T &&value); private: /** * Stream a string-like value into the given stream. If the type corresponds to the stream type, * then the string is streamed as-is. Other string-like types are converted to the Unicode * encoding used by the stream type. * * @tparam T The type of the string-like value to stream. * * @param stream The stream to insert the value into. * @param value The string-like value to stream. */ template <typename T> static void stream_string(ostream_type &stream, T &&value); }; /** * RAII helper class to make formatting modifications to a stream and ensure those modifications * are reset upon destruction. * * @author Timothy Flynn ([email protected]) * @version January 3, 2021 */ template <typename StringType> class BasicStreamModifiers { using traits = BasicStringTraits<StringType>; using ostream_type = typename traits::ostream_type; using streamed_char_type = typename traits::streamed_char_type; public: /** * Constructor. Store the stream's current state to be restored upon destruction. * * @param stream The stream to be modified. */ explicit BasicStreamModifiers(ostream_type &stream) noexcept; /** * Destructor. Restore the stream's orginal state. */ ~BasicStreamModifiers(); /** * Sets a formatting flag on the stream. * * @param flag The new formatting setting. */ void setf(std::ios_base::fmtflags flag); /** * Clears a mask of formatting flags on the stream and sets a specific flag. * * @param flag The new formatting setting. * @param mask The formatting mask to clear. */ void setf(std::ios_base::fmtflags flag, std::ios_base::fmtflags mask); /** * Imbue a new locale onto the stream with a specific facet. * * @tparam Facet The type of facet to imbue. */ template <typename Facet> void locale(); /** * Set the fill character of the stream. * * @param ch The new fill setting. */ void fill(streamed_char_type ch); /** * Set the width of the stream. * * @param size The new width setting. */ void width(std::streamsize size); /** * Set the precision of the stream. * * @param size The new precision setting. */ void precision(std::streamsize size); private: BasicStreamModifiers(const BasicStreamModifiers &) = delete; BasicStreamModifiers &operator=(const BasicStreamModifiers &) = delete; ostream_type &m_stream; const std::ios_base::fmtflags m_flags; bool m_changed_flags {false}; const std::locale m_locale; bool m_changed_locale {false}; const streamed_char_type m_fill; bool m_changed_fill {false}; const std::streamsize m_width; bool m_changed_width {false}; const std::streamsize m_precision; bool m_changed_precision {false}; }; /** * Helper facet to support BasicFormatSpecifier::Sign::NegativeOnlyWithPositivePadding. Overrides * std::ctype to replace the positive sign character with a space. * * @author Timothy Flynn ([email protected]) * @version January 3, 2021 */ template <typename CharType> class PositivePaddingFacet : public std::ctype<CharType> { protected: CharType do_widen(char ch) const override; const char *do_widen(const char *begin, const char *end, CharType *dest) const override; private: static constexpr const auto s_plus_sign = FLY_CHR(char, '+'); static constexpr const auto s_space = FLY_CHR(CharType, ' '); }; //================================================================================================== template <typename StringType> template <typename T> void BasicStringStreamer<StringType>::stream_value(ostream_type &stream, T &&value) { using U = std::remove_cvref_t<T>; if constexpr (detail::is_like_supported_string_v<U>) { stream_string(stream, std::forward<T>(value)); } else if constexpr (detail::is_supported_character_v<T>) { // TODO: Validate the value fits into streamed_char_type / convert Unicode encoding. stream << static_cast<streamed_char_type>(std::forward<T>(value)); } else if constexpr (traits::OstreamTraits::template is_declared_v<U>) { stream << std::forward<T>(value); } } //================================================================================================== template <typename StringType> template <typename T> void BasicStringStreamer<StringType>::stream_string(ostream_type &stream, T &&value) { using string_like_type = detail::is_like_supported_string_t<T>; using string_like_traits = BasicStringTraits<string_like_type>; if constexpr (std::is_same_v<streamed_type, string_like_type>) { stream << value; } else { using unicode = BasicStringUnicode<string_like_type>; using streamer = BasicStringStreamer<streamed_type>; typename string_like_traits::view_type view(std::forward<T>(value)); auto it = view.cbegin(); const auto end = view.cend(); if (auto converted = unicode::template convert_encoding<streamed_type>(it, end); converted) { streamer::stream_value(stream, *std::move(converted)); } } } //================================================================================================== template <typename StringType> BasicStreamModifiers<StringType>::BasicStreamModifiers(ostream_type &stream) noexcept : m_stream(stream), m_flags(stream.flags()), m_locale(stream.getloc()), m_fill(stream.fill()), m_width(stream.width()), m_precision(stream.precision()) { } //================================================================================================== template <typename StringType> BasicStreamModifiers<StringType>::~BasicStreamModifiers() { if (m_changed_flags) { m_stream.flags(m_flags); } if (m_changed_locale) { m_stream.imbue(m_locale); } if (m_changed_fill) { m_stream.fill(m_fill); } if (m_changed_width) { m_stream.width(m_width); } if (m_changed_precision) { m_stream.precision(m_precision); } } //================================================================================================== template <typename StringType> inline void BasicStreamModifiers<StringType>::setf(std::ios_base::fmtflags flag) { m_stream.setf(flag); m_changed_flags = true; } //================================================================================================== template <typename StringType> inline void BasicStreamModifiers<StringType>::setf(std::ios_base::fmtflags flag, std::ios_base::fmtflags mask) { m_stream.setf(flag, mask); m_changed_flags = true; } //================================================================================================== template <typename StringType> template <typename Facet> inline void BasicStreamModifiers<StringType>::locale() { m_stream.imbue({m_stream.getloc(), new Facet()}); m_changed_locale = true; } //================================================================================================== template <typename StringType> inline void BasicStreamModifiers<StringType>::fill(streamed_char_type ch) { m_stream.fill(ch); m_changed_fill = true; } //================================================================================================== template <typename StringType> inline void BasicStreamModifiers<StringType>::width(std::streamsize size) { m_stream.width(size); m_changed_width = true; } //================================================================================================== template <typename StringType> inline void BasicStreamModifiers<StringType>::precision(std::streamsize size) { m_stream.precision(size); m_changed_precision = true; } //================================================================================================== template <typename CharType> CharType PositivePaddingFacet<CharType>::do_widen(char ch) const { return (ch == s_plus_sign) ? s_space : static_cast<CharType>(ch); } //================================================================================================== template <typename CharType> const char * PositivePaddingFacet<CharType>::do_widen(const char *begin, const char *end, CharType *dest) const { while (begin != end) { *dest++ = do_widen(*begin++); } return end; } } // namespace fly::detail <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "TransientMultiApp.h" #include "LayeredSideFluxAverage.h" // libMesh #include "libmesh/mesh_tools.h" template<> InputParameters validParams<TransientMultiApp>() { InputParameters params = validParams<MultiApp>(); params += validParams<TransientInterface>(); params.addParam<bool>("sub_cycling", false, "Set to true to allow this MultiApp to take smaller timesteps than the rest of the simulation. More than one timestep will be performed for each 'master' timestep"); params.addParam<bool>("detect_steady_state", false, "If true then while sub_cycling a steady state check will be done. In this mode output will only be done once the MultiApp reaches the target time or steady state is reached"); params.addParam<Real>("steady_state_tol", 1e-8, "The relative difference between the new solution and the old solution that will be considered to be at steady state"); params.addParam<unsigned int>("max_failures", 0, "Maximum number of solve failures tolerated while sub_cycling."); return params; } TransientMultiApp::TransientMultiApp(const std::string & name, InputParameters parameters): MultiApp(name, parameters), TransientInterface(parameters, name, "multiapps"), _sub_cycling(getParam<bool>("sub_cycling")), _detect_steady_state(getParam<bool>("detect_steady_state")), _steady_state_tol(getParam<Real>("steady_state_tol")), _max_failures(getParam<unsigned int>("max_failures")), _failures(0) { if(!_has_an_app) return; MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm); if(_has_an_app) { _transient_executioners.resize(_my_num_apps); // Grab Transient Executioners from each app for(unsigned int i=0; i<_my_num_apps; i++) { MooseApp * app = _apps[i]; Transient * ex = dynamic_cast<Transient *>(app->getExecutioner()); if(!ex) mooseError("MultiApp " << name << " is not using a Transient Executioner!"); appProblem(_first_local_app + i)->initialSetup(); ex->preExecute(); appProblem(_first_local_app + i)->copyOldSolutions(); _transient_executioners[i] = ex; if(_detect_steady_state) ex->allowOutput(false); } } // Swap back Moose::swapLibMeshComm(swapped); } TransientMultiApp::~TransientMultiApp() { if(!_has_an_app) return; MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm); for(unsigned int i=0; i<_my_num_apps; i++) { Transient * ex = _transient_executioners[i]; ex->postExecute(); } // Swap back Moose::swapLibMeshComm(swapped); } void TransientMultiApp::solveStep() { if(!_has_an_app) return; std::cout<<"Solving MultiApp "<<_name<<std::endl; MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm); int rank; MPI_Comm_rank(_orig_comm, &rank); for(unsigned int i=0; i<_my_num_apps; i++) { Transient * ex = _transient_executioners[i]; if(_sub_cycling) { ex->setTargetTime(_t); unsigned int failures = 0; bool at_steady = false; // Now do all of the solves we need while(!at_steady && ex->getTime() + 2e-14 < _t) { ex->takeStep(); bool converged = ex->lastSolveConverged(); if(!converged) { mooseWarning("While sub_cycling "<<_name<<_first_local_app+i<<" failed to converge!"<<std::endl); _failures++; if(_failures > _max_failures) mooseError("While sub_cycling "<<_name<<_first_local_app+i<<" REALLY failed!"<<std::endl); } Real solution_change_norm = ex->solutionChangeNorm(); if(_detect_steady_state) std::cout<<"Solution change norm: "<<solution_change_norm<<std::endl; if(_detect_steady_state && solution_change_norm < _steady_state_tol) { std::cout<<"Detected Steady State! Fast-forwarding to "<<_t<<std::endl; at_steady = true; // Set the time for the problem to the target time we were looking for ex->setTime(_t); // Force it to output right now ex->forceOutput(); // Clean up the end ex->endStep(); } else ex->endStep(); } // If we were looking for a steady state, but didn't reach one, we still need to output one more time if(_detect_steady_state && !at_steady) ex->forceOutput(); } else { ex->takeStep(_dt); if(!ex->lastSolveConverged()) mooseWarning(_name<<_first_local_app+i<<" failed to converge!"<<std::endl); ex->endStep(); } } // Swap back Moose::swapLibMeshComm(swapped); std::cout<<"Finished Solving MultiApp "<<_name<<std::endl; } Real TransientMultiApp::computeDT() { if(_sub_cycling) // Bow out of the timestep selection dance return std::numeric_limits<Real>::max(); Real smallest_dt = std::numeric_limits<Real>::max(); if(_has_an_app) { MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm); for(unsigned int i=0; i<_my_num_apps; i++) { Transient * ex = _transient_executioners[i]; Real dt = ex->computeConstrainedDT(); smallest_dt = std::min(dt, smallest_dt); } // Swap back Moose::swapLibMeshComm(swapped); } Parallel::min(smallest_dt); return smallest_dt; } <commit_msg>ready to run with multiscale ref #1845<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "TransientMultiApp.h" #include "LayeredSideFluxAverage.h" // libMesh #include "libmesh/mesh_tools.h" template<> InputParameters validParams<TransientMultiApp>() { InputParameters params = validParams<MultiApp>(); params += validParams<TransientInterface>(); params.addParam<bool>("sub_cycling", false, "Set to true to allow this MultiApp to take smaller timesteps than the rest of the simulation. More than one timestep will be performed for each 'master' timestep"); params.addParam<bool>("detect_steady_state", false, "If true then while sub_cycling a steady state check will be done. In this mode output will only be done once the MultiApp reaches the target time or steady state is reached"); params.addParam<Real>("steady_state_tol", 1e-8, "The relative difference between the new solution and the old solution that will be considered to be at steady state"); params.addParam<unsigned int>("max_failures", 0, "Maximum number of solve failures tolerated while sub_cycling."); return params; } TransientMultiApp::TransientMultiApp(const std::string & name, InputParameters parameters): MultiApp(name, parameters), TransientInterface(parameters, name, "multiapps"), _sub_cycling(getParam<bool>("sub_cycling")), _detect_steady_state(getParam<bool>("detect_steady_state")), _steady_state_tol(getParam<Real>("steady_state_tol")), _max_failures(getParam<unsigned int>("max_failures")), _failures(0) { if(!_has_an_app) return; MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm); if(_has_an_app) { _transient_executioners.resize(_my_num_apps); // Grab Transient Executioners from each app for(unsigned int i=0; i<_my_num_apps; i++) { MooseApp * app = _apps[i]; Transient * ex = dynamic_cast<Transient *>(app->getExecutioner()); if(!ex) mooseError("MultiApp " << name << " is not using a Transient Executioner!"); appProblem(_first_local_app + i)->initialSetup(); ex->preExecute(); appProblem(_first_local_app + i)->copyOldSolutions(); _transient_executioners[i] = ex; if(_detect_steady_state) ex->allowOutput(false); } } // Swap back Moose::swapLibMeshComm(swapped); } TransientMultiApp::~TransientMultiApp() { if(!_has_an_app) return; MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm); for(unsigned int i=0; i<_my_num_apps; i++) { Transient * ex = _transient_executioners[i]; ex->postExecute(); } // Swap back Moose::swapLibMeshComm(swapped); } void TransientMultiApp::solveStep() { if(!_has_an_app) return; std::cout<<"Solving MultiApp "<<_name<<std::endl; MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm); int rank; MPI_Comm_rank(_orig_comm, &rank); for(unsigned int i=0; i<_my_num_apps; i++) { Transient * ex = _transient_executioners[i]; if(_sub_cycling) { ex->setTargetTime(_t); unsigned int failures = 0; bool at_steady = false; // Now do all of the solves we need while(!at_steady && ex->getTime() + 2e-14 < _t) { ex->takeStep(); bool converged = ex->lastSolveConverged(); if(!converged) { mooseWarning("While sub_cycling "<<_name<<_first_local_app+i<<" failed to converge!"<<std::endl); _failures++; if(_failures > _max_failures) mooseError("While sub_cycling "<<_name<<_first_local_app+i<<" REALLY failed!"<<std::endl); } Real solution_change_norm = ex->solutionChangeNorm(); if(_detect_steady_state) std::cout<<"Solution change norm: "<<solution_change_norm<<std::endl; if(converged && _detect_steady_state && solution_change_norm < _steady_state_tol) { std::cout<<"Detected Steady State! Fast-forwarding to "<<_t<<std::endl; at_steady = true; // Set the time for the problem to the target time we were looking for ex->setTime(_t); // Force it to output right now ex->forceOutput(); // Clean up the end ex->endStep(); } else ex->endStep(); } // If we were looking for a steady state, but didn't reach one, we still need to output one more time if(_detect_steady_state && !at_steady) ex->forceOutput(); } else { ex->takeStep(_dt); if(!ex->lastSolveConverged()) mooseWarning(_name<<_first_local_app+i<<" failed to converge!"<<std::endl); ex->endStep(); } } // Swap back Moose::swapLibMeshComm(swapped); std::cout<<"Finished Solving MultiApp "<<_name<<std::endl; } Real TransientMultiApp::computeDT() { if(_sub_cycling) // Bow out of the timestep selection dance return std::numeric_limits<Real>::max(); Real smallest_dt = std::numeric_limits<Real>::max(); if(_has_an_app) { MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm); for(unsigned int i=0; i<_my_num_apps; i++) { Transient * ex = _transient_executioners[i]; Real dt = ex->computeConstrainedDT(); smallest_dt = std::min(dt, smallest_dt); } // Swap back Moose::swapLibMeshComm(swapped); } Parallel::min(smallest_dt); return smallest_dt; } <|endoftext|>
<commit_before>// window.cpp #define DEFAULT_MODEL ":/3D_models/articated.obj" #ifndef SAMPLES_DIR #define SAMPLES_DIR "" #endif #include <QComboBox> #include <QDialog> #include <QDir> #include <QFileDialog> #include <QLabel> #include <QLineEdit> #include <QList> #include <QMessageBox> #include <QResizeEvent> #include <QSpinBox> #include <QStringList> #include <QtMultimedia/QCameraInfo> #include <iostream> #include "window.hpp" Window::Window (QWidget* parent) : QWidget (parent) , _is_paused (false) , _vision (_statusbar, _augmentation, this) , _layout (this) , _btn_reference ("") , _btn_pause ("") , _btn_settings ("") { this->layout ()->setContentsMargins (0, 0, 0, 0); // add background and foreground _layout.addLayout (&_layout_back, 0, 0); _layout.addLayout (&_layout_ui, 0, 0); _augmentation.setMinimumSize (600, 350); // somewhat 16:9 ratio _layout_back.addWidget (&_augmentation, 1); _layout_ui.addLayout (&_layout_status, 64); _layout_ui.addLayout (&_layout_buttons, 8); _layout_ui.insertStretch (2, 1); // small border after buttons _layout_status.insertStretch (0, 12); _layout_status.addWidget (&_statusbar, 1); _statusbar.setSizeGripEnabled (false); _layout_buttons.insertStretch (0, 1); _layout_buttons.addWidget (&_btn_pause, 2); _btn_pause.setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Expanding); _layout_buttons.setAlignment (&_btn_pause, Qt::AlignHCenter); _layout_buttons.insertStretch (2, 1); _layout_buttons.addWidget (&_btn_reference, 4); _btn_reference.setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Expanding); _layout_buttons.insertStretch (4, 1); _layout_buttons.addWidget (&_btn_settings, 2); _btn_settings.setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Expanding); _layout_buttons.setAlignment (&_btn_settings, Qt::AlignHCenter); _layout_buttons.insertStretch (6, 1); _statusbar.raise (); // don't be shy, come closer to people connect (&_btn_settings, SIGNAL (clicked ()), this, SLOT (btn_settings_clicked ())); connect (&_btn_pause, SIGNAL (clicked ()), this, SLOT (btn_pause_clicked ())); connect (&_btn_reference, SIGNAL (clicked ()), this, SLOT (btn_reference_clicked ())); connect (&_frame_timer, SIGNAL (timeout ()), this, SLOT (timeout ())); update_ui_style (); set_framerate (30); // fps connect (&_augmentation, SIGNAL (initialized ()), this, SLOT (augmentation_widget_initialized ())); debug_level (0); } Window::~Window () { } void Window::resizeEvent (QResizeEvent* event) { (void)event; // this is not used atm update_ui_style (); } QSize Window::minimumSizeHint () const { return _layout_back.minimumSize (); } QSize Window::sizeHint () const { return _layout_back.sizeHint (); } void Window::keyPressEvent (QKeyEvent* e) { switch (e->key ()) { case Qt::Key_Plus: debug_level (_vision.debug_mode () + 1); break; case Qt::Key_Minus: debug_level (_vision.debug_mode () - 1); break; case Qt::Key_M: case Qt::Key_Menu: case Qt::Key_Control: btn_settings_clicked (); break; case Qt::Key_Back: case Qt::Key_Escape: this->close (); break; default: break; } } void Window::set_framerate (int framerate) { if (framerate < 0) { _frame_timer.stop (); } else if (framerate == 0) { _frame_timer.setInterval (0); _frame_timer.start (); } else { _frame_timer.setInterval (1000 / framerate); _frame_timer.start (); } } void Window::timeout () { ; } void Window::augmentation_widget_initialized () { bool object_load_succes = _augmentation.loadObject (DEFAULT_MODEL); if (!object_load_succes) { _statusbar.showMessage ("failed to load inital model", 5000); } } void Window::btn_pause_clicked () { if (_is_paused) { _vision.set_paused (false); _is_paused = false; } else { _vision.set_paused (true); _is_paused = true; } update_ui_style (); } void Window::btn_settings_clicked () { //_vision.set_input (QString (":/debug_samples/3_markers_good.webm")); // create dialog ui elements QDialog dialog (this); QBoxLayout layout_dialog (QBoxLayout::TopToBottom, &dialog); QPushButton btn_debug_file ("Load test video"); QComboBox box_camid; QSpinBox box_debug; QComboBox box_model; QLabel label1 ("Select camera:"); QLabel label2 ("Or load test video"); QLabel label3 ("Select 3D model:"); QLabel label4 ("Debug level:"); // order the ui elements dialog.setWindowTitle ("Settings"); layout_dialog.addWidget (&label1); layout_dialog.addWidget (&box_camid); layout_dialog.addWidget (&label2); layout_dialog.addWidget (&btn_debug_file); layout_dialog.addWidget (&label3); layout_dialog.addWidget (&box_model); layout_dialog.addWidget (&label4); layout_dialog.addWidget (&box_debug); // fill list of cameras QList<QCameraInfo> cameras = QCameraInfo::availableCameras (); if (cameras.size () > 0) { box_camid.addItem ("Select Camera"); foreach (const QCameraInfo& cameraInfo, cameras) { box_camid.addItem (cameraInfo.description ()); } } else { box_camid.setEnabled (false); box_camid.addItem ("No Cameras Found"); } // fill list of models box_model.addItem ("Select Model"); QDir path (":/3D_models/"); QStringList files = path.entryList (QDir::Files); box_model.addItems (files); connect (&box_camid, SIGNAL (currentIndexChanged (int)), &dialog, SLOT (close ())); connect (&box_camid, SIGNAL (currentIndexChanged (int)), this, SLOT (dialog_box_camid_indexchanged (int))); connect (&box_model, SIGNAL (currentIndexChanged (int)), &dialog, SLOT (close ())); connect (&box_model, SIGNAL (currentIndexChanged (QString)), this, SLOT (dialog_box_model_indexchanged (QString))); connect (&btn_debug_file, SIGNAL (clicked ()), &dialog, SLOT (close ())); connect (&btn_debug_file, SIGNAL (clicked ()), this, SLOT (btn_load_test_video_clicked ())); connect (&box_debug, SIGNAL (valueChanged (int)), this, SLOT (debug_level (int))); dialog.exec (); } void Window::btn_load_test_video_clicked () { _vision.set_input (QString (":/debug_samples/3_markers_good.webm")); } void Window::dialog_box_camid_indexchanged (int idx) { QList<QCameraInfo> cameras = QCameraInfo::availableCameras (); if (cameras.size () > 0) { idx -= 1; if (idx >= 0 && idx < cameras.size ()) { _vision.set_input (cameras.at (idx)); } } _statusbar.showMessage (QString ("Selected camera #") + QString::number (idx), 2000); } void Window::dialog_box_model_indexchanged (QString name) { _augmentation.loadObject (name.prepend (":/3D_models/")); } void Window::btn_reference_clicked () { _statusbar.showMessage (QString ("set reference button"), 2000); _vision.set_reference (); } void Window::debug_level (int lvl) { lvl = lvl < 0 ? 0 : lvl; lvl = lvl > 3 ? 3 : lvl; _vision.set_debug_mode (lvl); } void Window::update_ui_style () { /* ref button */ QSize _btn_ref_size = _btn_reference.size (); _btn_reference.setMinimumWidth (_btn_ref_size.height ()); QString _btn_ref_style = "QPushButton { " " background-color: rgba(255, 255, 255, 50);" " border:5px solid rgb(100, 100, 100);" " border-radius:50px;" "}" "QPushButton:pressed {" " background-color: rgba(255, 255, 255, 255);" " border: 5px solid rgba(150, 150, 150);" "}" "QPushButton:focus {" " outline: none;" "}"; _btn_ref_style.replace ("border-radius:50px", QString ("border-radius:" + QString::number (_btn_ref_size.height () / 2) + "px")); _btn_reference.setStyleSheet (_btn_ref_style); /* settings button */ QSize _btn_settings_size = _btn_settings.size (); _btn_settings.setMinimumWidth (_btn_settings_size.height ()); QString _btn_settings_style = "QPushButton { " " background-color: rgba(50, 50, 50, 50);" " border:5px solid rgb(0, 0, 0);" " border-radius:50px;" "}" "QPushButton:pressed {" " background-color: rgba(50, 50, 50, 255);" " border: 5px solid rgba(50, 50, 50);" "}" "QPushButton:focus {" " outline: none;" "}"; _btn_settings_style.replace ("border-radius:50px", QString ("border-radius:" + QString::number (_btn_settings_size.height () / 2) + "px")); _btn_settings.setStyleSheet (_btn_settings_style); /* pause button */ QSize _btn_pause_size = _btn_pause.size (); _btn_pause.setMinimumWidth (_btn_pause_size.height ()); QString _btn_pause_style = ""; if (_is_paused) { _btn_pause_style = "QPushButton { " " background-color: rgba(255, 0, 0, 255);" " border: 5px solid rgb(255, 0, 0);" " border-radius:50px;" "}" "QPushButton:focus {" " outline: none;" "}"; } else { _btn_pause_style = "QPushButton { " " background-color: rgba(255, 0, 0, 100);" " border: 5px solid rgb(255, 0, 0);" " border-radius:50px;" "}" "QPushButton:focus {" " outline: none;" "}"; } _btn_pause_style.replace ("border-radius:50px", QString ("border-radius:" + QString::number (_btn_pause_size.height () / 2) + "px")); _btn_pause.setStyleSheet (_btn_pause_style); /* status bar */ QString _statusbar_style = "color:rgba(255, 255, 255, 255);" "background-color: rgba(100, 100, 100, 255);" "border-top-right-radius: 50px;"; _statusbar_style.replace ("border-top-right-radius: 50px;", QString ("border-top-right-radius:" + QString::number (_statusbar.size ().height () * 0.75) + "px")); _statusbar.setStyleSheet (_statusbar_style); } <commit_msg>remove obsolete define<commit_after>// window.cpp #define DEFAULT_MODEL ":/3D_models/articated.obj" #include <QComboBox> #include <QDialog> #include <QDir> #include <QFileDialog> #include <QLabel> #include <QLineEdit> #include <QList> #include <QMessageBox> #include <QResizeEvent> #include <QSpinBox> #include <QStringList> #include <QtMultimedia/QCameraInfo> #include <iostream> #include "window.hpp" Window::Window (QWidget* parent) : QWidget (parent) , _is_paused (false) , _vision (_statusbar, _augmentation, this) , _layout (this) , _btn_reference ("") , _btn_pause ("") , _btn_settings ("") { this->layout ()->setContentsMargins (0, 0, 0, 0); // add background and foreground _layout.addLayout (&_layout_back, 0, 0); _layout.addLayout (&_layout_ui, 0, 0); _augmentation.setMinimumSize (600, 350); // somewhat 16:9 ratio _layout_back.addWidget (&_augmentation, 1); _layout_ui.addLayout (&_layout_status, 64); _layout_ui.addLayout (&_layout_buttons, 8); _layout_ui.insertStretch (2, 1); // small border after buttons _layout_status.insertStretch (0, 12); _layout_status.addWidget (&_statusbar, 1); _statusbar.setSizeGripEnabled (false); _layout_buttons.insertStretch (0, 1); _layout_buttons.addWidget (&_btn_pause, 2); _btn_pause.setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Expanding); _layout_buttons.setAlignment (&_btn_pause, Qt::AlignHCenter); _layout_buttons.insertStretch (2, 1); _layout_buttons.addWidget (&_btn_reference, 4); _btn_reference.setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Expanding); _layout_buttons.insertStretch (4, 1); _layout_buttons.addWidget (&_btn_settings, 2); _btn_settings.setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Expanding); _layout_buttons.setAlignment (&_btn_settings, Qt::AlignHCenter); _layout_buttons.insertStretch (6, 1); _statusbar.raise (); // don't be shy, come closer to people connect (&_btn_settings, SIGNAL (clicked ()), this, SLOT (btn_settings_clicked ())); connect (&_btn_pause, SIGNAL (clicked ()), this, SLOT (btn_pause_clicked ())); connect (&_btn_reference, SIGNAL (clicked ()), this, SLOT (btn_reference_clicked ())); connect (&_frame_timer, SIGNAL (timeout ()), this, SLOT (timeout ())); update_ui_style (); set_framerate (30); // fps connect (&_augmentation, SIGNAL (initialized ()), this, SLOT (augmentation_widget_initialized ())); debug_level (0); } Window::~Window () { } void Window::resizeEvent (QResizeEvent* event) { (void)event; // this is not used atm update_ui_style (); } QSize Window::minimumSizeHint () const { return _layout_back.minimumSize (); } QSize Window::sizeHint () const { return _layout_back.sizeHint (); } void Window::keyPressEvent (QKeyEvent* e) { switch (e->key ()) { case Qt::Key_Plus: debug_level (_vision.debug_mode () + 1); break; case Qt::Key_Minus: debug_level (_vision.debug_mode () - 1); break; case Qt::Key_M: case Qt::Key_Menu: case Qt::Key_Control: btn_settings_clicked (); break; case Qt::Key_Back: case Qt::Key_Escape: this->close (); break; default: break; } } void Window::set_framerate (int framerate) { if (framerate < 0) { _frame_timer.stop (); } else if (framerate == 0) { _frame_timer.setInterval (0); _frame_timer.start (); } else { _frame_timer.setInterval (1000 / framerate); _frame_timer.start (); } } void Window::timeout () { ; } void Window::augmentation_widget_initialized () { bool object_load_succes = _augmentation.loadObject (DEFAULT_MODEL); if (!object_load_succes) { _statusbar.showMessage ("failed to load inital model", 5000); } } void Window::btn_pause_clicked () { if (_is_paused) { _vision.set_paused (false); _is_paused = false; } else { _vision.set_paused (true); _is_paused = true; } update_ui_style (); } void Window::btn_settings_clicked () { //_vision.set_input (QString (":/debug_samples/3_markers_good.webm")); // create dialog ui elements QDialog dialog (this); QBoxLayout layout_dialog (QBoxLayout::TopToBottom, &dialog); QPushButton btn_debug_file ("Load test video"); QComboBox box_camid; QSpinBox box_debug; QComboBox box_model; QLabel label1 ("Select camera:"); QLabel label2 ("Or load test video"); QLabel label3 ("Select 3D model:"); QLabel label4 ("Debug level:"); // order the ui elements dialog.setWindowTitle ("Settings"); layout_dialog.addWidget (&label1); layout_dialog.addWidget (&box_camid); layout_dialog.addWidget (&label2); layout_dialog.addWidget (&btn_debug_file); layout_dialog.addWidget (&label3); layout_dialog.addWidget (&box_model); layout_dialog.addWidget (&label4); layout_dialog.addWidget (&box_debug); // fill list of cameras QList<QCameraInfo> cameras = QCameraInfo::availableCameras (); if (cameras.size () > 0) { box_camid.addItem ("Select Camera"); foreach (const QCameraInfo& cameraInfo, cameras) { box_camid.addItem (cameraInfo.description ()); } } else { box_camid.setEnabled (false); box_camid.addItem ("No Cameras Found"); } // fill list of models box_model.addItem ("Select Model"); QDir path (":/3D_models/"); QStringList files = path.entryList (QDir::Files); box_model.addItems (files); connect (&box_camid, SIGNAL (currentIndexChanged (int)), &dialog, SLOT (close ())); connect (&box_camid, SIGNAL (currentIndexChanged (int)), this, SLOT (dialog_box_camid_indexchanged (int))); connect (&box_model, SIGNAL (currentIndexChanged (int)), &dialog, SLOT (close ())); connect (&box_model, SIGNAL (currentIndexChanged (QString)), this, SLOT (dialog_box_model_indexchanged (QString))); connect (&btn_debug_file, SIGNAL (clicked ()), &dialog, SLOT (close ())); connect (&btn_debug_file, SIGNAL (clicked ()), this, SLOT (btn_load_test_video_clicked ())); connect (&box_debug, SIGNAL (valueChanged (int)), this, SLOT (debug_level (int))); dialog.exec (); } void Window::btn_load_test_video_clicked () { _vision.set_input (QString (":/debug_samples/3_markers_good.webm")); } void Window::dialog_box_camid_indexchanged (int idx) { QList<QCameraInfo> cameras = QCameraInfo::availableCameras (); if (cameras.size () > 0) { idx -= 1; if (idx >= 0 && idx < cameras.size ()) { _vision.set_input (cameras.at (idx)); } } _statusbar.showMessage (QString ("Selected camera #") + QString::number (idx), 2000); } void Window::dialog_box_model_indexchanged (QString name) { _augmentation.loadObject (name.prepend (":/3D_models/")); } void Window::btn_reference_clicked () { _statusbar.showMessage (QString ("set reference button"), 2000); _vision.set_reference (); } void Window::debug_level (int lvl) { lvl = lvl < 0 ? 0 : lvl; lvl = lvl > 3 ? 3 : lvl; _vision.set_debug_mode (lvl); } void Window::update_ui_style () { /* ref button */ QSize _btn_ref_size = _btn_reference.size (); _btn_reference.setMinimumWidth (_btn_ref_size.height ()); QString _btn_ref_style = "QPushButton { " " background-color: rgba(255, 255, 255, 50);" " border:5px solid rgb(100, 100, 100);" " border-radius:50px;" "}" "QPushButton:pressed {" " background-color: rgba(255, 255, 255, 255);" " border: 5px solid rgba(150, 150, 150);" "}" "QPushButton:focus {" " outline: none;" "}"; _btn_ref_style.replace ("border-radius:50px", QString ("border-radius:" + QString::number (_btn_ref_size.height () / 2) + "px")); _btn_reference.setStyleSheet (_btn_ref_style); /* settings button */ QSize _btn_settings_size = _btn_settings.size (); _btn_settings.setMinimumWidth (_btn_settings_size.height ()); QString _btn_settings_style = "QPushButton { " " background-color: rgba(50, 50, 50, 50);" " border:5px solid rgb(0, 0, 0);" " border-radius:50px;" "}" "QPushButton:pressed {" " background-color: rgba(50, 50, 50, 255);" " border: 5px solid rgba(50, 50, 50);" "}" "QPushButton:focus {" " outline: none;" "}"; _btn_settings_style.replace ("border-radius:50px", QString ("border-radius:" + QString::number (_btn_settings_size.height () / 2) + "px")); _btn_settings.setStyleSheet (_btn_settings_style); /* pause button */ QSize _btn_pause_size = _btn_pause.size (); _btn_pause.setMinimumWidth (_btn_pause_size.height ()); QString _btn_pause_style = ""; if (_is_paused) { _btn_pause_style = "QPushButton { " " background-color: rgba(255, 0, 0, 255);" " border: 5px solid rgb(255, 0, 0);" " border-radius:50px;" "}" "QPushButton:focus {" " outline: none;" "}"; } else { _btn_pause_style = "QPushButton { " " background-color: rgba(255, 0, 0, 100);" " border: 5px solid rgb(255, 0, 0);" " border-radius:50px;" "}" "QPushButton:focus {" " outline: none;" "}"; } _btn_pause_style.replace ("border-radius:50px", QString ("border-radius:" + QString::number (_btn_pause_size.height () / 2) + "px")); _btn_pause.setStyleSheet (_btn_pause_style); /* status bar */ QString _statusbar_style = "color:rgba(255, 255, 255, 255);" "background-color: rgba(100, 100, 100, 255);" "border-top-right-radius: 50px;"; _statusbar_style.replace ("border-top-right-radius: 50px;", QString ("border-top-right-radius:" + QString::number (_statusbar.size ().height () * 0.75) + "px")); _statusbar.setStyleSheet (_statusbar_style); } <|endoftext|>
<commit_before>/* * Copyright (c) 2017 Akil Darjean ([email protected]) * Distributed under the MIT License. * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT */ #include "window.h" #include <SFML/Graphics.hpp> #include <exception> Window::Window(const std::string&& filename) { this->filename = filename; load(); init(); draw(); } void Window::load() { if (!texture.loadFromFile(filename)) { throw std::runtime_error("Error: Image not found"); } texture.setSmooth(true); sprite.setTexture(texture); } void Window::init() { window.create(sf::VideoMode(640, 480), "SFML Image Viewer"); window.setKeyRepeatEnabled(false); // Initialize view view.reset(sf::FloatRect( 0, 0, static_cast<float>(texture.getSize().x), static_cast<float>(texture.getSize().y))); } void Window::draw() { while (window.isOpen()) { checkEvents(); window.clear(); window.setView(view); window.draw(sprite); window.display(); } } void Window::checkEvents() { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::EventType::Closed: window.close(); break; case sf::Event::EventType::Resized: getLetterboxView(); break; case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Q) { window.close(); } default: break; } } } void Window::getLetterboxView() { float windowRatio = window.getSize().x / static_cast<float>(window.getSize().y); float viewRatio = view.getSize().x / static_cast<float>(view.getSize().y); sf::Vector2f size; sf::Vector2f pos; if (windowRatio > viewRatio) { size.x = viewRatio / windowRatio; pos.x = (1 - size.x) / 2.f; size.y = 1; pos.y = 0; } else { size.y = windowRatio / viewRatio; pos.y = (1 - size.y) / 2.f; size.x = 1; pos.x = 0; } view.setViewport(sf::FloatRect(pos.x, pos.y, size.x, size.y)); } <commit_msg>Add missing 'break;' statement to switch<commit_after>/* * Copyright (c) 2017 Akil Darjean ([email protected]) * Distributed under the MIT License. * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT */ #include "window.h" #include <SFML/Graphics.hpp> #include <exception> Window::Window(const std::string&& filename) { this->filename = filename; load(); init(); draw(); } void Window::load() { if (!texture.loadFromFile(filename)) { throw std::runtime_error("Error: Image not found"); } texture.setSmooth(true); sprite.setTexture(texture); } void Window::init() { window.create(sf::VideoMode(640, 480), "SFML Image Viewer"); window.setKeyRepeatEnabled(false); // Initialize view view.reset(sf::FloatRect( 0, 0, static_cast<float>(texture.getSize().x), static_cast<float>(texture.getSize().y))); } void Window::draw() { while (window.isOpen()) { checkEvents(); window.clear(); window.setView(view); window.draw(sprite); window.display(); } } void Window::checkEvents() { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::EventType::Closed: window.close(); break; case sf::Event::EventType::Resized: getLetterboxView(); break; case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Q) { window.close(); } break; default: break; } } } void Window::getLetterboxView() { float windowRatio = window.getSize().x / static_cast<float>(window.getSize().y); float viewRatio = view.getSize().x / static_cast<float>(view.getSize().y); sf::Vector2f size; sf::Vector2f pos; if (windowRatio > viewRatio) { size.x = viewRatio / windowRatio; pos.x = (1 - size.x) / 2.f; size.y = 1; pos.y = 0; } else { size.y = windowRatio / viewRatio; pos.y = (1 - size.y) / 2.f; size.x = 1; pos.x = 0; } view.setViewport(sf::FloatRect(pos.x, pos.y, size.x, size.y)); } <|endoftext|>
<commit_before>/* * Copyright 2008, 2009 Free Software Foundation, Inc. * * This software is distributed under the terms of the GNU Affero Public License. * See the COPYING file in the main directory for details. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. 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/>. */ //#define NDEBUG #include "radioInterface.h" #include <Logger.h> GSM::Time VectorQueue::nextTime() const { GSM::Time retVal; ScopedLock lock(mLock); while (mQ.size()==0) mWriteSignal.wait(mLock); return mQ.top()->time(); } radioVector* VectorQueue::getStaleBurst(const GSM::Time& targTime) { ScopedLock lock(mLock); if ((mQ.size()==0)) { return NULL; } if (mQ.top()->time() < targTime) { radioVector* retVal = mQ.top(); mQ.pop(); return retVal; } return NULL; } radioVector* VectorQueue::getCurrentBurst(const GSM::Time& targTime) { ScopedLock lock(mLock); if ((mQ.size()==0)) { return NULL; } if (mQ.top()->time() == targTime) { radioVector* retVal = mQ.top(); mQ.pop(); return retVal; } return NULL; } RadioInterface::RadioInterface(RadioDevice *wRadio, int wReceiveOffset, int wRadioOversampling, int wTransceiverOversampling, GSM::Time wStartTime) { underrun = false; sendCursor = 0; rcvCursor = 0; mOn = false; mRadio = wRadio; receiveOffset = wReceiveOffset; samplesPerSymbol = wRadioOversampling; mClock.set(wStartTime); loadTest = false; powerScaling = 1.0; } RadioInterface::~RadioInterface(void) { if (rcvBuffer!=NULL) delete rcvBuffer; //mReceiveFIFO.clear(); } double RadioInterface::fullScaleInputValue(void) { return mRadio->fullScaleInputValue(); } double RadioInterface::fullScaleOutputValue(void) { return mRadio->fullScaleOutputValue(); } void RadioInterface::setPowerAttenuation(double atten) { double rfAtten, digAtten; rfAtten = mRadio->setTxGain(mRadio->maxTxGain() - atten); digAtten = atten - rfAtten; if (digAtten < 1.0) powerScaling = 1.0; else powerScaling = 1.0/sqrt(pow(10, (digAtten/10.0))); } short *RadioInterface::radioifyVector(signalVector &wVector, short *retVector, float scale, bool zeroOut) { signalVector::iterator itr = wVector.begin(); short *shortItr = retVector; if (zeroOut) { while (itr < wVector.end()) { *shortItr++ = 0; *shortItr++ = 0; itr++; } } else if (scale != 1.0) { while (itr < wVector.end()) { *shortItr++ = (short) (itr->real() * scale); *shortItr++ = (short) (itr->imag() * scale); itr++; } } else { while (itr < wVector.end()) { *shortItr++ = (short) (itr->real()); *shortItr++ = (short) (itr->imag()); itr++; } } return retVector; } void RadioInterface::unRadioifyVector(short *shortVector, signalVector& newVector) { signalVector::iterator itr = newVector.begin(); short *shortItr = shortVector; while (itr < newVector.end()) { *itr++ = Complex<float>(*shortItr,*(shortItr+1)); //LOG(DEBUG) << (*(itr-1)); shortItr += 2; } } bool started = false; void RadioInterface::pushBuffer(void) { if (sendCursor < 2*INCHUNK*samplesPerSymbol) return; // send resampleVector int samplesWritten = mRadio->writeSamples(sendBuffer, INCHUNK*samplesPerSymbol, &underrun, writeTimestamp); //LOG(DEBUG) << "writeTimestamp: " << writeTimestamp << ", samplesWritten: " << samplesWritten; writeTimestamp += (TIMESTAMP) samplesWritten; if (sendCursor > 2*samplesWritten) memcpy(sendBuffer,sendBuffer+samplesWritten*2,sizeof(short)*2*(sendCursor-2*samplesWritten)); sendCursor = sendCursor - 2*samplesWritten; } void RadioInterface::pullBuffer(void) { bool localUnderrun; // receive receiveVector short* shortVector = rcvBuffer+rcvCursor; //LOG(DEBUG) << "Reading USRP samples at timestamp " << readTimestamp; int samplesRead = mRadio->readSamples(shortVector,OUTCHUNK*samplesPerSymbol,&overrun,readTimestamp,&localUnderrun); underrun |= localUnderrun; readTimestamp += (TIMESTAMP) samplesRead; while (samplesRead < OUTCHUNK*samplesPerSymbol) { int oldSamplesRead = samplesRead; samplesRead += mRadio->readSamples(shortVector+2*samplesRead, OUTCHUNK*samplesPerSymbol-samplesRead, &overrun, readTimestamp, &localUnderrun); underrun |= localUnderrun; readTimestamp += (TIMESTAMP) (samplesRead - oldSamplesRead); } //LOG(DEBUG) << "samplesRead " << samplesRead; rcvCursor += samplesRead*2; } bool RadioInterface::tuneTx(double freq) { return mRadio->setTxFreq(freq); } bool RadioInterface::tuneRx(double freq) { return mRadio->setRxFreq(freq); } void RadioInterface::start() { LOG(INFO) << "starting radio interface..."; mAlignRadioServiceLoopThread.start((void * (*)(void*))AlignRadioServiceLoopAdapter, (void*)this); writeTimestamp = mRadio->initialWriteTimestamp(); readTimestamp = mRadio->initialReadTimestamp(); mRadio->start(); LOG(DEBUG) << "Radio started"; mRadio->updateAlignment(writeTimestamp-10000); mRadio->updateAlignment(writeTimestamp-10000); sendBuffer = new short[2*2*INCHUNK*samplesPerSymbol]; rcvBuffer = new short[2*2*OUTCHUNK*samplesPerSymbol]; mOn = true; } void *AlignRadioServiceLoopAdapter(RadioInterface *radioInterface) { while (1) { radioInterface->alignRadio(); pthread_testcancel(); } return NULL; } void RadioInterface::alignRadio() { sleep(60); mRadio->updateAlignment(writeTimestamp+ (TIMESTAMP) 10000); } void RadioInterface::driveTransmitRadio(signalVector &radioBurst, bool zeroBurst) { if (!mOn) return; radioifyVector(radioBurst, sendBuffer+sendCursor, powerScaling, zeroBurst); sendCursor += (radioBurst.size()*2); pushBuffer(); } void RadioInterface::driveReceiveRadio() { if (!mOn) return; if (mReceiveFIFO.size() > 8) return; pullBuffer(); GSM::Time rcvClock = mClock.get(); rcvClock.decTN(receiveOffset); unsigned tN = rcvClock.TN(); int rcvSz = rcvCursor/2; int readSz = 0; const int symbolsPerSlot = gSlotLen + 8; // while there's enough data in receive buffer, form received // GSM bursts and pass up to Transceiver // Using the 157-156-156-156 symbols per timeslot format. while (rcvSz > (symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol) { signalVector rxVector((symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol); unRadioifyVector(rcvBuffer+readSz*2,rxVector); GSM::Time tmpTime = rcvClock; if (rcvClock.FN() >= 0) { //LOG(DEBUG) << "FN: " << rcvClock.FN(); radioVector *rxBurst = NULL; if (!loadTest) rxBurst = new radioVector(rxVector,tmpTime); else { if (tN % 4 == 0) rxBurst = new radioVector(*finalVec9,tmpTime); else rxBurst = new radioVector(*finalVec,tmpTime); } mReceiveFIFO.put(rxBurst); } mClock.incTN(); rcvClock.incTN(); //if (mReceiveFIFO.size() >= 16) mReceiveFIFO.wait(8); //LOG(DEBUG) << "receiveFIFO: wrote radio vector at time: " << mClock.get() << ", new size: " << mReceiveFIFO.size() ; readSz += (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol; rcvSz -= (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol; tN = rcvClock.TN(); } if (readSz > 0) { memcpy(rcvBuffer,rcvBuffer+2*readSz,sizeof(short)*2*(rcvCursor-readSz)); rcvCursor = rcvCursor-2*readSz; } } <commit_msg>transceiver: fix bug in setting low-level attenuation<commit_after>/* * Copyright 2008, 2009 Free Software Foundation, Inc. * * This software is distributed under the terms of the GNU Affero Public License. * See the COPYING file in the main directory for details. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. 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/>. */ //#define NDEBUG #include "radioInterface.h" #include <Logger.h> GSM::Time VectorQueue::nextTime() const { GSM::Time retVal; ScopedLock lock(mLock); while (mQ.size()==0) mWriteSignal.wait(mLock); return mQ.top()->time(); } radioVector* VectorQueue::getStaleBurst(const GSM::Time& targTime) { ScopedLock lock(mLock); if ((mQ.size()==0)) { return NULL; } if (mQ.top()->time() < targTime) { radioVector* retVal = mQ.top(); mQ.pop(); return retVal; } return NULL; } radioVector* VectorQueue::getCurrentBurst(const GSM::Time& targTime) { ScopedLock lock(mLock); if ((mQ.size()==0)) { return NULL; } if (mQ.top()->time() == targTime) { radioVector* retVal = mQ.top(); mQ.pop(); return retVal; } return NULL; } RadioInterface::RadioInterface(RadioDevice *wRadio, int wReceiveOffset, int wRadioOversampling, int wTransceiverOversampling, GSM::Time wStartTime) { underrun = false; sendCursor = 0; rcvCursor = 0; mOn = false; mRadio = wRadio; receiveOffset = wReceiveOffset; samplesPerSymbol = wRadioOversampling; mClock.set(wStartTime); loadTest = false; powerScaling = 1.0; } RadioInterface::~RadioInterface(void) { if (rcvBuffer!=NULL) delete rcvBuffer; //mReceiveFIFO.clear(); } double RadioInterface::fullScaleInputValue(void) { return mRadio->fullScaleInputValue(); } double RadioInterface::fullScaleOutputValue(void) { return mRadio->fullScaleOutputValue(); } void RadioInterface::setPowerAttenuation(double atten) { double rfGain, digAtten; rfGain = mRadio->setTxGain(mRadio->maxTxGain() - atten); digAtten = atten - mRadio->maxTxGain() + rfGain; if (digAtten < 1.0) powerScaling = 1.0; else powerScaling = 1.0/sqrt(pow(10, (digAtten/10.0))); } short *RadioInterface::radioifyVector(signalVector &wVector, short *retVector, float scale, bool zeroOut) { signalVector::iterator itr = wVector.begin(); short *shortItr = retVector; if (zeroOut) { while (itr < wVector.end()) { *shortItr++ = 0; *shortItr++ = 0; itr++; } } else if (scale != 1.0) { while (itr < wVector.end()) { *shortItr++ = (short) (itr->real() * scale); *shortItr++ = (short) (itr->imag() * scale); itr++; } } else { while (itr < wVector.end()) { *shortItr++ = (short) (itr->real()); *shortItr++ = (short) (itr->imag()); itr++; } } return retVector; } void RadioInterface::unRadioifyVector(short *shortVector, signalVector& newVector) { signalVector::iterator itr = newVector.begin(); short *shortItr = shortVector; while (itr < newVector.end()) { *itr++ = Complex<float>(*shortItr,*(shortItr+1)); //LOG(DEBUG) << (*(itr-1)); shortItr += 2; } } bool started = false; void RadioInterface::pushBuffer(void) { if (sendCursor < 2*INCHUNK*samplesPerSymbol) return; // send resampleVector int samplesWritten = mRadio->writeSamples(sendBuffer, INCHUNK*samplesPerSymbol, &underrun, writeTimestamp); //LOG(DEBUG) << "writeTimestamp: " << writeTimestamp << ", samplesWritten: " << samplesWritten; writeTimestamp += (TIMESTAMP) samplesWritten; if (sendCursor > 2*samplesWritten) memcpy(sendBuffer,sendBuffer+samplesWritten*2,sizeof(short)*2*(sendCursor-2*samplesWritten)); sendCursor = sendCursor - 2*samplesWritten; } void RadioInterface::pullBuffer(void) { bool localUnderrun; // receive receiveVector short* shortVector = rcvBuffer+rcvCursor; //LOG(DEBUG) << "Reading USRP samples at timestamp " << readTimestamp; int samplesRead = mRadio->readSamples(shortVector,OUTCHUNK*samplesPerSymbol,&overrun,readTimestamp,&localUnderrun); underrun |= localUnderrun; readTimestamp += (TIMESTAMP) samplesRead; while (samplesRead < OUTCHUNK*samplesPerSymbol) { int oldSamplesRead = samplesRead; samplesRead += mRadio->readSamples(shortVector+2*samplesRead, OUTCHUNK*samplesPerSymbol-samplesRead, &overrun, readTimestamp, &localUnderrun); underrun |= localUnderrun; readTimestamp += (TIMESTAMP) (samplesRead - oldSamplesRead); } //LOG(DEBUG) << "samplesRead " << samplesRead; rcvCursor += samplesRead*2; } bool RadioInterface::tuneTx(double freq) { return mRadio->setTxFreq(freq); } bool RadioInterface::tuneRx(double freq) { return mRadio->setRxFreq(freq); } void RadioInterface::start() { LOG(INFO) << "starting radio interface..."; mAlignRadioServiceLoopThread.start((void * (*)(void*))AlignRadioServiceLoopAdapter, (void*)this); writeTimestamp = mRadio->initialWriteTimestamp(); readTimestamp = mRadio->initialReadTimestamp(); mRadio->start(); LOG(DEBUG) << "Radio started"; mRadio->updateAlignment(writeTimestamp-10000); mRadio->updateAlignment(writeTimestamp-10000); sendBuffer = new short[2*2*INCHUNK*samplesPerSymbol]; rcvBuffer = new short[2*2*OUTCHUNK*samplesPerSymbol]; mOn = true; } void *AlignRadioServiceLoopAdapter(RadioInterface *radioInterface) { while (1) { radioInterface->alignRadio(); pthread_testcancel(); } return NULL; } void RadioInterface::alignRadio() { sleep(60); mRadio->updateAlignment(writeTimestamp+ (TIMESTAMP) 10000); } void RadioInterface::driveTransmitRadio(signalVector &radioBurst, bool zeroBurst) { if (!mOn) return; radioifyVector(radioBurst, sendBuffer+sendCursor, powerScaling, zeroBurst); sendCursor += (radioBurst.size()*2); pushBuffer(); } void RadioInterface::driveReceiveRadio() { if (!mOn) return; if (mReceiveFIFO.size() > 8) return; pullBuffer(); GSM::Time rcvClock = mClock.get(); rcvClock.decTN(receiveOffset); unsigned tN = rcvClock.TN(); int rcvSz = rcvCursor/2; int readSz = 0; const int symbolsPerSlot = gSlotLen + 8; // while there's enough data in receive buffer, form received // GSM bursts and pass up to Transceiver // Using the 157-156-156-156 symbols per timeslot format. while (rcvSz > (symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol) { signalVector rxVector((symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol); unRadioifyVector(rcvBuffer+readSz*2,rxVector); GSM::Time tmpTime = rcvClock; if (rcvClock.FN() >= 0) { //LOG(DEBUG) << "FN: " << rcvClock.FN(); radioVector *rxBurst = NULL; if (!loadTest) rxBurst = new radioVector(rxVector,tmpTime); else { if (tN % 4 == 0) rxBurst = new radioVector(*finalVec9,tmpTime); else rxBurst = new radioVector(*finalVec,tmpTime); } mReceiveFIFO.put(rxBurst); } mClock.incTN(); rcvClock.incTN(); //if (mReceiveFIFO.size() >= 16) mReceiveFIFO.wait(8); //LOG(DEBUG) << "receiveFIFO: wrote radio vector at time: " << mClock.get() << ", new size: " << mReceiveFIFO.size() ; readSz += (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol; rcvSz -= (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol; tN = rcvClock.TN(); } if (readSz > 0) { memcpy(rcvBuffer,rcvBuffer+2*readSz,sizeof(short)*2*(rcvCursor-readSz)); rcvCursor = rcvCursor-2*readSz; } } <|endoftext|>
<commit_before>#include <allegro.h> #include <iostream> #include <sstream> #include <vector> #include <Python.h> #include "character.h" using namespace std; static int error(const std::string & message){ std::cout << message << std::endl; return -1; } std::string localKeys = "5900"; int enteredState = 0; bool checkKeys(){ if (keypressed()){ int val = readkey(); if ((val & 0xff) >= 48 && (val & 0xff) <= 57){ localKeys += (char)(val & 0xff); } else if ((val & 0xff) == 13){ enteredState = atoi(localKeys.c_str()); localKeys.clear(); return true; } else if ((val & 0xff) == 8){ if (localKeys.size() > 0){ localKeys.erase(localKeys.size()-1); } } } return false; } int main(int argc, char ** argv){ if (argc > 1){ install_allegro(0, NULL, NULL); install_timer(); install_keyboard(); if (set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0) != 0){ error("Couldn't create GFX window"); } Py_Initialize(); /* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */ PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); BITMAP * buffer = create_bitmap(640, 480); try { Character * character = new Character(argv[1]); bool quit = false; while (!quit){ if (key[KEY_ESC]){ quit = true; } character->act(); poll_keyboard(); if (checkKeys()){ // Change state character->changeState(enteredState); } clear_to_color(buffer, makecol(0,0,0)); textprintf_ex(buffer, font, 10, 10, makecol(255, 255, 255), -1, "Loaded Character: %s", character->getName().c_str()); textprintf_ex(buffer, font, 10, 20, makecol(255, 255, 255), -1, "Current State: %d", character->getCurrentStateNumber()); textprintf_ex(buffer, font, 10, 60, makecol(255, 255, 255), -1, "Input new state: %s", localKeys.c_str()); blit(buffer, screen, 0, 0, 0, 0, 640, 480); } delete character; } catch (const PyException & ex){ error("Problem with module! Reason: " + ex.getReason()); } destroy_bitmap(buffer); Py_Finalize(); allegro_exit(); return 0; } std::cout << "Usage: ./test character_module_name" << std::endl; return 0; } END_OF_MAIN() <commit_msg>Allow negative number input.<commit_after>#include <allegro.h> #include <iostream> #include <sstream> #include <vector> #include <Python.h> #include "character.h" using namespace std; static int error(const std::string & message){ std::cout << message << std::endl; return -1; } std::string localKeys = "5900"; int enteredState = 0; bool checkKeys(){ if (keypressed()){ int val = readkey(); if (((val & 0xff) == 45) && localKeys.empty()){ localKeys += (char)(val & 0xff); } else if ((val & 0xff) >= 48 && (val & 0xff) <= 57){ localKeys += (char)(val & 0xff); } else if ((val & 0xff) == 13){ enteredState = atoi(localKeys.c_str()); localKeys.clear(); return true; } else if ((val & 0xff) == 8){ if (localKeys.size() > 0){ localKeys.erase(localKeys.size()-1); } } } return false; } int main(int argc, char ** argv){ if (argc > 1){ install_allegro(0, NULL, NULL); install_timer(); install_keyboard(); if (set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0) != 0){ error("Couldn't create GFX window"); } Py_Initialize(); /* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */ PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); BITMAP * buffer = create_bitmap(640, 480); try { Character * character = new Character(argv[1]); bool quit = false; while (!quit){ if (key[KEY_ESC]){ quit = true; } character->act(); poll_keyboard(); if (checkKeys()){ // Change state character->changeState(enteredState); } clear_to_color(buffer, makecol(0,0,0)); textprintf_ex(buffer, font, 10, 10, makecol(255, 255, 255), -1, "Loaded Character: %s", character->getName().c_str()); textprintf_ex(buffer, font, 10, 20, makecol(255, 255, 255), -1, "Current State: %d", character->getCurrentStateNumber()); textprintf_ex(buffer, font, 10, 60, makecol(255, 255, 255), -1, "Input new state: %s", localKeys.c_str()); blit(buffer, screen, 0, 0, 0, 0, 640, 480); } delete character; } catch (const PyException & ex){ error("Problem with module! Reason: " + ex.getReason()); } destroy_bitmap(buffer); Py_Finalize(); allegro_exit(); return 0; } std::cout << "Usage: ./test character_module_name" << std::endl; return 0; } END_OF_MAIN() <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_POLICY_WORK_STEALING_HPP #define CAF_POLICY_WORK_STEALING_HPP #include <deque> #include <chrono> #include <thread> #include <random> #include <cstddef> #include "caf/resumable.hpp" #include "caf/detail/double_ended_queue.hpp" namespace caf { namespace policy { /// Implements scheduling of actors via work stealing. This implementation uses /// two queues: a synchronized queue accessible by other threads and an internal /// queue. Access to the synchronized queue is minimized. /// The reasoning behind this design decision is that it /// has been shown that stealing actually is very rare for most workloads [1]. /// Hence, implementations should focus on the performance in /// the non-stealing case. For this reason, each worker has an exposed /// job queue that can be accessed by the central scheduler instance as /// well as other workers, but it also has a private job list it is /// currently working on. To account for the load balancing aspect, each /// worker makes sure that at least one job is left in its exposed queue /// to allow other workers to steal it. /// /// [1] http://dl.acm.org/citation.cfm?doid=2398857.2384639 /// /// @extends scheduler_policy class work_stealing { public: // A thead-safe queue implementation. using queue_type = detail::double_ended_queue<resumable>; // The coordinator has only a counter for round-robin enqueue to its workers. struct coordinator_data { std::atomic<size_t> next_worker; inline coordinator_data() : next_worker(0) { // nop } }; // Holds job job queue of a worker and a random number generator. struct worker_data { // This queue is exposed to other workers that may attempt to steal jobs // from it and the central scheduling unit can push new jobs to the queue. queue_type queue; // needed by our engine std::random_device rdevice; // needed to generate pseudo random numbers std::default_random_engine rengine; // initialize random engine inline worker_data() : rdevice(), rengine(rdevice()) { // nop } }; // Convenience function to access the data field. template <class WorkerOrCoordinator> static auto d(WorkerOrCoordinator* self) -> decltype(self->data()) { return self->data(); } // Goes on a raid in quest for a shiny new job. template <class Worker> resumable* try_steal(Worker* self) { auto p = self->parent(); if (p->num_workers() < 2) { // you can't steal from yourself, can you? return nullptr; } size_t victim; do { // roll the dice to pick a victim other than ourselves victim = d(self).rengine() % p->num_workers(); } while (victim == self->id()); // steal oldest element from the victim's queue return d(p->worker_by_id(victim)).queue.take_tail(); } template <class Coordinator> void central_enqueue(Coordinator* self, resumable* job) { auto w = self->worker_by_id(d(self).next_worker++ % self->num_workers()); w->external_enqueue(job); } template <class Worker> void external_enqueue(Worker* self, resumable* job) { d(self).queue.append(job); } template <class Worker> void internal_enqueue(Worker* self, resumable* job) { d(self).queue.prepend(job); } template <class Worker> void resume_job_later(Worker* self, resumable* job) { // job has voluntarily released the CPU to let others run instead // this means we are going to put this job to the very end of our queue d(self).queue.append(job); } template <class Worker> resumable* dequeue(Worker* self) { // we wait for new jobs by polling our external queue: first, we // assume an active work load on the machine and perform aggresive // polling, then we relax our polling a bit and wait 50 us between // dequeue attempts, finally we assume pretty much nothing is going // on and poll every 10 ms; this strategy strives to minimize the // downside of "busy waiting", which still performs much better than a // "signalizing" implementation based on mutexes and conition variables struct poll_strategy { size_t attempts; size_t step_size; size_t steal_interval; std::chrono::microseconds sleep_duration; }; poll_strategy strategies[3] = { // aggressive polling (100x) without sleep interval {100, 1, 10, std::chrono::microseconds{0}}, // moderate polling (500x) with 50 us sleep interval {500, 1, 5, std::chrono::microseconds{50}}, // relaxed polling (infinite attempts) with 10 ms sleep interval {101, 0, 1, std::chrono::microseconds{10000}} }; resumable* job = nullptr; for (auto& strat : strategies) { for (size_t i = 0; i < strat.attempts; i += strat.step_size) { job = d(self).queue.take_head(); if (job) { return job; } // try to steal every X poll attempts if ((i % strat.steal_interval) == 0) { job = try_steal(self); if (job) { return job; } } std::this_thread::sleep_for(strat.sleep_duration); } } // unreachable, because the last strategy loops // until a job has been dequeued return nullptr; } template <class Worker> void before_shutdown(Worker*) { // nop } template <class Worker> void before_resume(Worker*, resumable*) { // nop } template <class Worker> void after_resume(Worker*, resumable*) { // nop } template <class Worker> void after_completion(Worker*, resumable*) { // nop } template <class Worker, class UnaryFunction> void foreach_resumable(Worker* self, UnaryFunction f) { auto next = [&] { return d(self).queue.take_head(); }; for (auto job = next(); job != nullptr; job = next()) { f(job); } } template <class Coordinator, class UnaryFunction> void foreach_central_resumable(Coordinator*, UnaryFunction) { // nop } }; } // namespace policy } // namespace caf #endif // CAF_POLICY_WORK_STEALING_HPP <commit_msg>Improve `policy::work_stealing::try_steal()`<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_POLICY_WORK_STEALING_HPP #define CAF_POLICY_WORK_STEALING_HPP #include <deque> #include <chrono> #include <thread> #include <random> #include <cstddef> #include "caf/resumable.hpp" #include "caf/detail/double_ended_queue.hpp" namespace caf { namespace policy { /// Implements scheduling of actors via work stealing. This implementation uses /// two queues: a synchronized queue accessible by other threads and an internal /// queue. Access to the synchronized queue is minimized. /// The reasoning behind this design decision is that it /// has been shown that stealing actually is very rare for most workloads [1]. /// Hence, implementations should focus on the performance in /// the non-stealing case. For this reason, each worker has an exposed /// job queue that can be accessed by the central scheduler instance as /// well as other workers, but it also has a private job list it is /// currently working on. To account for the load balancing aspect, each /// worker makes sure that at least one job is left in its exposed queue /// to allow other workers to steal it. /// /// [1] http://dl.acm.org/citation.cfm?doid=2398857.2384639 /// /// @extends scheduler_policy class work_stealing { public: // A thead-safe queue implementation. using queue_type = detail::double_ended_queue<resumable>; // The coordinator has only a counter for round-robin enqueue to its workers. struct coordinator_data { std::atomic<size_t> next_worker; inline coordinator_data() : next_worker(0) { // nop } }; // Holds job job queue of a worker and a random number generator. struct worker_data { // This queue is exposed to other workers that may attempt to steal jobs // from it and the central scheduling unit can push new jobs to the queue. queue_type queue; // needed by our engine std::random_device rdevice; // needed to generate pseudo random numbers std::default_random_engine rengine; // initialize random engine inline worker_data() : rdevice(), rengine(rdevice()) { // nop } }; // Convenience function to access the data field. template <class WorkerOrCoordinator> static auto d(WorkerOrCoordinator* self) -> decltype(self->data()) { return self->data(); } // Goes on a raid in quest for a shiny new job. template <class Worker> resumable* try_steal(Worker* self) { auto p = self->parent(); if (p->num_workers() < 2) { // you can't steal from yourself, can you? return nullptr; } // roll the dice to pick a victim other than ourselves size_t victim = d(self).rengine() % (p->num_workers() - 1); if (victim == self->id()) victim = p->num_workers() - 1; // steal oldest element from the victim's queue return d(p->worker_by_id(victim)).queue.take_tail(); } template <class Coordinator> void central_enqueue(Coordinator* self, resumable* job) { auto w = self->worker_by_id(d(self).next_worker++ % self->num_workers()); w->external_enqueue(job); } template <class Worker> void external_enqueue(Worker* self, resumable* job) { d(self).queue.append(job); } template <class Worker> void internal_enqueue(Worker* self, resumable* job) { d(self).queue.prepend(job); } template <class Worker> void resume_job_later(Worker* self, resumable* job) { // job has voluntarily released the CPU to let others run instead // this means we are going to put this job to the very end of our queue d(self).queue.append(job); } template <class Worker> resumable* dequeue(Worker* self) { // we wait for new jobs by polling our external queue: first, we // assume an active work load on the machine and perform aggresive // polling, then we relax our polling a bit and wait 50 us between // dequeue attempts, finally we assume pretty much nothing is going // on and poll every 10 ms; this strategy strives to minimize the // downside of "busy waiting", which still performs much better than a // "signalizing" implementation based on mutexes and conition variables struct poll_strategy { size_t attempts; size_t step_size; size_t steal_interval; std::chrono::microseconds sleep_duration; }; poll_strategy strategies[3] = { // aggressive polling (100x) without sleep interval {100, 1, 10, std::chrono::microseconds{0}}, // moderate polling (500x) with 50 us sleep interval {500, 1, 5, std::chrono::microseconds{50}}, // relaxed polling (infinite attempts) with 10 ms sleep interval {101, 0, 1, std::chrono::microseconds{10000}} }; resumable* job = nullptr; for (auto& strat : strategies) { for (size_t i = 0; i < strat.attempts; i += strat.step_size) { job = d(self).queue.take_head(); if (job) { return job; } // try to steal every X poll attempts if ((i % strat.steal_interval) == 0) { job = try_steal(self); if (job) { return job; } } std::this_thread::sleep_for(strat.sleep_duration); } } // unreachable, because the last strategy loops // until a job has been dequeued return nullptr; } template <class Worker> void before_shutdown(Worker*) { // nop } template <class Worker> void before_resume(Worker*, resumable*) { // nop } template <class Worker> void after_resume(Worker*, resumable*) { // nop } template <class Worker> void after_completion(Worker*, resumable*) { // nop } template <class Worker, class UnaryFunction> void foreach_resumable(Worker* self, UnaryFunction f) { auto next = [&] { return d(self).queue.take_head(); }; for (auto job = next(); job != nullptr; job = next()) { f(job); } } template <class Coordinator, class UnaryFunction> void foreach_central_resumable(Coordinator*, UnaryFunction) { // nop } }; } // namespace policy } // namespace caf #endif // CAF_POLICY_WORK_STEALING_HPP <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <[email protected]> // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Path.h" #include "clang/Sema/Sema.h" #include "clang/Basic/Diagnostic.h" #include "clang/AST/AST.h" #include "clang/AST/ASTContext.h" // for operator new[](unsigned long, ASTCtx..) #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/DeclVisitor.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/AutoloadCallback.h" #include "cling/Interpreter/Transaction.h" namespace { static const char annoTag[] = "$clingAutoload$"; static const size_t lenAnnoTag = sizeof(annoTag) - 1; } using namespace clang; namespace cling { void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name, llvm::StringRef header) { Sema& sema= m_Interpreter->getSema(); unsigned id = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning, "Note: '%0' can be found in %1"); /* unsigned idn //TODO: To be enabled after we have a way to get the full path = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note, "Type : %0 , Full Path: %1")*/; if (header.startswith(llvm::StringRef(annoTag, lenAnnoTag))) sema.Diags.Report(l, id) << name << header.drop_front(lenAnnoTag); } bool AutoloadCallback::LookupObject (TagDecl *t) { if (m_ShowSuggestions && t->hasAttr<AnnotateAttr>()) report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation()); return false; } class AutoloadingVisitor: public RecursiveASTVisitor<AutoloadingVisitor> { private: ///\brief Flag determining the visitor's actions. If true, register autoload /// entries, i.e. remember the connection between filename and the declaration /// that needs to be updated on #include of the filename. /// If false, react on an #include by adjusting the forward decls, e.g. by /// removing the default tremplate arguments (that will now be provided by /// the definition read from the include) and by removing enum declarations /// that would otherwise be duplicates. bool m_IsStoringState; AutoloadCallback::FwdDeclsMap* m_Map; clang::Preprocessor* m_PP; const clang::FileEntry* m_PrevFE; std::string m_PrevFileName; private: void InsertIntoAutoloadingState (Decl* decl, llvm::StringRef annotation) { assert(!annotation.empty() && "Empty annotation!"); if (!annotation.startswith(llvm::StringRef(annoTag, lenAnnoTag))) { // not an autoload annotation. return; } assert(m_PP); const FileEntry* FE = 0; SourceLocation fileNameLoc; bool isAngled = false; const DirectoryLookup* LookupFrom = 0; const DirectoryLookup* CurDir = 0; llvm::StringRef FileName = annotation.drop_front(lenAnnoTag); if (FileName.equals(m_PrevFileName)) FE = m_PrevFE; else { FE = m_PP->LookupFile(fileNameLoc, FileName, isAngled, LookupFrom, CurDir, /*SearchPath*/0, /*RelativePath*/ 0, /*suggestedModule*/0, /*SkipCache*/ false, /*OpenFile*/ false, /*CacheFail*/ true); m_PrevFE = FE; m_PrevFileName = FileName; } assert(FE && "Must have a valid FileEntry"); if (FE) { auto& Vec = (*m_Map)[FE]; Vec.push_back(decl); } } public: AutoloadingVisitor(): m_IsStoringState(false), m_Map(0), m_PP(0), m_PrevFE(0) {} void RemoveDefaultArgsOf(Decl* D) { //D = D->getMostRecentDecl(); TraverseDecl(D); //while ((D = D->getPreviousDecl())) // TraverseDecl(D); } void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map, Preprocessor& PP) { m_IsStoringState = true; m_Map = &map; m_PP = &PP; TraverseDecl(D); m_PP = 0; m_Map = 0; m_IsStoringState = false; } bool shouldVisitTemplateInstantiations() { return true; } bool VisitDecl(Decl* D) { if (!m_IsStoringState) return true; if (!D->hasAttr<AnnotateAttr>()) return true; AnnotateAttr* attr = D->getAttr<AnnotateAttr>(); if (!attr) return true; switch (D->getKind()) { default: InsertIntoAutoloadingState(D, attr->getAnnotation()); break; case Decl::Enum: // EnumDecls have extra information 2 chars after the filename used // for extra fixups. EnumDecl* ED = cast<EnumDecl>(D); if (ED->isFixed()) { StringRef str = ED->getAttr<AnnotateAttr>()->getAnnotation(); char ch = str.back(); // str.drop_back(2); ED->getAttr<AnnotateAttr>()->setAnnotation(ED->getASTContext(), str); struct EnumDeclDerived: public EnumDecl { static void setFixed(EnumDecl* ED, bool value = true) { ((EnumDeclDerived*)ED)->IsFixed = value; } }; if (ch != '1') EnumDeclDerived::setFixed(ED, false); } InsertIntoAutoloadingState(D, attr->getAnnotation().drop_back(2)); break; } return true; } bool VisitCXXRecordDecl(CXXRecordDecl* D) { if (!D->hasAttr<AnnotateAttr>()) return true; VisitDecl(D); if (ClassTemplateDecl* TmplD = D->getDescribedClassTemplate()) return VisitTemplateDecl(TmplD); return true; } bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitTemplateDecl(TemplateDecl* D) { if (D->getTemplatedDecl() && !D->getTemplatedDecl()->hasAttr<AnnotateAttr>()) return true; VisitDecl(D); // If we have a definition we might be about to re-#include the // same header containing definition that was #included previously, // i.e. we might have multiple fwd decls for the same template. // DO NOT remove the defaults here; the definition needs to keep it. // (ROOT-7037) if (ClassTemplateDecl* CTD = dyn_cast<ClassTemplateDecl>(D)) if (CXXRecordDecl* TemplatedD = CTD->getTemplatedDecl()) if (TemplatedD->getDefinition()) return true; for(auto P: D->getTemplateParameters()->asArray()) TraverseDecl(P); return true; } bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitParmVarDecl(ParmVarDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArg()) D->setDefaultArg(nullptr); return true; } }; void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc, const clang::Token &IncludeTok, llvm::StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, const clang::FileEntry *File, llvm::StringRef SearchPath, llvm::StringRef RelativePath, const clang::Module *Imported) { // If File is 0 this means that the #included file doesn't exist. if (!File) return; auto found = m_Map.find(File); if (found == m_Map.end()) return; // nothing to do, file not referred in any annotation AutoloadingVisitor defaultArgsCleaner; for (auto D : found->second) { defaultArgsCleaner.RemoveDefaultArgsOf(D); } // Don't need to keep track of cleaned up decls from file. m_Map.erase(found); } AutoloadCallback::~AutoloadCallback() { } void AutoloadCallback::TransactionCommitted(const Transaction &T) { if (T.decls_begin() == T.decls_end()) return; if (T.decls_begin()->m_DGR.isNull()) return; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { AutoloadingVisitor defaultArgsStateCollector; Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor(); for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; // if (DCI.m_Call != Transaction::kCCIHandleTopLevelDecl) // continue; if (DCI.m_DGR.isNull()) continue; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; for (DeclGroupRef::iterator J = DCI.m_DGR.begin(), JE = DCI.m_DGR.end(); J != JE; ++J) { defaultArgsStateCollector.TrackDefaultArgStateOf(*J, m_Map, PP); } } } } } } } //end namespace cling <commit_msg>Follow interface change.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <[email protected]> // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Path.h" #include "clang/Sema/Sema.h" #include "clang/Basic/Diagnostic.h" #include "clang/AST/AST.h" #include "clang/AST/ASTContext.h" // for operator new[](unsigned long, ASTCtx..) #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/DeclVisitor.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/AutoloadCallback.h" #include "cling/Interpreter/Transaction.h" namespace { static const char annoTag[] = "$clingAutoload$"; static const size_t lenAnnoTag = sizeof(annoTag) - 1; } using namespace clang; namespace cling { void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name, llvm::StringRef header) { Sema& sema= m_Interpreter->getSema(); unsigned id = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning, "Note: '%0' can be found in %1"); /* unsigned idn //TODO: To be enabled after we have a way to get the full path = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note, "Type : %0 , Full Path: %1")*/; if (header.startswith(llvm::StringRef(annoTag, lenAnnoTag))) sema.Diags.Report(l, id) << name << header.drop_front(lenAnnoTag); } bool AutoloadCallback::LookupObject (TagDecl *t) { if (m_ShowSuggestions && t->hasAttr<AnnotateAttr>()) report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation()); return false; } class AutoloadingVisitor: public RecursiveASTVisitor<AutoloadingVisitor> { private: ///\brief Flag determining the visitor's actions. If true, register autoload /// entries, i.e. remember the connection between filename and the declaration /// that needs to be updated on #include of the filename. /// If false, react on an #include by adjusting the forward decls, e.g. by /// removing the default tremplate arguments (that will now be provided by /// the definition read from the include) and by removing enum declarations /// that would otherwise be duplicates. bool m_IsStoringState; AutoloadCallback::FwdDeclsMap* m_Map; clang::Preprocessor* m_PP; const clang::FileEntry* m_PrevFE; std::string m_PrevFileName; private: void InsertIntoAutoloadingState (Decl* decl, llvm::StringRef annotation) { assert(!annotation.empty() && "Empty annotation!"); if (!annotation.startswith(llvm::StringRef(annoTag, lenAnnoTag))) { // not an autoload annotation. return; } assert(m_PP); const FileEntry* FE = 0; SourceLocation fileNameLoc; bool isAngled = false; const DirectoryLookup* FromDir = 0; const FileEntry* FromFile = 0; const DirectoryLookup* CurDir = 0; llvm::StringRef FileName = annotation.drop_front(lenAnnoTag); if (FileName.equals(m_PrevFileName)) FE = m_PrevFE; else { FE = m_PP->LookupFile(fileNameLoc, FileName, isAngled, FromDir, FromFile, CurDir, /*SearchPath*/0, /*RelativePath*/ 0, /*suggestedModule*/0, /*SkipCache*/ false, /*OpenFile*/ false, /*CacheFail*/ true); m_PrevFE = FE; m_PrevFileName = FileName; } assert(FE && "Must have a valid FileEntry"); if (FE) { auto& Vec = (*m_Map)[FE]; Vec.push_back(decl); } } public: AutoloadingVisitor(): m_IsStoringState(false), m_Map(0), m_PP(0), m_PrevFE(0) {} void RemoveDefaultArgsOf(Decl* D) { //D = D->getMostRecentDecl(); TraverseDecl(D); //while ((D = D->getPreviousDecl())) // TraverseDecl(D); } void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map, Preprocessor& PP) { m_IsStoringState = true; m_Map = &map; m_PP = &PP; TraverseDecl(D); m_PP = 0; m_Map = 0; m_IsStoringState = false; } bool shouldVisitTemplateInstantiations() { return true; } bool VisitDecl(Decl* D) { if (!m_IsStoringState) return true; if (!D->hasAttr<AnnotateAttr>()) return true; AnnotateAttr* attr = D->getAttr<AnnotateAttr>(); if (!attr) return true; switch (D->getKind()) { default: InsertIntoAutoloadingState(D, attr->getAnnotation()); break; case Decl::Enum: // EnumDecls have extra information 2 chars after the filename used // for extra fixups. EnumDecl* ED = cast<EnumDecl>(D); if (ED->isFixed()) { StringRef str = ED->getAttr<AnnotateAttr>()->getAnnotation(); char ch = str.back(); // str.drop_back(2); ED->getAttr<AnnotateAttr>()->setAnnotation(ED->getASTContext(), str); struct EnumDeclDerived: public EnumDecl { static void setFixed(EnumDecl* ED, bool value = true) { ((EnumDeclDerived*)ED)->IsFixed = value; } }; if (ch != '1') EnumDeclDerived::setFixed(ED, false); } InsertIntoAutoloadingState(D, attr->getAnnotation().drop_back(2)); break; } return true; } bool VisitCXXRecordDecl(CXXRecordDecl* D) { if (!D->hasAttr<AnnotateAttr>()) return true; VisitDecl(D); if (ClassTemplateDecl* TmplD = D->getDescribedClassTemplate()) return VisitTemplateDecl(TmplD); return true; } bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitTemplateDecl(TemplateDecl* D) { if (D->getTemplatedDecl() && !D->getTemplatedDecl()->hasAttr<AnnotateAttr>()) return true; VisitDecl(D); // If we have a definition we might be about to re-#include the // same header containing definition that was #included previously, // i.e. we might have multiple fwd decls for the same template. // DO NOT remove the defaults here; the definition needs to keep it. // (ROOT-7037) if (ClassTemplateDecl* CTD = dyn_cast<ClassTemplateDecl>(D)) if (CXXRecordDecl* TemplatedD = CTD->getTemplatedDecl()) if (TemplatedD->getDefinition()) return true; for(auto P: D->getTemplateParameters()->asArray()) TraverseDecl(P); return true; } bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitParmVarDecl(ParmVarDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArg()) D->setDefaultArg(nullptr); return true; } }; void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc, const clang::Token &IncludeTok, llvm::StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, const clang::FileEntry *File, llvm::StringRef SearchPath, llvm::StringRef RelativePath, const clang::Module *Imported) { // If File is 0 this means that the #included file doesn't exist. if (!File) return; auto found = m_Map.find(File); if (found == m_Map.end()) return; // nothing to do, file not referred in any annotation AutoloadingVisitor defaultArgsCleaner; for (auto D : found->second) { defaultArgsCleaner.RemoveDefaultArgsOf(D); } // Don't need to keep track of cleaned up decls from file. m_Map.erase(found); } AutoloadCallback::~AutoloadCallback() { } void AutoloadCallback::TransactionCommitted(const Transaction &T) { if (T.decls_begin() == T.decls_end()) return; if (T.decls_begin()->m_DGR.isNull()) return; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { AutoloadingVisitor defaultArgsStateCollector; Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor(); for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; // if (DCI.m_Call != Transaction::kCCIHandleTopLevelDecl) // continue; if (DCI.m_DGR.isNull()) continue; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; for (DeclGroupRef::iterator J = DCI.m_DGR.begin(), JE = DCI.m_DGR.end(); J != JE; ++J) { defaultArgsStateCollector.TrackDefaultArgStateOf(*J, m_Map, PP); } } } } } } } //end namespace cling <|endoftext|>
<commit_before>#include <X11/Xlib.h> #include <include/wrapper/cef_helpers.h> #include <include/cef_app.h> #include <unistd.h> #include <gdk/gdkx.h> #include "brick_app.h" #include "third-party/json/json.h" #include "status_icon/status_icon.h" #include "cef_handler.h" #include "cef_app.h" #include "window_util.h" #include "helper.h" #undef Status // Definition conflicts with cef_urlrequest.h #undef Success // Definition conflicts with cef_message_router.h namespace { std::string APPICONS[] = {"brick16.png", "brick32.png", "brick48.png", "brick128.png", "brick256.png"}; std::string szWorkingDir; // The current working directory bool GetWorkingDir(std::string& dir) { char buff[1024]; // Retrieve the executable path. ssize_t len = readlink("/proc/self/exe", buff, sizeof(buff)-1); if (len == -1) return false; buff[len] = 0; dir = std::string(buff); // Remove the executable name from the path. dir = dir.substr(0, dir.find_last_of("/")); return true; } } // static const char* BrickApp::GetConfigHome() { return g_get_user_config_dir(); } // static const char* BrickApp::GetCacheHome() { return g_get_user_cache_dir(); } void TerminationSignalHandler(int signatl) { CefQuitMessageLoop(); } int main(int argc, char* argv[]) { CefMainArgs main_args(argc, argv); CefRefPtr<ClientApp> app(new ClientApp); // Execute the secondary process, if any. int exit_code = CefExecuteProcess(main_args, app.get(), NULL); if (exit_code >= 0) return exit_code; GetWorkingDir(szWorkingDir); std::string plain_config = BrickApp::GetConfig(); AppSettings app_settings = AppSettings::InitByJson(plain_config); app_settings.resource_dir = helper::BaseDir(szWorkingDir) + "/resources/"; CefRefPtr<AccountManager> account_manager(new AccountManager); // ToDo: Fix this bulhit! account_manager->Init( std::string(BrickApp::GetConfigHome()) + "/" + APP_COMMON_NAME + "/accounts.json" ); // Initialize CEF. CefInitialize(main_args, BrickApp::GetCefSettings(szWorkingDir, app_settings), app.get(), NULL); // Create the handler. CefRefPtr<ClientHandler> client_handler(new ClientHandler); // Set default windows icon. Important to do this before any GTK window created! GList *list = NULL; std::string icon_path = app_settings.resource_dir + "/app_icons/"; int icons_count = sizeof(APPICONS) / sizeof(APPICONS[0]); for (int i = 0; i < icons_count; ++i) { GdkPixbuf *icon = gdk_pixbuf_new_from_file((icon_path + APPICONS[i]).c_str(), NULL); if (!icon) continue; list = g_list_append(list, icon); } gtk_window_set_default_icon_list(list); g_list_foreach(list, (GFunc) g_object_unref, NULL); g_list_free(list); // Initialize main window CefRefPtr<MainWindow> main_window(new MainWindow); main_window->Init(); main_window->SetTitle(APP_NAME); main_window->Show(); client_handler->SetAppSettings(app_settings); client_handler->SetMainWindowHandle(main_window); client_handler->SetAccountManager(account_manager); // Initialize status icon CefRefPtr<StatusIcon> status_icon(new StatusIcon(app_settings.resource_dir + "/indicators/")); client_handler->SetStatusIconHandle(status_icon); CefWindowInfo window_info; // The GTK window must be visible before we can retrieve the XID. ::Window xwindow = GDK_WINDOW_XID(gtk_widget_get_window(main_window->GetHandler())); window_info.SetAsChild(xwindow, CefRect(0, 0, 0, 0)); window_util::SetLeaderWindow(xwindow); window_util::InitWindow(xwindow); window_util::InitHooks(); std::string startup_url = account_manager->GetCurrentAccount()->GetBaseUrl(); if (account_manager->GetCurrentAccount()->IsExisted()) { // Login to our account startup_url += "internals/pages/portal-loader#login=yes"; } else { // Otherwise let's show error page startup_url += "internals/pages/home"; } // Create browser CefBrowserHost::CreateBrowserSync( window_info, client_handler.get(), startup_url, BrickApp::GetBrowserSettings(szWorkingDir, app_settings), NULL); // Install a signal handler so we clean up after ourselves. signal(SIGINT, TerminationSignalHandler); signal(SIGTERM, TerminationSignalHandler); CefRunMessageLoop(); CefShutdown(); return 0; } <commit_msg>Fixed misprinted<commit_after>#include <X11/Xlib.h> #include <include/wrapper/cef_helpers.h> #include <include/cef_app.h> #include <unistd.h> #include <gdk/gdkx.h> #include "brick_app.h" #include "third-party/json/json.h" #include "status_icon/status_icon.h" #include "cef_handler.h" #include "cef_app.h" #include "window_util.h" #include "helper.h" #undef Status // Definition conflicts with cef_urlrequest.h #undef Success // Definition conflicts with cef_message_router.h namespace { std::string APPICONS[] = {"brick16.png", "brick32.png", "brick48.png", "brick128.png", "brick256.png"}; std::string szWorkingDir; // The current working directory bool GetWorkingDir(std::string& dir) { char buff[1024]; // Retrieve the executable path. ssize_t len = readlink("/proc/self/exe", buff, sizeof(buff)-1); if (len == -1) return false; buff[len] = 0; dir = std::string(buff); // Remove the executable name from the path. dir = dir.substr(0, dir.find_last_of("/")); return true; } } // static const char* BrickApp::GetConfigHome() { return g_get_user_config_dir(); } // static const char* BrickApp::GetCacheHome() { return g_get_user_cache_dir(); } void TerminationSignalHandler(int signatl) { CefQuitMessageLoop(); } int main(int argc, char* argv[]) { CefMainArgs main_args(argc, argv); CefRefPtr<ClientApp> app(new ClientApp); // Execute the secondary process, if any. int exit_code = CefExecuteProcess(main_args, app.get(), NULL); if (exit_code >= 0) return exit_code; GetWorkingDir(szWorkingDir); std::string plain_config = BrickApp::GetConfig(); AppSettings app_settings = AppSettings::InitByJson(plain_config); app_settings.resource_dir = helper::BaseDir(szWorkingDir) + "/resources/"; CefRefPtr<AccountManager> account_manager(new AccountManager); // ToDo: Fix this bullshit! account_manager->Init( std::string(BrickApp::GetConfigHome()) + "/" + APP_COMMON_NAME + "/accounts.json" ); // Initialize CEF. CefInitialize(main_args, BrickApp::GetCefSettings(szWorkingDir, app_settings), app.get(), NULL); // Create the handler. CefRefPtr<ClientHandler> client_handler(new ClientHandler); // Set default windows icon. Important to do this before any GTK window created! GList *list = NULL; std::string icon_path = app_settings.resource_dir + "/app_icons/"; int icons_count = sizeof(APPICONS) / sizeof(APPICONS[0]); for (int i = 0; i < icons_count; ++i) { GdkPixbuf *icon = gdk_pixbuf_new_from_file((icon_path + APPICONS[i]).c_str(), NULL); if (!icon) continue; list = g_list_append(list, icon); } gtk_window_set_default_icon_list(list); g_list_foreach(list, (GFunc) g_object_unref, NULL); g_list_free(list); // Initialize main window CefRefPtr<MainWindow> main_window(new MainWindow); main_window->Init(); main_window->SetTitle(APP_NAME); main_window->Show(); client_handler->SetAppSettings(app_settings); client_handler->SetMainWindowHandle(main_window); client_handler->SetAccountManager(account_manager); // Initialize status icon CefRefPtr<StatusIcon> status_icon(new StatusIcon(app_settings.resource_dir + "/indicators/")); client_handler->SetStatusIconHandle(status_icon); CefWindowInfo window_info; // The GTK window must be visible before we can retrieve the XID. ::Window xwindow = GDK_WINDOW_XID(gtk_widget_get_window(main_window->GetHandler())); window_info.SetAsChild(xwindow, CefRect(0, 0, 0, 0)); window_util::SetLeaderWindow(xwindow); window_util::InitWindow(xwindow); window_util::InitHooks(); std::string startup_url = account_manager->GetCurrentAccount()->GetBaseUrl(); if (account_manager->GetCurrentAccount()->IsExisted()) { // Login to our account startup_url += "internals/pages/portal-loader#login=yes"; } else { // Otherwise let's show error page startup_url += "internals/pages/home"; } // Create browser CefBrowserHost::CreateBrowserSync( window_info, client_handler.get(), startup_url, BrickApp::GetBrowserSettings(szWorkingDir, app_settings), NULL); // Install a signal handler so we clean up after ourselves. signal(SIGINT, TerminationSignalHandler); signal(SIGTERM, TerminationSignalHandler); CefRunMessageLoop(); CefShutdown(); return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2017-2018 Jonathan Müller <[email protected]> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #include <cppast/cpp_entity_index.hpp> #include <cppast/detail/assert.hpp> #include <cppast/cpp_entity.hpp> #include <cppast/cpp_entity_kind.hpp> #include <cppast/cpp_file.hpp> using namespace cppast; cpp_entity_index::duplicate_definition_error::duplicate_definition_error() : std::logic_error("duplicate registration of entity definition") { } void cpp_entity_index::register_definition(cpp_entity_id id, type_safe::object_ref<const cpp_entity> entity) const { DEBUG_ASSERT(entity->kind() != cpp_entity_kind::namespace_t, detail::precondition_error_handler{}, "must not be a namespace"); std::lock_guard<std::mutex> lock(mutex_); auto result = map_.emplace(std::move(id), value(entity, true)); if (!result.second) { // already in map, override declaration auto& value = result.first->second; if (value.is_definition) throw duplicate_definition_error(); value.is_definition = true; value.entity = entity; } } bool cpp_entity_index::register_file(cpp_entity_id id, type_safe::object_ref<const cpp_file> file) const { std::lock_guard<std::mutex> lock(mutex_); return map_.emplace(std::move(id), value(file, true)).second; } void cpp_entity_index::register_forward_declaration( cpp_entity_id id, type_safe::object_ref<const cpp_entity> entity) const { std::lock_guard<std::mutex> lock(mutex_); map_.emplace(std::move(id), value(entity, false)); } void cpp_entity_index::register_namespace(cpp_entity_id id, type_safe::object_ref<const cpp_namespace> ns) const { std::lock_guard<std::mutex> lock(mutex_); ns_[std::move(id)].push_back(ns); } type_safe::optional_ref<const cpp_entity> cpp_entity_index::lookup(const cpp_entity_id& id) const noexcept { std::lock_guard<std::mutex> lock(mutex_); auto iter = map_.find(id); if (iter == map_.end()) return {}; return type_safe::ref(iter->second.entity.get()); } type_safe::optional_ref<const cpp_entity> cpp_entity_index::lookup_definition( const cpp_entity_id& id) const noexcept { std::lock_guard<std::mutex> lock(mutex_); auto iter = map_.find(id); if (iter == map_.end() || !iter->second.is_definition) return {}; return type_safe::ref(iter->second.entity.get()); } auto cpp_entity_index::lookup_namespace(const cpp_entity_id& id) const noexcept -> type_safe::array_ref<type_safe::object_ref<const cpp_namespace>> { std::lock_guard<std::mutex> lock(mutex_); auto iter = ns_.find(id); if (iter == ns_.end()) return nullptr; auto& vec = iter->second; return type_safe::ref(vec.data(), vec.size()); } <commit_msg>ThirdParty: Disable cppast error as it is benign in this case.<commit_after>// Copyright (C) 2017-2018 Jonathan Müller <[email protected]> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #include <cppast/cpp_entity_index.hpp> #include <cppast/detail/assert.hpp> #include <cppast/cpp_entity.hpp> #include <cppast/cpp_entity_kind.hpp> #include <cppast/cpp_file.hpp> using namespace cppast; cpp_entity_index::duplicate_definition_error::duplicate_definition_error() : std::logic_error("duplicate registration of entity definition") { } void cpp_entity_index::register_definition(cpp_entity_id id, type_safe::object_ref<const cpp_entity> entity) const { DEBUG_ASSERT(entity->kind() != cpp_entity_kind::namespace_t, detail::precondition_error_handler{}, "must not be a namespace"); std::lock_guard<std::mutex> lock(mutex_); auto result = map_.emplace(std::move(id), value(entity, true)); if (!result.second) { // already in map, override declaration auto& value = result.first->second; // Urho3D: Few files trigger this error for some reason. It is ok to ignore in this case. // if (value.is_definition) // throw duplicate_definition_error(); value.is_definition = true; value.entity = entity; } } bool cpp_entity_index::register_file(cpp_entity_id id, type_safe::object_ref<const cpp_file> file) const { std::lock_guard<std::mutex> lock(mutex_); return map_.emplace(std::move(id), value(file, true)).second; } void cpp_entity_index::register_forward_declaration( cpp_entity_id id, type_safe::object_ref<const cpp_entity> entity) const { std::lock_guard<std::mutex> lock(mutex_); map_.emplace(std::move(id), value(entity, false)); } void cpp_entity_index::register_namespace(cpp_entity_id id, type_safe::object_ref<const cpp_namespace> ns) const { std::lock_guard<std::mutex> lock(mutex_); ns_[std::move(id)].push_back(ns); } type_safe::optional_ref<const cpp_entity> cpp_entity_index::lookup(const cpp_entity_id& id) const noexcept { std::lock_guard<std::mutex> lock(mutex_); auto iter = map_.find(id); if (iter == map_.end()) return {}; return type_safe::ref(iter->second.entity.get()); } type_safe::optional_ref<const cpp_entity> cpp_entity_index::lookup_definition( const cpp_entity_id& id) const noexcept { std::lock_guard<std::mutex> lock(mutex_); auto iter = map_.find(id); if (iter == map_.end() || !iter->second.is_definition) return {}; return type_safe::ref(iter->second.entity.get()); } auto cpp_entity_index::lookup_namespace(const cpp_entity_id& id) const noexcept -> type_safe::array_ref<type_safe::object_ref<const cpp_namespace>> { std::lock_guard<std::mutex> lock(mutex_); auto iter = ns_.find(id); if (iter == ns_.end()) return nullptr; auto& vec = iter->second; return type_safe::ref(vec.data(), vec.size()); } <|endoftext|>
<commit_before>// Copyright 2015 Headcrash Industries LLC. All Rights Reserved. #include "VlcMediaPCH.h" #include "Vlc.h" #include "VlcMediaPlayer.h" #include "VlcMediaUtils.h" /* FVlcMediaPlayer structors *****************************************************************************/ FVlcMediaPlayer::FVlcMediaPlayer(FLibvlcInstance* InVlcInstance) : CurrentTime(FTimespan::Zero()) , DesiredRate(0.0) , LastPlatformSeconds(0.0) , MediaSource(InVlcInstance) , Player(nullptr) , ShouldLoop(false) { } FVlcMediaPlayer::~FVlcMediaPlayer() { Close(); } /* FTickerObjectBase interface *****************************************************************************/ bool FVlcMediaPlayer::Tick(float DeltaTime) { if (Player == nullptr) { return true; } // interpolate time, because FVlc::MediaPlayerGetTime is too low-res if (FVlc::MediaPlayerGetState(Player) == ELibvlcState::Playing) { double PlatformSeconds = FPlatformTime::Seconds(); CurrentTime += FTimespan::FromSeconds(DesiredRate * (PlatformSeconds - LastPlatformSeconds)); LastPlatformSeconds = PlatformSeconds; } // process events ELibvlcEventType Event; while (Events.Dequeue(Event)) { switch (Event) { case ELibvlcEventType::MediaParsedChanged: MediaEvent.Broadcast(EMediaEvent::TracksChanged); break; case ELibvlcEventType::MediaPlayerEndReached: // begin hack: this causes a short delay, but there seems to be no // other way. looping via VLC Media List players is also broken :( FVlc::MediaPlayerStop(Player); // end hack if (ShouldLoop && (DesiredRate != 0.0f)) { SetRate(DesiredRate); } MediaEvent.Broadcast(EMediaEvent::PlaybackSuspended); MediaEvent.Broadcast(EMediaEvent::PlaybackEndReached); break; case ELibvlcEventType::MediaPlayerPaused: LastPlatformSeconds = FPlatformTime::Seconds(); MediaEvent.Broadcast(EMediaEvent::PlaybackSuspended); break; case ELibvlcEventType::MediaPlayerPlaying: LastPlatformSeconds = FPlatformTime::Seconds(); MediaEvent.Broadcast(EMediaEvent::PlaybackResumed); break; case ELibvlcEventType::MediaPlayerPositionChanged: CurrentTime = FTimespan::FromMilliseconds(FMath::Max<int64>(0, FVlc::MediaPlayerGetTime(Player))); LastPlatformSeconds = FPlatformTime::Seconds(); break; default: continue; } } return true; } /* IMediaControls interface *****************************************************************************/ FTimespan FVlcMediaPlayer::GetDuration() const { if (Player == nullptr) { return FTimespan::Zero(); } int64 Length = FVlc::MediaPlayerGetLength(Player); if (Length <= 0) { return GetTime(); } return FTimespan::FromMilliseconds(Length); } float FVlcMediaPlayer::GetRate() const { if ((Player == nullptr) || (FVlc::MediaPlayerGetState(Player) != ELibvlcState::Playing)) { return 0.0f; } return FVlc::MediaPlayerGetRate(Player); } EMediaState FVlcMediaPlayer::GetState() const { if (Player == nullptr) { return EMediaState::Closed; } ELibvlcState State = FVlc::MediaPlayerGetState(Player); switch (State) { case ELibvlcState::Error: return EMediaState::Error; case ELibvlcState::Buffering: case ELibvlcState::Opening: return EMediaState::Preparing; case ELibvlcState::Paused: return EMediaState::Paused; case ELibvlcState::Playing: return EMediaState::Playing; case ELibvlcState::Ended: case ELibvlcState::NothingSpecial: case ELibvlcState::Stopped: return EMediaState::Stopped; } return EMediaState::Error; // should never get here } TRange<float> FVlcMediaPlayer::GetSupportedRates(EMediaPlaybackDirections Direction, bool Unthinned) const { if (Direction == EMediaPlaybackDirections::Reverse) { return TRange<float>::Empty(); } return TRange<float>(0.0f, 10.0f); } FTimespan FVlcMediaPlayer::GetTime() const { return CurrentTime; } bool FVlcMediaPlayer::IsLooping() const { return ShouldLoop; } bool FVlcMediaPlayer::SetLooping(bool Looping) { ShouldLoop = Looping; return true; } bool FVlcMediaPlayer::SetRate(float Rate) { if (Player == nullptr) { return false; } if ((FVlc::MediaPlayerSetRate(Player, Rate) == -1)) { return false; } if (FMath::IsNearlyZero(Rate)) { if (FVlc::MediaPlayerGetState(Player) == ELibvlcState::Playing) { if (FVlc::MediaPlayerCanPause(Player) == 0) { return false; } FVlc::MediaPlayerPause(Player); } } else if (FVlc::MediaPlayerGetState(Player) != ELibvlcState::Playing) { if (FVlc::MediaPlayerPlay(Player) == -1) { return false; } } DesiredRate = Rate; return true; } bool FVlcMediaPlayer::SupportsRate(float Rate, bool Unthinned) const { return (Rate >= 0.0f) && (Rate <= 10.0f); } bool FVlcMediaPlayer::SupportsScrubbing() const { return ((Player != nullptr) && (FVlc::MediaPlayerIsSeekable(Player) != 0)); } bool FVlcMediaPlayer::SupportsSeeking() const { return ((Player != nullptr) && (FVlc::MediaPlayerIsSeekable(Player) != 0)); } /* IMediaPlayer interface *****************************************************************************/ void FVlcMediaPlayer::Close() { if (Player == nullptr) { return; } // detach callback handlers Output.Shutdown(); Tracks.Shutdown(); // release player FVlc::MediaPlayerStop(Player); FVlc::MediaPlayerRelease(Player); Player = nullptr; // reset fields CurrentTime = FTimespan::Zero(); MediaSource.Close(); Info.Empty(); // notify listeners MediaEvent.Broadcast(EMediaEvent::TracksChanged); MediaEvent.Broadcast(EMediaEvent::MediaClosed); } IMediaControls& FVlcMediaPlayer::GetControls() { return *this; } FString FVlcMediaPlayer::GetInfo() const { return Info; } FName FVlcMediaPlayer::GetName() const { static FName PlayerName(TEXT("VlcMedia")); return PlayerName; } IMediaOutput& FVlcMediaPlayer::GetOutput() { return Output; } FString FVlcMediaPlayer::GetStats() const { FLibvlcMedia* Media = MediaSource.GetMedia(); if (Media == nullptr) { return TEXT("No media opened."); } FLibvlcMediaStats Stats; if (!FVlc::MediaGetStats(Media, &Stats)) { return TEXT("Stats currently not available."); } FString StatsString; { StatsString += TEXT("General\n"); StatsString += FString::Printf(TEXT(" Decoded Video: %i\n"), Stats.DecodedVideo); StatsString += FString::Printf(TEXT(" Decoded Audio: %i\n"), Stats.DecodedAudio); StatsString += FString::Printf(TEXT(" Displayed Pictures: %i\n"), Stats.DisplayedPictures); StatsString += FString::Printf(TEXT(" Lost Pictures: %i\n"), Stats.LostPictures); StatsString += FString::Printf(TEXT(" Played A-Buffers: %i\n"), Stats.PlayedAbuffers); StatsString += FString::Printf(TEXT(" Lost Lost A-Buffers: %i\n"), Stats.LostAbuffers); StatsString += TEXT("\n"); StatsString += TEXT("Input\n"); StatsString += FString::Printf(TEXT(" Bit Rate: %i\n"), Stats.InputBitrate); StatsString += FString::Printf(TEXT(" Bytes Read: %i\n"), Stats.ReadBytes); StatsString += TEXT("\n"); StatsString += TEXT("Demux\n"); StatsString += FString::Printf(TEXT(" Bit Rate: %f\n"), Stats.DemuxBitrate); StatsString += FString::Printf(TEXT(" Bytes Read: %i\n"), Stats.DemuxReadBytes); StatsString += FString::Printf(TEXT(" Corrupted: %i\n"), Stats.DemuxCorrupted); StatsString += FString::Printf(TEXT(" Discontinuity: %i\n"), Stats.DemuxDiscontinuity); StatsString += TEXT("\n"); StatsString += TEXT("Network\n"); StatsString += FString::Printf(TEXT(" Bitrate: %f\n"), Stats.SendBitrate); StatsString += FString::Printf(TEXT(" Sent Bytes: %i\n"), Stats.SentBytes); StatsString += FString::Printf(TEXT(" Sent Packets: %i\n"), Stats.SentPackets); StatsString += TEXT("\n"); } return StatsString; } IMediaTracks& FVlcMediaPlayer::GetTracks() { return Tracks; } FString FVlcMediaPlayer::GetUrl() const { return MediaSource.GetCurrentUrl(); } bool FVlcMediaPlayer::Open(const FString& Url, const IMediaOptions& Options) { Close(); if (Url.IsEmpty()) { return false; } if (Url.StartsWith(TEXT("file://"))) { // open local files via platform file system TSharedPtr<FArchive, ESPMode::ThreadSafe> Archive; const TCHAR* FilePath = &Url[7]; if (Options.GetMediaOption("PrecacheFile", false)) { FArrayReader* Reader = new FArrayReader; if (FFileHelper::LoadFileToArray(*Reader, FilePath)) { Archive = MakeShareable(Reader); } else { delete Reader; } } else { Archive = MakeShareable(IFileManager::Get().CreateFileReader(FilePath)); } if (!Archive.IsValid()) { UE_LOG(LogVlcMedia, Warning, TEXT("Failed to open media file: %s"), FilePath); return false; } if (!MediaSource.OpenArchive(Archive.ToSharedRef(), Url)) { return false; } } else { if (!MediaSource.OpenUrl(Url)) { return false; } } return InitializePlayer(); } bool FVlcMediaPlayer::Open(const TSharedRef<FArchive, ESPMode::ThreadSafe>& Archive, const FString& OriginalUrl, const IMediaOptions& Options) { Close(); if (OriginalUrl.IsEmpty() || !MediaSource.OpenArchive(Archive, OriginalUrl)) { return false; } return InitializePlayer(); } bool FVlcMediaPlayer::Seek(const FTimespan& Time) { ELibvlcState State = FVlc::MediaPlayerGetState(Player); if ((State != ELibvlcState::Opening) || (State == ELibvlcState::Buffering) || (State == ELibvlcState::Error)) { return false; } FVlc::MediaPlayerSetTime(Player, Time.GetTotalMilliseconds()); return true; } /* FVlcMediaPlayer implementation *****************************************************************************/ bool FVlcMediaPlayer::InitializePlayer() { Player = FVlc::MediaPlayerNewFromMedia(MediaSource.GetMedia()); if (Player == nullptr) { UE_LOG(LogVlcMedia, Warning, TEXT("Failed to initialize media player: %s"), ANSI_TO_TCHAR(FVlc::Errmsg())); return false; } // attach to event managers FLibvlcEventManager* MediaEventManager = FVlc::MediaEventManager(MediaSource.GetMedia()); FLibvlcEventManager* PlayerEventManager = FVlc::MediaPlayerEventManager(Player); if ((MediaEventManager == nullptr) || (PlayerEventManager == nullptr)) { FVlc::MediaPlayerRelease(Player); Player = nullptr; return false; } FVlc::EventAttach(MediaEventManager, ELibvlcEventType::MediaParsedChanged, &FVlcMediaPlayer::StaticEventCallback, this); FVlc::EventAttach(PlayerEventManager, ELibvlcEventType::MediaPlayerEndReached, &FVlcMediaPlayer::StaticEventCallback, this); FVlc::EventAttach(PlayerEventManager, ELibvlcEventType::MediaPlayerPlaying, &FVlcMediaPlayer::StaticEventCallback, this); FVlc::EventAttach(PlayerEventManager, ELibvlcEventType::MediaPlayerPositionChanged, &FVlcMediaPlayer::StaticEventCallback, this); MediaEvent.Broadcast(EMediaEvent::MediaOpened); return true; } /* FVlcMediaPlayer static functions *****************************************************************************/ void FVlcMediaPlayer::StaticEventCallback(FLibvlcEvent* Event, void* UserData) { UE_LOG(LogVlcMedia, Verbose, TEXT("LibVLC event: %s"), *VlcMedia::EventToString(Event)); auto MediaPlayer = (FVlcMediaPlayer*)UserData; if (MediaPlayer == nullptr) { return; } if (Event->Type == ELibvlcEventType::MediaParsedChanged) { MediaPlayer->Tracks.Initialize(*MediaPlayer->Player, MediaPlayer->Info); MediaPlayer->Output.Initialize(*MediaPlayer->Player); } else if (Event->Type == ELibvlcEventType::MediaPlayerPlaying) { MediaPlayer->Output.Resume(MediaPlayer->CurrentTime); } MediaPlayer->Events.Enqueue(Event->Type); } <commit_msg>Fixed current time not resetting at beginning of playback.<commit_after>// Copyright 2015 Headcrash Industries LLC. All Rights Reserved. #include "VlcMediaPCH.h" #include "Vlc.h" #include "VlcMediaPlayer.h" #include "VlcMediaUtils.h" /* FVlcMediaPlayer structors *****************************************************************************/ FVlcMediaPlayer::FVlcMediaPlayer(FLibvlcInstance* InVlcInstance) : CurrentTime(FTimespan::Zero()) , DesiredRate(0.0) , LastPlatformSeconds(0.0) , MediaSource(InVlcInstance) , Player(nullptr) , ShouldLoop(false) { } FVlcMediaPlayer::~FVlcMediaPlayer() { Close(); } /* FTickerObjectBase interface *****************************************************************************/ bool FVlcMediaPlayer::Tick(float DeltaTime) { if (Player == nullptr) { return true; } // interpolate time, because FVlc::MediaPlayerGetTime is too low-res if (FVlc::MediaPlayerGetState(Player) == ELibvlcState::Playing) { double PlatformSeconds = FPlatformTime::Seconds(); CurrentTime += FTimespan::FromSeconds(DesiredRate * (PlatformSeconds - LastPlatformSeconds)); LastPlatformSeconds = PlatformSeconds; } // process events ELibvlcEventType Event; while (Events.Dequeue(Event)) { switch (Event) { case ELibvlcEventType::MediaParsedChanged: MediaEvent.Broadcast(EMediaEvent::TracksChanged); break; case ELibvlcEventType::MediaPlayerEndReached: // begin hack: this causes a short delay, but there seems to be no // other way. looping via VLC Media List players is also broken :( FVlc::MediaPlayerStop(Player); // end hack if (ShouldLoop && (DesiredRate != 0.0f)) { SetRate(DesiredRate); } MediaEvent.Broadcast(EMediaEvent::PlaybackSuspended); MediaEvent.Broadcast(EMediaEvent::PlaybackEndReached); break; case ELibvlcEventType::MediaPlayerPaused: LastPlatformSeconds = FPlatformTime::Seconds(); MediaEvent.Broadcast(EMediaEvent::PlaybackSuspended); break; case ELibvlcEventType::MediaPlayerPlaying: CurrentTime = FTimespan::Zero(); LastPlatformSeconds = FPlatformTime::Seconds(); MediaEvent.Broadcast(EMediaEvent::PlaybackResumed); break; case ELibvlcEventType::MediaPlayerPositionChanged: CurrentTime = FTimespan::FromMilliseconds(FMath::Max<int64>(0, FVlc::MediaPlayerGetTime(Player))); LastPlatformSeconds = FPlatformTime::Seconds(); break; default: continue; } } return true; } /* IMediaControls interface *****************************************************************************/ FTimespan FVlcMediaPlayer::GetDuration() const { if (Player == nullptr) { return FTimespan::Zero(); } int64 Length = FVlc::MediaPlayerGetLength(Player); if (Length <= 0) { return GetTime(); } return FTimespan::FromMilliseconds(Length); } float FVlcMediaPlayer::GetRate() const { if ((Player == nullptr) || (FVlc::MediaPlayerGetState(Player) != ELibvlcState::Playing)) { return 0.0f; } return FVlc::MediaPlayerGetRate(Player); } EMediaState FVlcMediaPlayer::GetState() const { if (Player == nullptr) { return EMediaState::Closed; } ELibvlcState State = FVlc::MediaPlayerGetState(Player); switch (State) { case ELibvlcState::Error: return EMediaState::Error; case ELibvlcState::Buffering: case ELibvlcState::Opening: return EMediaState::Preparing; case ELibvlcState::Paused: return EMediaState::Paused; case ELibvlcState::Playing: return EMediaState::Playing; case ELibvlcState::Ended: case ELibvlcState::NothingSpecial: case ELibvlcState::Stopped: return EMediaState::Stopped; } return EMediaState::Error; // should never get here } TRange<float> FVlcMediaPlayer::GetSupportedRates(EMediaPlaybackDirections Direction, bool Unthinned) const { if (Direction == EMediaPlaybackDirections::Reverse) { return TRange<float>::Empty(); } return TRange<float>(0.0f, 10.0f); } FTimespan FVlcMediaPlayer::GetTime() const { return CurrentTime; } bool FVlcMediaPlayer::IsLooping() const { return ShouldLoop; } bool FVlcMediaPlayer::SetLooping(bool Looping) { ShouldLoop = Looping; return true; } bool FVlcMediaPlayer::SetRate(float Rate) { if (Player == nullptr) { return false; } if ((FVlc::MediaPlayerSetRate(Player, Rate) == -1)) { return false; } if (FMath::IsNearlyZero(Rate)) { if (FVlc::MediaPlayerGetState(Player) == ELibvlcState::Playing) { if (FVlc::MediaPlayerCanPause(Player) == 0) { return false; } FVlc::MediaPlayerPause(Player); } } else if (FVlc::MediaPlayerGetState(Player) != ELibvlcState::Playing) { if (FVlc::MediaPlayerPlay(Player) == -1) { return false; } } DesiredRate = Rate; return true; } bool FVlcMediaPlayer::SupportsRate(float Rate, bool Unthinned) const { return (Rate >= 0.0f) && (Rate <= 10.0f); } bool FVlcMediaPlayer::SupportsScrubbing() const { return ((Player != nullptr) && (FVlc::MediaPlayerIsSeekable(Player) != 0)); } bool FVlcMediaPlayer::SupportsSeeking() const { return ((Player != nullptr) && (FVlc::MediaPlayerIsSeekable(Player) != 0)); } /* IMediaPlayer interface *****************************************************************************/ void FVlcMediaPlayer::Close() { if (Player == nullptr) { return; } // detach callback handlers Output.Shutdown(); Tracks.Shutdown(); // release player FVlc::MediaPlayerStop(Player); FVlc::MediaPlayerRelease(Player); Player = nullptr; // reset fields CurrentTime = FTimespan::Zero(); MediaSource.Close(); Info.Empty(); // notify listeners MediaEvent.Broadcast(EMediaEvent::TracksChanged); MediaEvent.Broadcast(EMediaEvent::MediaClosed); } IMediaControls& FVlcMediaPlayer::GetControls() { return *this; } FString FVlcMediaPlayer::GetInfo() const { return Info; } FName FVlcMediaPlayer::GetName() const { static FName PlayerName(TEXT("VlcMedia")); return PlayerName; } IMediaOutput& FVlcMediaPlayer::GetOutput() { return Output; } FString FVlcMediaPlayer::GetStats() const { FLibvlcMedia* Media = MediaSource.GetMedia(); if (Media == nullptr) { return TEXT("No media opened."); } FLibvlcMediaStats Stats; if (!FVlc::MediaGetStats(Media, &Stats)) { return TEXT("Stats currently not available."); } FString StatsString; { StatsString += TEXT("General\n"); StatsString += FString::Printf(TEXT(" Decoded Video: %i\n"), Stats.DecodedVideo); StatsString += FString::Printf(TEXT(" Decoded Audio: %i\n"), Stats.DecodedAudio); StatsString += FString::Printf(TEXT(" Displayed Pictures: %i\n"), Stats.DisplayedPictures); StatsString += FString::Printf(TEXT(" Lost Pictures: %i\n"), Stats.LostPictures); StatsString += FString::Printf(TEXT(" Played A-Buffers: %i\n"), Stats.PlayedAbuffers); StatsString += FString::Printf(TEXT(" Lost Lost A-Buffers: %i\n"), Stats.LostAbuffers); StatsString += TEXT("\n"); StatsString += TEXT("Input\n"); StatsString += FString::Printf(TEXT(" Bit Rate: %i\n"), Stats.InputBitrate); StatsString += FString::Printf(TEXT(" Bytes Read: %i\n"), Stats.ReadBytes); StatsString += TEXT("\n"); StatsString += TEXT("Demux\n"); StatsString += FString::Printf(TEXT(" Bit Rate: %f\n"), Stats.DemuxBitrate); StatsString += FString::Printf(TEXT(" Bytes Read: %i\n"), Stats.DemuxReadBytes); StatsString += FString::Printf(TEXT(" Corrupted: %i\n"), Stats.DemuxCorrupted); StatsString += FString::Printf(TEXT(" Discontinuity: %i\n"), Stats.DemuxDiscontinuity); StatsString += TEXT("\n"); StatsString += TEXT("Network\n"); StatsString += FString::Printf(TEXT(" Bitrate: %f\n"), Stats.SendBitrate); StatsString += FString::Printf(TEXT(" Sent Bytes: %i\n"), Stats.SentBytes); StatsString += FString::Printf(TEXT(" Sent Packets: %i\n"), Stats.SentPackets); StatsString += TEXT("\n"); } return StatsString; } IMediaTracks& FVlcMediaPlayer::GetTracks() { return Tracks; } FString FVlcMediaPlayer::GetUrl() const { return MediaSource.GetCurrentUrl(); } bool FVlcMediaPlayer::Open(const FString& Url, const IMediaOptions& Options) { Close(); if (Url.IsEmpty()) { return false; } if (Url.StartsWith(TEXT("file://"))) { // open local files via platform file system TSharedPtr<FArchive, ESPMode::ThreadSafe> Archive; const TCHAR* FilePath = &Url[7]; if (Options.GetMediaOption("PrecacheFile", false)) { FArrayReader* Reader = new FArrayReader; if (FFileHelper::LoadFileToArray(*Reader, FilePath)) { Archive = MakeShareable(Reader); } else { delete Reader; } } else { Archive = MakeShareable(IFileManager::Get().CreateFileReader(FilePath)); } if (!Archive.IsValid()) { UE_LOG(LogVlcMedia, Warning, TEXT("Failed to open media file: %s"), FilePath); return false; } if (!MediaSource.OpenArchive(Archive.ToSharedRef(), Url)) { return false; } } else { if (!MediaSource.OpenUrl(Url)) { return false; } } return InitializePlayer(); } bool FVlcMediaPlayer::Open(const TSharedRef<FArchive, ESPMode::ThreadSafe>& Archive, const FString& OriginalUrl, const IMediaOptions& Options) { Close(); if (OriginalUrl.IsEmpty() || !MediaSource.OpenArchive(Archive, OriginalUrl)) { return false; } return InitializePlayer(); } bool FVlcMediaPlayer::Seek(const FTimespan& Time) { ELibvlcState State = FVlc::MediaPlayerGetState(Player); if ((State != ELibvlcState::Opening) || (State == ELibvlcState::Buffering) || (State == ELibvlcState::Error)) { return false; } FVlc::MediaPlayerSetTime(Player, Time.GetTotalMilliseconds()); return true; } /* FVlcMediaPlayer implementation *****************************************************************************/ bool FVlcMediaPlayer::InitializePlayer() { Player = FVlc::MediaPlayerNewFromMedia(MediaSource.GetMedia()); if (Player == nullptr) { UE_LOG(LogVlcMedia, Warning, TEXT("Failed to initialize media player: %s"), ANSI_TO_TCHAR(FVlc::Errmsg())); return false; } // attach to event managers FLibvlcEventManager* MediaEventManager = FVlc::MediaEventManager(MediaSource.GetMedia()); FLibvlcEventManager* PlayerEventManager = FVlc::MediaPlayerEventManager(Player); if ((MediaEventManager == nullptr) || (PlayerEventManager == nullptr)) { FVlc::MediaPlayerRelease(Player); Player = nullptr; return false; } FVlc::EventAttach(MediaEventManager, ELibvlcEventType::MediaParsedChanged, &FVlcMediaPlayer::StaticEventCallback, this); FVlc::EventAttach(PlayerEventManager, ELibvlcEventType::MediaPlayerEndReached, &FVlcMediaPlayer::StaticEventCallback, this); FVlc::EventAttach(PlayerEventManager, ELibvlcEventType::MediaPlayerPlaying, &FVlcMediaPlayer::StaticEventCallback, this); FVlc::EventAttach(PlayerEventManager, ELibvlcEventType::MediaPlayerPositionChanged, &FVlcMediaPlayer::StaticEventCallback, this); MediaEvent.Broadcast(EMediaEvent::MediaOpened); return true; } /* FVlcMediaPlayer static functions *****************************************************************************/ void FVlcMediaPlayer::StaticEventCallback(FLibvlcEvent* Event, void* UserData) { UE_LOG(LogVlcMedia, Verbose, TEXT("LibVLC event: %s"), *VlcMedia::EventToString(Event)); auto MediaPlayer = (FVlcMediaPlayer*)UserData; if (MediaPlayer == nullptr) { return; } if (Event->Type == ELibvlcEventType::MediaParsedChanged) { MediaPlayer->Tracks.Initialize(*MediaPlayer->Player, MediaPlayer->Info); MediaPlayer->Output.Initialize(*MediaPlayer->Player); } else if (Event->Type == ELibvlcEventType::MediaPlayerPlaying) { MediaPlayer->Output.Resume(MediaPlayer->CurrentTime); } MediaPlayer->Events.Enqueue(Event->Type); } <|endoftext|>
<commit_before>#include "mbed.h" #include "test_env.h" #include "rtos.h" typedef struct { float voltage; /* AD result of measured voltage */ float current; /* AD result of measured current */ uint32_t counter; /* A counter value */ } message_t; #define CREATE_VOLTAGE(COUNTER) (COUNTER * 0.1) * 33 #define CREATE_CURRENT(COUNTER) (COUNTER * 0.1) * 11 #define QUEUE_SIZE 16 #define QUEUE_PUT_DELAY 100 MemoryPool<message_t, QUEUE_SIZE> mpool; Queue<message_t, QUEUE_SIZE> queue; /* Send Thread */ void send_thread (void const *argument) { static uint32_t i = 0; while (true) { i++; // Fake data update message_t *message = mpool.alloc(); message->voltage = CREATE_VOLTAGE(i); message->current = CREATE_CURRENT(i); message->counter = i; queue.put(message); Thread::wait(QUEUE_PUT_DELAY); } } int main (void) { Thread thread(send_thread); bool result = true; int result_counter = 0; while (true) { osEvent evt = queue.get(); if (evt.status == osEventMessage) { message_t *message = (message_t*)evt.value.p; float expected_voltage = CREATE_VOLTAGE(message->counter); float expected_current = CREATE_CURRENT(message->counter); // Check using macros if received values correspond to values sent via queue bool expected_values = (expected_voltage == message->voltage) && (expected_current == message->current); result = result && expected_values; const char *result_msg = expected_values ? "OK" : "FAIL"; printf("%3d %.2fV %.2fA ... [%s]\r\n", message->counter, message->voltage, message->current, result_msg); mpool.free(message); if (result == false || ++result_counter == QUEUE_SIZE) { break; } } } notify_completion(result); return 0; } <commit_msg>RTOS_5 Queue test small implementation changes<commit_after>#include "mbed.h" #include "test_env.h" #include "rtos.h" typedef struct { float voltage; /* AD result of measured voltage */ float current; /* AD result of measured current */ uint32_t counter; /* A counter value */ } message_t; #define CREATE_VOLTAGE(COUNTER) (COUNTER * 0.1) * 33 #define CREATE_CURRENT(COUNTER) (COUNTER * 0.1) * 11 #define QUEUE_SIZE 16 #define QUEUE_PUT_DELAY 100 MemoryPool<message_t, QUEUE_SIZE> mpool; Queue<message_t, QUEUE_SIZE> queue; /* Send Thread */ void send_thread (void const *argument) { static uint32_t i = 0; while (true) { i++; // Fake data update message_t *message = mpool.alloc(); message->voltage = CREATE_VOLTAGE(i); message->current = CREATE_CURRENT(i); message->counter = i; queue.put(message); Thread::wait(QUEUE_PUT_DELAY); } } int main (void) { Thread thread(send_thread); bool result = true; int result_counter = 0; while (true) { osEvent evt = queue.get(); if (evt.status == osEventMessage) { message_t *message = (message_t*)evt.value.p; const float expected_voltage = CREATE_VOLTAGE(message->counter); const float expected_current = CREATE_CURRENT(message->counter); // Check using macros if received values correspond to values sent via queue bool expected_values = (expected_voltage == message->voltage) && (expected_current == message->current); result = result && expected_values; const char *result_msg = expected_values ? "OK" : "FAIL"; printf("%3d %.2fV %.2fA ... [%s]\r\n", message->counter, message->voltage, message->current, result_msg); mpool.free(message); if (result == false || ++result_counter == QUEUE_SIZE) { break; } } } notify_completion(result); return 0; } <|endoftext|>
<commit_before>// Copyright 2013 Alessio Sclocco <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> using std::cout; using std::cerr; using std::endl; #include <string> using std::string; #include <vector> using std::vector; #include <exception> using std::exception; #include <iomanip> using std::fixed; using std::setprecision; #include <limits> using std::numeric_limits; #include <cmath> #include <ctime> #include <ArgumentList.hpp> using isa::utils::ArgumentList; #include <Observation.hpp> using AstroData::Observation; #include <InitializeOpenCL.hpp> using isa::OpenCL::initializeOpenCL; #include <CLData.hpp> using isa::OpenCL::CLData; #include <utils.hpp> using isa::utils::same; #include <Folding.hpp> using PulsarSearch::Folding; #include <FoldingCPU.hpp> using PulsarSearch::folding; using PulsarSearch::traditionalFolding; #include <Bins.hpp> using PulsarSearch::getNrSamplesPerBin; typedef float dataType; const string typeName("float"); int main(int argc, char *argv[]) { bool print = false; long long unsigned int wrongValues = 0; Observation< dataType > observation("FoldingTest", typeName); CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true); CLData< dataType > * dedispersedDataTraditional = new CLData< dataType >("DedispersedDataTraditional", true); CLData< dataType > * foldedDataCPU = new CLData<dataType >("FoldedDataCPU", true); CLData< dataType > * foldedDataTraditional = new CLData<dataType >("FoldedDataTraditional", true); CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true); CLData< unsigned int > * counterDataTraditional = new CLData< unsigned int >("CounterDataTraditional", true); try { ArgumentList args(argc, argv); print = args.getSwitch("-print"); observation.setPadding(args.getSwitchArgument< unsigned int >("-passing")); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms")); observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods")); observation.setFirstPeriod(args.getSwitchArgument< unsigned int >("-period_first")); observation.setPeriodStep(args.getSwitchArgument< unsigned int >("-period_step")); observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins")); } catch ( exception &err ) { cerr << err.what() << endl; return 1; } // Allocate memory dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs()); dedispersedDataTraditional->allocateHostData(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); foldedDataCPU->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); foldedDataCPU->blankHostData(); foldedDataTraditional->allocateHostData(observation.getNrDMs() * observation.getNrPaddedBins() * observation.getNrPeriods()); foldedDataTraditional->blankHostData(); counterData->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins()); counterData->blankHostData(); counterDataTraditional->allocateHostData(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrPaddedBins()); counterDataTraditional->blankHostData(); srand(time(NULL)); for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { dedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100); dedispersedDataTraditional->setHostDataItem((DM * observation.getNrSamplesPerPaddedSecond()) + sample, dedispersedData->getHostDataItem((sample * observation.getNrPaddedDMs()) + DM)); } } // Test & Check folding(0, observation, dedispersedData->getHostData(), foldedDataCPU->getHostData(), counterData->getHostData()); traditionalFolding(0, observation, dedispersedDataTraditional->getHostData(), foldedDataTraditional->getHostData(), counterDataTraditional->getHostData()); if ( print ) { for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { cout << foldedDataCPU->getHostDataItem((bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM) << "-" << counterData->getHostDataItem((period * observation.getNrPaddedBins()) + bin) << " "; } cout << endl; } cout << endl; } cout << endl; for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { cout << foldedDataTraditional->getHostDataItem((((DM * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin) << "-" << counterDataTraditional->getHostDataItem((((DM * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin) << " "; } cout << endl; } cout << endl; } cout << endl; } for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { long long unsigned int wrongValuesBin = 0; for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { if ( !same(foldedDataCPU->getHostDataItem((bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM), foldedDataTraditional->getHostDataItem((((DM * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin)) ) { wrongValues++; wrongValuesBin++; } } } if ( wrongValuesBin > 0 && print ) { cout << "Wrong samples bin " << bin << ": " << wrongValuesBin << " (" << (wrongValuesBin * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << endl; } } cout << endl; if ( wrongValues > 0 ) { cout << "Wrong samples: " << wrongValues << " (" << (wrongValues * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl; } else { cout << "TEST PASSED." << endl; } cout << endl; return 0; } <commit_msg>Typo.<commit_after>// Copyright 2013 Alessio Sclocco <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> using std::cout; using std::cerr; using std::endl; #include <string> using std::string; #include <vector> using std::vector; #include <exception> using std::exception; #include <iomanip> using std::fixed; using std::setprecision; #include <limits> using std::numeric_limits; #include <cmath> #include <ctime> #include <ArgumentList.hpp> using isa::utils::ArgumentList; #include <Observation.hpp> using AstroData::Observation; #include <InitializeOpenCL.hpp> using isa::OpenCL::initializeOpenCL; #include <CLData.hpp> using isa::OpenCL::CLData; #include <utils.hpp> using isa::utils::same; #include <Folding.hpp> using PulsarSearch::Folding; #include <FoldingCPU.hpp> using PulsarSearch::folding; using PulsarSearch::traditionalFolding; #include <Bins.hpp> using PulsarSearch::getNrSamplesPerBin; typedef float dataType; const string typeName("float"); int main(int argc, char *argv[]) { bool print = false; long long unsigned int wrongValues = 0; Observation< dataType > observation("FoldingTest", typeName); CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true); CLData< dataType > * dedispersedDataTraditional = new CLData< dataType >("DedispersedDataTraditional", true); CLData< dataType > * foldedDataCPU = new CLData<dataType >("FoldedDataCPU", true); CLData< dataType > * foldedDataTraditional = new CLData<dataType >("FoldedDataTraditional", true); CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true); CLData< unsigned int > * counterDataTraditional = new CLData< unsigned int >("CounterDataTraditional", true); try { ArgumentList args(argc, argv); print = args.getSwitch("-print"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms")); observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods")); observation.setFirstPeriod(args.getSwitchArgument< unsigned int >("-period_first")); observation.setPeriodStep(args.getSwitchArgument< unsigned int >("-period_step")); observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins")); } catch ( exception &err ) { cerr << err.what() << endl; return 1; } // Allocate memory dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs()); dedispersedDataTraditional->allocateHostData(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); foldedDataCPU->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); foldedDataCPU->blankHostData(); foldedDataTraditional->allocateHostData(observation.getNrDMs() * observation.getNrPaddedBins() * observation.getNrPeriods()); foldedDataTraditional->blankHostData(); counterData->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins()); counterData->blankHostData(); counterDataTraditional->allocateHostData(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrPaddedBins()); counterDataTraditional->blankHostData(); srand(time(NULL)); for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { dedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100); dedispersedDataTraditional->setHostDataItem((DM * observation.getNrSamplesPerPaddedSecond()) + sample, dedispersedData->getHostDataItem((sample * observation.getNrPaddedDMs()) + DM)); } } // Test & Check folding(0, observation, dedispersedData->getHostData(), foldedDataCPU->getHostData(), counterData->getHostData()); traditionalFolding(0, observation, dedispersedDataTraditional->getHostData(), foldedDataTraditional->getHostData(), counterDataTraditional->getHostData()); if ( print ) { for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { cout << foldedDataCPU->getHostDataItem((bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM) << "-" << counterData->getHostDataItem((period * observation.getNrPaddedBins()) + bin) << " "; } cout << endl; } cout << endl; } cout << endl; for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { cout << foldedDataTraditional->getHostDataItem((((DM * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin) << "-" << counterDataTraditional->getHostDataItem((((DM * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin) << " "; } cout << endl; } cout << endl; } cout << endl; } for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { long long unsigned int wrongValuesBin = 0; for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { if ( !same(foldedDataCPU->getHostDataItem((bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM), foldedDataTraditional->getHostDataItem((((DM * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin)) ) { wrongValues++; wrongValuesBin++; } } } if ( wrongValuesBin > 0 && print ) { cout << "Wrong samples bin " << bin << ": " << wrongValuesBin << " (" << (wrongValuesBin * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << endl; } } cout << endl; if ( wrongValues > 0 ) { cout << "Wrong samples: " << wrongValues << " (" << (wrongValues * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl; } else { cout << "TEST PASSED." << endl; } cout << endl; return 0; } <|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: * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "platform/graphics/DeferredImageDecoder.h" #include "platform/graphics/DecodingImageGenerator.h" #include "platform/graphics/ImageDecodingStore.h" #include "platform/graphics/LazyDecodingPixelRef.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "wtf/PassOwnPtr.h" namespace WebCore { namespace { // URI label for a lazily decoded SkPixelRef. const char labelLazyDecoded[] = "lazy"; // URI label for SkDiscardablePixelRef. const char labelDiscardable[] = "discardable"; } // namespace bool DeferredImageDecoder::s_enabled = false; bool DeferredImageDecoder::s_skiaDiscardableMemoryEnabled = false; DeferredImageDecoder::DeferredImageDecoder(PassOwnPtr<ImageDecoder> actualDecoder) : m_allDataReceived(false) , m_lastDataSize(0) , m_dataChanged(false) , m_actualDecoder(actualDecoder) , m_orientation(DefaultImageOrientation) , m_repetitionCount(cAnimationNone) , m_hasColorProfile(false) { } DeferredImageDecoder::~DeferredImageDecoder() { } PassOwnPtr<DeferredImageDecoder> DeferredImageDecoder::create(const SharedBuffer& data, ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorOption) { OwnPtr<ImageDecoder> actualDecoder = ImageDecoder::create(data, alphaOption, gammaAndColorOption); return actualDecoder ? adoptPtr(new DeferredImageDecoder(actualDecoder.release())) : nullptr; } PassOwnPtr<DeferredImageDecoder> DeferredImageDecoder::createForTesting(PassOwnPtr<ImageDecoder> decoder) { return adoptPtr(new DeferredImageDecoder(decoder)); } bool DeferredImageDecoder::isLazyDecoded(const SkBitmap& bitmap) { return bitmap.pixelRef() && bitmap.pixelRef()->getURI() && (!memcmp(bitmap.pixelRef()->getURI(), labelLazyDecoded, sizeof(labelLazyDecoded)) || !memcmp(bitmap.pixelRef()->getURI(), labelDiscardable, sizeof(labelDiscardable))); } void DeferredImageDecoder::setEnabled(bool enabled) { s_enabled = enabled; #if !OS(ANDROID) // FIXME: This code is temporary to enable discardable memory for // non-Android platforms. In the future all platforms will be // the same and we can remove this code. s_skiaDiscardableMemoryEnabled = enabled; if (enabled) ImageDecodingStore::setImageCachingEnabled(false); #endif } bool DeferredImageDecoder::enabled() { return s_enabled; } String DeferredImageDecoder::filenameExtension() const { return m_actualDecoder ? m_actualDecoder->filenameExtension() : m_filenameExtension; } ImageFrame* DeferredImageDecoder::frameBufferAtIndex(size_t index) { prepareLazyDecodedFrames(); if (index < m_lazyDecodedFrames.size()) { // ImageFrameGenerator has the latest known alpha state. There will // be a performance boost if this frame is opaque. m_lazyDecodedFrames[index]->setHasAlpha(m_frameGenerator->hasAlpha(index)); return m_lazyDecodedFrames[index].get(); } if (m_actualDecoder) return m_actualDecoder->frameBufferAtIndex(index); return 0; } void DeferredImageDecoder::setData(SharedBuffer& data, bool allDataReceived) { if (m_actualDecoder) { const bool firstData = !m_data; const bool moreData = data.size() > m_lastDataSize; m_dataChanged = firstData || moreData; m_data = RefPtr<SharedBuffer>(data); m_lastDataSize = data.size(); m_allDataReceived = allDataReceived; m_actualDecoder->setData(&data, allDataReceived); prepareLazyDecodedFrames(); } if (m_frameGenerator) m_frameGenerator->setData(&data, allDataReceived); } bool DeferredImageDecoder::isSizeAvailable() { // m_actualDecoder is 0 only if image decoding is deferred and that // means image header decoded successfully and size is available. return m_actualDecoder ? m_actualDecoder->isSizeAvailable() : true; } bool DeferredImageDecoder::hasColorProfile() const { return m_actualDecoder ? m_actualDecoder->hasColorProfile() : m_hasColorProfile; } IntSize DeferredImageDecoder::size() const { return m_actualDecoder ? m_actualDecoder->size() : m_size; } IntSize DeferredImageDecoder::frameSizeAtIndex(size_t index) const { // FIXME: LocalFrame size is assumed to be uniform. This might not be true for // future supported codecs. return m_actualDecoder ? m_actualDecoder->frameSizeAtIndex(index) : m_size; } size_t DeferredImageDecoder::frameCount() { return m_actualDecoder ? m_actualDecoder->frameCount() : m_lazyDecodedFrames.size(); } int DeferredImageDecoder::repetitionCount() const { return m_actualDecoder ? m_actualDecoder->repetitionCount() : m_repetitionCount; } size_t DeferredImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame) { // If image decoding is deferred then frame buffer cache is managed by // the compositor and this call is ignored. return m_actualDecoder ? m_actualDecoder->clearCacheExceptFrame(clearExceptFrame) : 0; } bool DeferredImageDecoder::frameHasAlphaAtIndex(size_t index) const { if (m_actualDecoder) return m_actualDecoder->frameHasAlphaAtIndex(index); if (!m_frameGenerator->isMultiFrame()) return m_frameGenerator->hasAlpha(index); return true; } bool DeferredImageDecoder::frameIsCompleteAtIndex(size_t index) const { if (m_actualDecoder) return m_actualDecoder->frameIsCompleteAtIndex(index); if (index < m_lazyDecodedFrames.size()) return m_lazyDecodedFrames[index]->status() == ImageFrame::FrameComplete; return false; } float DeferredImageDecoder::frameDurationAtIndex(size_t index) const { if (m_actualDecoder) return m_actualDecoder->frameDurationAtIndex(index); if (index < m_lazyDecodedFrames.size()) return m_lazyDecodedFrames[index]->duration(); return 0; } unsigned DeferredImageDecoder::frameBytesAtIndex(size_t index) const { // If frame decoding is deferred then it is not managed by MemoryCache // so return 0 here. return m_frameGenerator ? 0 : m_actualDecoder->frameBytesAtIndex(index); } ImageOrientation DeferredImageDecoder::orientation() const { return m_actualDecoder ? m_actualDecoder->orientation() : m_orientation; } void DeferredImageDecoder::activateLazyDecoding() { if (m_frameGenerator) return; m_size = m_actualDecoder->size(); m_orientation = m_actualDecoder->orientation(); m_filenameExtension = m_actualDecoder->filenameExtension(); m_hasColorProfile = m_actualDecoder->hasColorProfile(); const bool isSingleFrame = m_actualDecoder->repetitionCount() == cAnimationNone || (m_allDataReceived && m_actualDecoder->frameCount() == 1u); m_frameGenerator = ImageFrameGenerator::create(SkISize::Make(m_actualDecoder->decodedSize().width(), m_actualDecoder->decodedSize().height()), m_data, m_allDataReceived, !isSingleFrame); } void DeferredImageDecoder::prepareLazyDecodedFrames() { if (!s_enabled || !m_actualDecoder || !m_actualDecoder->isSizeAvailable() || m_actualDecoder->filenameExtension() == "ico") return; activateLazyDecoding(); const size_t previousSize = m_lazyDecodedFrames.size(); m_lazyDecodedFrames.resize(m_actualDecoder->frameCount()); // We have encountered a broken image file. Simply bail. if (m_lazyDecodedFrames.size() < previousSize) return; for (size_t i = previousSize; i < m_lazyDecodedFrames.size(); ++i) { OwnPtr<ImageFrame> frame(adoptPtr(new ImageFrame())); frame->setSkBitmap(createBitmap(i)); frame->setDuration(m_actualDecoder->frameDurationAtIndex(i)); frame->setStatus(m_actualDecoder->frameIsCompleteAtIndex(i) ? ImageFrame::FrameComplete : ImageFrame::FramePartial); m_lazyDecodedFrames[i] = frame.release(); } // The last lazy decoded frame created from previous call might be // incomplete so update its state. if (previousSize) { const size_t lastFrame = previousSize - 1; m_lazyDecodedFrames[lastFrame]->setStatus(m_actualDecoder->frameIsCompleteAtIndex(lastFrame) ? ImageFrame::FrameComplete : ImageFrame::FramePartial); // If data has changed then create a new bitmap. This forces // Skia to decode again. if (m_dataChanged) { m_dataChanged = false; m_lazyDecodedFrames[lastFrame]->setSkBitmap(createBitmap(lastFrame)); } } if (m_allDataReceived) { m_repetitionCount = m_actualDecoder->repetitionCount(); m_actualDecoder.clear(); m_data = nullptr; } } // Creates either a SkBitmap backed by SkDiscardablePixelRef or a SkBitmap using the // legacy LazyDecodingPixelRef. SkBitmap DeferredImageDecoder::createBitmap(size_t index) { // This code is temporary until the transition to SkDiscardablePixelRef is complete. if (s_skiaDiscardableMemoryEnabled) return createSkiaDiscardableBitmap(index); return createLazyDecodingBitmap(index); } // Creates a SkBitmap that is backed by SkDiscardablePixelRef. SkBitmap DeferredImageDecoder::createSkiaDiscardableBitmap(size_t index) { IntSize decodedSize = m_actualDecoder->decodedSize(); ASSERT(decodedSize.width() > 0); ASSERT(decodedSize.height() > 0); SkImageInfo info; info.fWidth = decodedSize.width(); info.fHeight = decodedSize.height(); info.fColorType = kBGRA_8888_SkColorType; info.fAlphaType = kPremul_SkAlphaType; SkBitmap bitmap; DecodingImageGenerator* generator = new DecodingImageGenerator(m_frameGenerator, info, index); bool installed = SkInstallDiscardablePixelRef(generator, &bitmap); ASSERT_UNUSED(installed, installed); bitmap.pixelRef()->setURI(labelDiscardable); generator->setGenerationId(bitmap.getGenerationID()); return bitmap; } SkBitmap DeferredImageDecoder::createLazyDecodingBitmap(size_t index) { IntSize decodedSize = m_actualDecoder->decodedSize(); ASSERT(decodedSize.width() > 0); ASSERT(decodedSize.height() > 0); SkImageInfo info; info.fWidth = decodedSize.width(); info.fHeight = decodedSize.height(); info.fColorType = kPMColor_SkColorType; info.fAlphaType = kPremul_SkAlphaType; // Creates a lazily decoded SkPixelRef that references the entire image without scaling. SkBitmap bitmap; bitmap.setConfig(info); bitmap.setPixelRef(new LazyDecodingPixelRef(info, m_frameGenerator, index))->unref(); // Use the URI to identify this as a lazily decoded SkPixelRef of type LazyDecodingPixelRef. // FIXME: It would be more useful to give the actual image URI. bitmap.pixelRef()->setURI(labelLazyDecoded); // Inform the bitmap that we will never change the pixels. This is a performance hint // subsystems that may try to cache this bitmap (e.g. pictures, pipes, gpu, pdf, etc.) bitmap.setImmutable(); return bitmap; } bool DeferredImageDecoder::hotSpot(IntPoint& hotSpot) const { // TODO: Implement. return m_actualDecoder ? m_actualDecoder->hotSpot(hotSpot) : false; } } // namespace WebCore <commit_msg>Use skia discardable memory for decoded images on Android.<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: * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "platform/graphics/DeferredImageDecoder.h" #include "platform/graphics/DecodingImageGenerator.h" #include "platform/graphics/ImageDecodingStore.h" #include "platform/graphics/LazyDecodingPixelRef.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "wtf/PassOwnPtr.h" namespace WebCore { namespace { // URI label for a lazily decoded SkPixelRef. const char labelLazyDecoded[] = "lazy"; // URI label for SkDiscardablePixelRef. const char labelDiscardable[] = "discardable"; } // namespace bool DeferredImageDecoder::s_enabled = false; bool DeferredImageDecoder::s_skiaDiscardableMemoryEnabled = false; DeferredImageDecoder::DeferredImageDecoder(PassOwnPtr<ImageDecoder> actualDecoder) : m_allDataReceived(false) , m_lastDataSize(0) , m_dataChanged(false) , m_actualDecoder(actualDecoder) , m_orientation(DefaultImageOrientation) , m_repetitionCount(cAnimationNone) , m_hasColorProfile(false) { } DeferredImageDecoder::~DeferredImageDecoder() { } PassOwnPtr<DeferredImageDecoder> DeferredImageDecoder::create(const SharedBuffer& data, ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorOption) { OwnPtr<ImageDecoder> actualDecoder = ImageDecoder::create(data, alphaOption, gammaAndColorOption); return actualDecoder ? adoptPtr(new DeferredImageDecoder(actualDecoder.release())) : nullptr; } PassOwnPtr<DeferredImageDecoder> DeferredImageDecoder::createForTesting(PassOwnPtr<ImageDecoder> decoder) { return adoptPtr(new DeferredImageDecoder(decoder)); } bool DeferredImageDecoder::isLazyDecoded(const SkBitmap& bitmap) { return bitmap.pixelRef() && bitmap.pixelRef()->getURI() && (!memcmp(bitmap.pixelRef()->getURI(), labelLazyDecoded, sizeof(labelLazyDecoded)) || !memcmp(bitmap.pixelRef()->getURI(), labelDiscardable, sizeof(labelDiscardable))); } void DeferredImageDecoder::setEnabled(bool enabled) { s_enabled = enabled; // FIXME: Remove all non-discardable memory related code now that this is // used on all platforms. s_skiaDiscardableMemoryEnabled = enabled; if (enabled) ImageDecodingStore::setImageCachingEnabled(false); } bool DeferredImageDecoder::enabled() { return s_enabled; } String DeferredImageDecoder::filenameExtension() const { return m_actualDecoder ? m_actualDecoder->filenameExtension() : m_filenameExtension; } ImageFrame* DeferredImageDecoder::frameBufferAtIndex(size_t index) { prepareLazyDecodedFrames(); if (index < m_lazyDecodedFrames.size()) { // ImageFrameGenerator has the latest known alpha state. There will // be a performance boost if this frame is opaque. m_lazyDecodedFrames[index]->setHasAlpha(m_frameGenerator->hasAlpha(index)); return m_lazyDecodedFrames[index].get(); } if (m_actualDecoder) return m_actualDecoder->frameBufferAtIndex(index); return 0; } void DeferredImageDecoder::setData(SharedBuffer& data, bool allDataReceived) { if (m_actualDecoder) { const bool firstData = !m_data; const bool moreData = data.size() > m_lastDataSize; m_dataChanged = firstData || moreData; m_data = RefPtr<SharedBuffer>(data); m_lastDataSize = data.size(); m_allDataReceived = allDataReceived; m_actualDecoder->setData(&data, allDataReceived); prepareLazyDecodedFrames(); } if (m_frameGenerator) m_frameGenerator->setData(&data, allDataReceived); } bool DeferredImageDecoder::isSizeAvailable() { // m_actualDecoder is 0 only if image decoding is deferred and that // means image header decoded successfully and size is available. return m_actualDecoder ? m_actualDecoder->isSizeAvailable() : true; } bool DeferredImageDecoder::hasColorProfile() const { return m_actualDecoder ? m_actualDecoder->hasColorProfile() : m_hasColorProfile; } IntSize DeferredImageDecoder::size() const { return m_actualDecoder ? m_actualDecoder->size() : m_size; } IntSize DeferredImageDecoder::frameSizeAtIndex(size_t index) const { // FIXME: LocalFrame size is assumed to be uniform. This might not be true for // future supported codecs. return m_actualDecoder ? m_actualDecoder->frameSizeAtIndex(index) : m_size; } size_t DeferredImageDecoder::frameCount() { return m_actualDecoder ? m_actualDecoder->frameCount() : m_lazyDecodedFrames.size(); } int DeferredImageDecoder::repetitionCount() const { return m_actualDecoder ? m_actualDecoder->repetitionCount() : m_repetitionCount; } size_t DeferredImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame) { // If image decoding is deferred then frame buffer cache is managed by // the compositor and this call is ignored. return m_actualDecoder ? m_actualDecoder->clearCacheExceptFrame(clearExceptFrame) : 0; } bool DeferredImageDecoder::frameHasAlphaAtIndex(size_t index) const { if (m_actualDecoder) return m_actualDecoder->frameHasAlphaAtIndex(index); if (!m_frameGenerator->isMultiFrame()) return m_frameGenerator->hasAlpha(index); return true; } bool DeferredImageDecoder::frameIsCompleteAtIndex(size_t index) const { if (m_actualDecoder) return m_actualDecoder->frameIsCompleteAtIndex(index); if (index < m_lazyDecodedFrames.size()) return m_lazyDecodedFrames[index]->status() == ImageFrame::FrameComplete; return false; } float DeferredImageDecoder::frameDurationAtIndex(size_t index) const { if (m_actualDecoder) return m_actualDecoder->frameDurationAtIndex(index); if (index < m_lazyDecodedFrames.size()) return m_lazyDecodedFrames[index]->duration(); return 0; } unsigned DeferredImageDecoder::frameBytesAtIndex(size_t index) const { // If frame decoding is deferred then it is not managed by MemoryCache // so return 0 here. return m_frameGenerator ? 0 : m_actualDecoder->frameBytesAtIndex(index); } ImageOrientation DeferredImageDecoder::orientation() const { return m_actualDecoder ? m_actualDecoder->orientation() : m_orientation; } void DeferredImageDecoder::activateLazyDecoding() { if (m_frameGenerator) return; m_size = m_actualDecoder->size(); m_orientation = m_actualDecoder->orientation(); m_filenameExtension = m_actualDecoder->filenameExtension(); m_hasColorProfile = m_actualDecoder->hasColorProfile(); const bool isSingleFrame = m_actualDecoder->repetitionCount() == cAnimationNone || (m_allDataReceived && m_actualDecoder->frameCount() == 1u); m_frameGenerator = ImageFrameGenerator::create(SkISize::Make(m_actualDecoder->decodedSize().width(), m_actualDecoder->decodedSize().height()), m_data, m_allDataReceived, !isSingleFrame); } void DeferredImageDecoder::prepareLazyDecodedFrames() { if (!s_enabled || !m_actualDecoder || !m_actualDecoder->isSizeAvailable() || m_actualDecoder->filenameExtension() == "ico") return; activateLazyDecoding(); const size_t previousSize = m_lazyDecodedFrames.size(); m_lazyDecodedFrames.resize(m_actualDecoder->frameCount()); // We have encountered a broken image file. Simply bail. if (m_lazyDecodedFrames.size() < previousSize) return; for (size_t i = previousSize; i < m_lazyDecodedFrames.size(); ++i) { OwnPtr<ImageFrame> frame(adoptPtr(new ImageFrame())); frame->setSkBitmap(createBitmap(i)); frame->setDuration(m_actualDecoder->frameDurationAtIndex(i)); frame->setStatus(m_actualDecoder->frameIsCompleteAtIndex(i) ? ImageFrame::FrameComplete : ImageFrame::FramePartial); m_lazyDecodedFrames[i] = frame.release(); } // The last lazy decoded frame created from previous call might be // incomplete so update its state. if (previousSize) { const size_t lastFrame = previousSize - 1; m_lazyDecodedFrames[lastFrame]->setStatus(m_actualDecoder->frameIsCompleteAtIndex(lastFrame) ? ImageFrame::FrameComplete : ImageFrame::FramePartial); // If data has changed then create a new bitmap. This forces // Skia to decode again. if (m_dataChanged) { m_dataChanged = false; m_lazyDecodedFrames[lastFrame]->setSkBitmap(createBitmap(lastFrame)); } } if (m_allDataReceived) { m_repetitionCount = m_actualDecoder->repetitionCount(); m_actualDecoder.clear(); m_data = nullptr; } } // Creates either a SkBitmap backed by SkDiscardablePixelRef or a SkBitmap using the // legacy LazyDecodingPixelRef. SkBitmap DeferredImageDecoder::createBitmap(size_t index) { // This code is temporary until the transition to SkDiscardablePixelRef is complete. if (s_skiaDiscardableMemoryEnabled) return createSkiaDiscardableBitmap(index); return createLazyDecodingBitmap(index); } // Creates a SkBitmap that is backed by SkDiscardablePixelRef. SkBitmap DeferredImageDecoder::createSkiaDiscardableBitmap(size_t index) { IntSize decodedSize = m_actualDecoder->decodedSize(); ASSERT(decodedSize.width() > 0); ASSERT(decodedSize.height() > 0); SkImageInfo info; info.fWidth = decodedSize.width(); info.fHeight = decodedSize.height(); info.fColorType = kBGRA_8888_SkColorType; info.fAlphaType = kPremul_SkAlphaType; SkBitmap bitmap; DecodingImageGenerator* generator = new DecodingImageGenerator(m_frameGenerator, info, index); bool installed = SkInstallDiscardablePixelRef(generator, &bitmap); ASSERT_UNUSED(installed, installed); bitmap.pixelRef()->setURI(labelDiscardable); generator->setGenerationId(bitmap.getGenerationID()); return bitmap; } SkBitmap DeferredImageDecoder::createLazyDecodingBitmap(size_t index) { IntSize decodedSize = m_actualDecoder->decodedSize(); ASSERT(decodedSize.width() > 0); ASSERT(decodedSize.height() > 0); SkImageInfo info; info.fWidth = decodedSize.width(); info.fHeight = decodedSize.height(); info.fColorType = kPMColor_SkColorType; info.fAlphaType = kPremul_SkAlphaType; // Creates a lazily decoded SkPixelRef that references the entire image without scaling. SkBitmap bitmap; bitmap.setConfig(info); bitmap.setPixelRef(new LazyDecodingPixelRef(info, m_frameGenerator, index))->unref(); // Use the URI to identify this as a lazily decoded SkPixelRef of type LazyDecodingPixelRef. // FIXME: It would be more useful to give the actual image URI. bitmap.pixelRef()->setURI(labelLazyDecoded); // Inform the bitmap that we will never change the pixels. This is a performance hint // subsystems that may try to cache this bitmap (e.g. pictures, pipes, gpu, pdf, etc.) bitmap.setImmutable(); return bitmap; } bool DeferredImageDecoder::hotSpot(IntPoint& hotSpot) const { // TODO: Implement. return m_actualDecoder ? m_actualDecoder->hotSpot(hotSpot) : false; } } // namespace WebCore <|endoftext|>
<commit_before>// -*- c-basic-offset: 2; related-file-name: "" -*- /* * @(#)$Id$ * * Copyright (c) 2004 Intel Corporation. All rights reserved. * * This file is distributed under the terms in the attached INTEL-LICENSE file. * If you do not find these files, copies can be found by writing to: * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, * Berkeley, CA, 94704. Attention: Intel License Inquiry. * * DESCRIPTION: A chord dataflow. * */ #if HAVE_CONFIG_H #include <config.h> #endif /* HAVE_CONFIG_H */ #include <async.h> #include <arpc.h> #include <iostream> #include <stdlib.h> #include "tuple.h" #include "router.h" #include "val_int32.h" #include "val_uint32.h" #include "val_str.h" #include "val_id.h" #include "ol_lexer.h" #include "ol_context.h" #include "rtr_confgen.h" #include "udp.h" bool DEBUG = false; bool CC = false; bool TEST_SUCCESSOR = false; bool TEST_LOOKUP = false; void killJoin() { exit(0); } str LOCAL("127.0.0.1:10000"); str REMOTE("Remote.com"); str FINGERIP("Finger.com"); struct SuccessorGenerator : public FunctorSource::Generator { TupleRef operator()() { TupleRef tuple = Tuple::mk(); tuple->append(Val_Str::mk("succ")); str myAddress = str(strbuf() << LOCAL); tuple->append(Val_Str::mk(myAddress)); IDRef successor = ID::mk((uint32_t) rand()); tuple->append(Val_ID::mk(successor)); str succAddress = str(strbuf() << successor->toString() << "IP"); tuple->append(Val_Str::mk(succAddress)); tuple->freeze(); return tuple; } }; // this allows us to isolate and test just the finger lookup rules void fakeFingersSuccessors(ref< OL_Context> ctxt, ref<Rtr_ConfGen> routerConfigGenerator, str localAddress, IDRef me) { TableRef fingerTable = routerConfigGenerator->getTableByName(localAddress, "finger"); OL_Context::TableInfo* fingerTableInfo = ctxt->getTableInfos()->find("finger")->second; // Fill up the table with fingers for (int i = 0; i < fingerTableInfo->size; i++) { TupleRef tuple = Tuple::mk(); tuple->append(Val_Str::mk("finger")); str myAddress = str(strbuf() << localAddress); tuple->append(Val_Str::mk(myAddress)); tuple->append(Val_Int32::mk(i)); IDRef target = ID::mk((uint32_t) 0X1)->shift(i)->add(me); IDRef best = ID::mk()->add(target)->add(ID::mk((uint32_t) i*10)); tuple->append(Val_ID::mk(best)); str address = str(strbuf() << "Finger:" << (i / 2)); tuple->append(Val_Str::mk(address)); tuple->freeze(); fingerTable->insert(tuple); warn << tuple->toString() << "\n"; } // fake the best successor table. Only for testing purposes. TableRef bestSuccessorTable = routerConfigGenerator->getTableByName(localAddress, "bestSucc"); TupleRef tuple = Tuple::mk(); tuple->append(Val_Str::mk("bestSucc")); str myAddress = str(strbuf() << localAddress); tuple->append(Val_Str::mk(myAddress)); IDRef target = ID::mk((uint32_t) 0X1)->add(me); tuple->append(Val_ID::mk(target)); str address = str(strbuf() << "Finger:" << 0); tuple->append(Val_Str::mk(address)); tuple->freeze(); bestSuccessorTable->insert(tuple); warn << "BestSucc: " << tuple->toString() << "\n"; } void initializeBaseTables(ref< OL_Context> ctxt, ref<Rtr_ConfGen> routerConfigGenerator, str localAddress) { // create information on the node itself uint32_t random[ID::WORDS]; for (uint32_t i = 0; i < ID::WORDS; i++) { random[i] = rand(); } IDRef myKey = ID::mk(random); //IDRef myKey = ID::mk((uint32_t) 1); if (TEST_LOOKUP) { // fake fingers and best successors fakeFingersSuccessors(ctxt, routerConfigGenerator, localAddress, myKey); } TableRef nodeTable = routerConfigGenerator->getTableByName(localAddress, "node"); TupleRef tuple = Tuple::mk(); tuple->append(Val_Str::mk("node")); str myAddress = str(strbuf() << localAddress); tuple->append(Val_Str::mk(myAddress)); tuple->append(Val_ID::mk(myKey)); tuple->freeze(); nodeTable->insert(tuple); warn << "Node: " << tuple->toString() << "\n"; TableRef predecessorTable = routerConfigGenerator->getTableByName(localAddress, "pred"); TupleRef predecessorTuple = Tuple::mk(); predecessorTuple->append(Val_Str::mk("pred")); predecessorTuple->append(Val_Str::mk(localAddress)); predecessorTuple->append(Val_ID::mk(ID::mk())); predecessorTuple->append(Val_Str::mk(str("-"))); predecessorTuple->freeze(); predecessorTable->insert(predecessorTuple); warn << "Initial predecessor " << predecessorTuple->toString() << "\n"; /*TableRef nextFingerFixTable = routerConfigGenerator->getTableByName(localAddress, "nextFingerFix"); TupleRef nextFingerFixTuple = Tuple::mk(); nextFingerFixTuple->append(Val_Str::mk("nextFingerFix")); nextFingerFixTuple->append(Val_Str::mk(localAddress)); nextFingerFixTuple->append(Val_Int32::mk(0)); nextFingerFixTuple->freeze(); nextFingerFixTable->insert(nextFingerFixTuple); warn << "Next finger fix: " << nextFingerFixTuple->toString() << "\n";*/ } void sendSuccessorStream(ref< Udp> udp, ref< Router::Configuration > conf, str localAddress) { // have something that populates the table of successors. For testing purposes SuccessorGenerator* successorGenerator = new SuccessorGenerator(); ElementSpecRef sourceS = conf->addElement(New refcounted< FunctorSource >(str("SuccessorSource:"), successorGenerator)); ElementSpecRef print = conf->addElement(New refcounted< Print >(strbuf("SuccessorSource"))); // The timed pusher ElementSpecRef pushS = conf->addElement(New refcounted< TimedPullPush >(strbuf("SuccessorPush:"), 2)); // And a slot from which to pull ElementSpecRef slotS = conf->addElement(New refcounted< Slot >(strbuf("SuccessorSlot:"))); ElementSpecRef encap = conf->addElement(New refcounted< PelTransform >("SuccessorEncap", "$1 pop \ $0 ->t $1 append $2 append $3 append pop")); // the rest ElementSpecRef marshal = conf->addElement(New refcounted< MarshalField >("SuccessorMarshalField", 1)); ElementSpecRef route = conf->addElement(New refcounted< StrToSockaddr >(strbuf("SuccessorStrToSocket"), 0)); ElementSpecRef udpTx = conf->addElement(udp->get_tx()); conf->hookUp(sourceS, 0, print, 0); conf->hookUp(print, 0, pushS, 0); conf->hookUp(pushS, 0, slotS, 0); conf->hookUp(slotS, 0, encap, 0); conf->hookUp(encap, 0, marshal, 0); conf->hookUp(marshal, 0, route, 0); conf->hookUp(route, 0, udpTx, 0); } void initiateJoinRequest(ref< Rtr_ConfGen > routerConfigGenerator, ref< Router::Configuration > conf, str localAddress, double delay) { // My next finger fix tuple TupleRef joinEventTuple = Tuple::mk(); joinEventTuple->append(Val_Str::mk("join")); joinEventTuple->append(Val_Str::mk(localAddress)); joinEventTuple->append(Val_Int32::mk(random())); joinEventTuple->freeze(); ElementSpecRef sourceS = conf->addElement(New refcounted< TupleSource >(str("JoinEventSource:") << localAddress, joinEventTuple)); // The once pusher ElementSpecRef onceS = conf->addElement(New refcounted< TimedPullPush >(strbuf("JoinEventPush:") << localAddress, delay, // run immediately 1 // run once )); ElementSpecRef slotS = conf->addElement(New refcounted< Slot >(strbuf("JoinEventSlot:"))); // Link everything conf->hookUp(sourceS, 0, onceS, 0); conf->hookUp(onceS, 0, slotS, 0); routerConfigGenerator->registerUDPPushSenders(slotS); } /** Test lookups. */ void startChordInDatalog(LoggerI::Level level, ref< OL_Context> ctxt, str datalogFile, str localAddress, int port, str landmarkAddress, double delay) { // create dataflow for translated chord lookup rules Router::ConfigurationRef conf = New refcounted< Router::Configuration >(); ref< Rtr_ConfGen > routerConfigGenerator = New refcounted< Rtr_ConfGen >(ctxt, conf, false, DEBUG, CC, datalogFile); routerConfigGenerator->createTables(localAddress); ref< Udp > udp = New refcounted< Udp > (localAddress, port); routerConfigGenerator->clear(); initiateJoinRequest(routerConfigGenerator, conf, localAddress, delay); routerConfigGenerator->configureRouter(udp, localAddress); initializeBaseTables(ctxt, routerConfigGenerator, localAddress); // synthetically generate stream of successors to test replacement policies // at one node ref< Udp > bootstrapUdp = New refcounted< Udp > (localAddress, 20000 + port); if (TEST_SUCCESSOR) { sendSuccessorStream(bootstrapUdp, conf, localAddress); } TableRef landmarkNodeTable = routerConfigGenerator->getTableByName(localAddress, "landmark"); TupleRef landmark = Tuple::mk(); landmark->append(Val_Str::mk("landmark")); landmark->append(Val_Str::mk(localAddress)); landmark->append(Val_Str::mk(landmarkAddress)); landmark->freeze(); warn << "Insert landmark node " << landmark->toString() << "\n"; landmarkNodeTable->insert(landmark); RouterRef router = New refcounted< Router >(conf, level); if (router->initialize(router) == 0) { warn << "Correctly initialized network of chord lookup flows.\n"; } else { warn << "** Failed to initialize correct spec\n"; return; } // Activate the router router->activate(); // Run the router amain(); } <commit_msg>eager<commit_after>// -*- c-basic-offset: 2; related-file-name: "" -*- /* * @(#)$Id$ * * Copyright (c) 2004 Intel Corporation. All rights reserved. * * This file is distributed under the terms in the attached INTEL-LICENSE file. * If you do not find these files, copies can be found by writing to: * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, * Berkeley, CA, 94704. Attention: Intel License Inquiry. * * DESCRIPTION: A chord dataflow. * */ #if HAVE_CONFIG_H #include <config.h> #endif /* HAVE_CONFIG_H */ #include <async.h> #include <arpc.h> #include <iostream> #include <stdlib.h> #include "tuple.h" #include "router.h" #include "val_int32.h" #include "val_uint32.h" #include "val_str.h" #include "val_id.h" #include "ol_lexer.h" #include "ol_context.h" #include "rtr_confgen.h" #include "udp.h" bool DEBUG = false; bool CC = false; bool TEST_SUCCESSOR = false; bool TEST_LOOKUP = false; void killJoin() { exit(0); } str LOCAL("127.0.0.1:10000"); str REMOTE("Remote.com"); str FINGERIP("Finger.com"); struct SuccessorGenerator : public FunctorSource::Generator { TupleRef operator()() { TupleRef tuple = Tuple::mk(); tuple->append(Val_Str::mk("succ")); str myAddress = str(strbuf() << LOCAL); tuple->append(Val_Str::mk(myAddress)); IDRef successor = ID::mk((uint32_t) rand()); tuple->append(Val_ID::mk(successor)); str succAddress = str(strbuf() << successor->toString() << "IP"); tuple->append(Val_Str::mk(succAddress)); tuple->freeze(); return tuple; } }; // this allows us to isolate and test just the finger lookup rules void fakeFingersSuccessors(ref< OL_Context> ctxt, ref<Rtr_ConfGen> routerConfigGenerator, str localAddress, IDRef me) { TableRef fingerTable = routerConfigGenerator->getTableByName(localAddress, "finger"); OL_Context::TableInfo* fingerTableInfo = ctxt->getTableInfos()->find("finger")->second; // Fill up the table with fingers for (int i = 0; i < fingerTableInfo->size; i++) { TupleRef tuple = Tuple::mk(); tuple->append(Val_Str::mk("finger")); str myAddress = str(strbuf() << localAddress); tuple->append(Val_Str::mk(myAddress)); tuple->append(Val_Int32::mk(i)); IDRef target = ID::mk((uint32_t) 0X1)->shift(i)->add(me); IDRef best = ID::mk()->add(target)->add(ID::mk((uint32_t) i*10)); tuple->append(Val_ID::mk(best)); str address = str(strbuf() << "Finger:" << (i / 2)); tuple->append(Val_Str::mk(address)); tuple->freeze(); fingerTable->insert(tuple); warn << tuple->toString() << "\n"; } // fake the best successor table. Only for testing purposes. TableRef bestSuccessorTable = routerConfigGenerator->getTableByName(localAddress, "bestSucc"); TupleRef tuple = Tuple::mk(); tuple->append(Val_Str::mk("bestSucc")); str myAddress = str(strbuf() << localAddress); tuple->append(Val_Str::mk(myAddress)); IDRef target = ID::mk((uint32_t) 0X1)->add(me); tuple->append(Val_ID::mk(target)); str address = str(strbuf() << "Finger:" << 0); tuple->append(Val_Str::mk(address)); tuple->freeze(); bestSuccessorTable->insert(tuple); warn << "BestSucc: " << tuple->toString() << "\n"; } void initializeBaseTables(ref< OL_Context> ctxt, ref<Rtr_ConfGen> routerConfigGenerator, str localAddress) { // create information on the node itself uint32_t random[ID::WORDS]; for (uint32_t i = 0; i < ID::WORDS; i++) { random[i] = rand(); } IDRef myKey = ID::mk(random); //IDRef myKey = ID::mk((uint32_t) 1); if (TEST_LOOKUP) { // fake fingers and best successors fakeFingersSuccessors(ctxt, routerConfigGenerator, localAddress, myKey); } TableRef nodeTable = routerConfigGenerator->getTableByName(localAddress, "node"); TupleRef tuple = Tuple::mk(); tuple->append(Val_Str::mk("node")); str myAddress = str(strbuf() << localAddress); tuple->append(Val_Str::mk(myAddress)); tuple->append(Val_ID::mk(myKey)); tuple->freeze(); nodeTable->insert(tuple); warn << "Node: " << tuple->toString() << "\n"; TableRef predecessorTable = routerConfigGenerator->getTableByName(localAddress, "pred"); TupleRef predecessorTuple = Tuple::mk(); predecessorTuple->append(Val_Str::mk("pred")); predecessorTuple->append(Val_Str::mk(localAddress)); predecessorTuple->append(Val_ID::mk(ID::mk())); predecessorTuple->append(Val_Str::mk(str("-"))); predecessorTuple->freeze(); predecessorTable->insert(predecessorTuple); warn << "Initial predecessor " << predecessorTuple->toString() << "\n"; TableRef nextFingerFixTable = routerConfigGenerator->getTableByName(localAddress, "nextFingerFix"); TupleRef nextFingerFixTuple = Tuple::mk(); nextFingerFixTuple->append(Val_Str::mk("nextFingerFix")); nextFingerFixTuple->append(Val_Str::mk(localAddress)); nextFingerFixTuple->append(Val_Int32::mk(0)); nextFingerFixTuple->freeze(); nextFingerFixTable->insert(nextFingerFixTuple); warn << "Next finger fix: " << nextFingerFixTuple->toString() << "\n"; } void sendSuccessorStream(ref< Udp> udp, ref< Router::Configuration > conf, str localAddress) { // have something that populates the table of successors. For testing purposes SuccessorGenerator* successorGenerator = new SuccessorGenerator(); ElementSpecRef sourceS = conf->addElement(New refcounted< FunctorSource >(str("SuccessorSource:"), successorGenerator)); ElementSpecRef print = conf->addElement(New refcounted< Print >(strbuf("SuccessorSource"))); // The timed pusher ElementSpecRef pushS = conf->addElement(New refcounted< TimedPullPush >(strbuf("SuccessorPush:"), 2)); // And a slot from which to pull ElementSpecRef slotS = conf->addElement(New refcounted< Slot >(strbuf("SuccessorSlot:"))); ElementSpecRef encap = conf->addElement(New refcounted< PelTransform >("SuccessorEncap", "$1 pop \ $0 ->t $1 append $2 append $3 append pop")); // the rest ElementSpecRef marshal = conf->addElement(New refcounted< MarshalField >("SuccessorMarshalField", 1)); ElementSpecRef route = conf->addElement(New refcounted< StrToSockaddr >(strbuf("SuccessorStrToSocket"), 0)); ElementSpecRef udpTx = conf->addElement(udp->get_tx()); conf->hookUp(sourceS, 0, print, 0); conf->hookUp(print, 0, pushS, 0); conf->hookUp(pushS, 0, slotS, 0); conf->hookUp(slotS, 0, encap, 0); conf->hookUp(encap, 0, marshal, 0); conf->hookUp(marshal, 0, route, 0); conf->hookUp(route, 0, udpTx, 0); } void initiateJoinRequest(ref< Rtr_ConfGen > routerConfigGenerator, ref< Router::Configuration > conf, str localAddress, double delay) { // My next finger fix tuple TupleRef joinEventTuple = Tuple::mk(); joinEventTuple->append(Val_Str::mk("join")); joinEventTuple->append(Val_Str::mk(localAddress)); joinEventTuple->append(Val_Int32::mk(random())); joinEventTuple->freeze(); ElementSpecRef sourceS = conf->addElement(New refcounted< TupleSource >(str("JoinEventSource:") << localAddress, joinEventTuple)); // The once pusher ElementSpecRef onceS = conf->addElement(New refcounted< TimedPullPush >(strbuf("JoinEventPush:") << localAddress, delay, // run immediately 1 // run once )); ElementSpecRef slotS = conf->addElement(New refcounted< Slot >(strbuf("JoinEventSlot:"))); // Link everything conf->hookUp(sourceS, 0, onceS, 0); conf->hookUp(onceS, 0, slotS, 0); routerConfigGenerator->registerUDPPushSenders(slotS); } /** Test lookups. */ void startChordInDatalog(LoggerI::Level level, ref< OL_Context> ctxt, str datalogFile, str localAddress, int port, str landmarkAddress, double delay) { // create dataflow for translated chord lookup rules Router::ConfigurationRef conf = New refcounted< Router::Configuration >(); ref< Rtr_ConfGen > routerConfigGenerator = New refcounted< Rtr_ConfGen >(ctxt, conf, false, DEBUG, CC, datalogFile); routerConfigGenerator->createTables(localAddress); ref< Udp > udp = New refcounted< Udp > (localAddress, port); routerConfigGenerator->clear(); initiateJoinRequest(routerConfigGenerator, conf, localAddress, delay); routerConfigGenerator->configureRouter(udp, localAddress); initializeBaseTables(ctxt, routerConfigGenerator, localAddress); // synthetically generate stream of successors to test replacement policies // at one node ref< Udp > bootstrapUdp = New refcounted< Udp > (localAddress, 20000 + port); if (TEST_SUCCESSOR) { sendSuccessorStream(bootstrapUdp, conf, localAddress); } TableRef landmarkNodeTable = routerConfigGenerator->getTableByName(localAddress, "landmark"); TupleRef landmark = Tuple::mk(); landmark->append(Val_Str::mk("landmark")); landmark->append(Val_Str::mk(localAddress)); landmark->append(Val_Str::mk(landmarkAddress)); landmark->freeze(); warn << "Insert landmark node " << landmark->toString() << "\n"; landmarkNodeTable->insert(landmark); RouterRef router = New refcounted< Router >(conf, level); if (router->initialize(router) == 0) { warn << "Correctly initialized network of chord lookup flows.\n"; } else { warn << "** Failed to initialize correct spec\n"; return; } // Activate the router router->activate(); // Run the router amain(); } <|endoftext|>
<commit_before>// This file is part of MicroRestD <http://github.com/ufal/microrestd/>. // // Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // 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/. #include <chrono> #include <cstdlib> #include <string> #include <thread> #include "microrestd.h" using namespace std; using namespace ufal::microrestd; class file_service : public rest_service { class file_generator : public response_generator { public: file_generator(FILE* f) : f(f) {} ~file_generator() { if (f) fclose(f); } virtual bool generate() override { size_t data_size = data.size(); data.resize(data_size + 1024); size_t read = fread(data.data() + data_size, 1, 1024, f); data.resize(data_size + read); // Now sleep for 2 seconds to simulate hard work :-) this_thread::sleep_for(chrono::seconds(2)); return read; } virtual string_piece current() const override { return string_piece(data.data(), data.size()); } virtual void consume(size_t length) override { if (length >= data.size()) data.clear(); else if (length) data.erase(data.begin(), data.begin() + length); } private: FILE* f; vector<char> data; }; public: virtual bool handle(rest_request& req) override { fprintf(stderr, "Serving url %s via method %s\n", req.url.c_str(), req.method.c_str()); if (req.method != "HEAD" && req.method != "GET") return req.respond_method_not_allowed("HEAD, GET"); if (!req.url.empty()) { FILE* f = fopen(req.url.c_str() + 1, "rb"); if (f) return req.respond("application/octet-stream", new file_generator(f)); } return req.respond_not_found(); } }; int main(int argc, char* argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s port [threads] [connection_limit]\n", argv[0]); return 1; } int port = stoi(argv[1]); int threads = argc >= 3 ? stoi(argv[2]) : 0; int connection_limit = argc >= 4 ? stoi(argv[3]) : 2; rest_server server; server.set_max_connections(connection_limit); server.set_threads(threads); file_service service; if (!server.start(&service, port)) { fprintf(stderr, "Cannot start REST server!\n"); return 1; } server.wait_until_closed(); return 0; } <commit_msg>Log to stderr, allow POST method.<commit_after>// This file is part of MicroRestD <http://github.com/ufal/microrestd/>. // // Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // 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/. #include <chrono> #include <cstdlib> #include <string> #include <thread> #include "microrestd.h" using namespace std; using namespace ufal::microrestd; class file_service : public rest_service { class file_generator : public response_generator { public: file_generator(FILE* f) : f(f) {} ~file_generator() { if (f) fclose(f); } virtual bool generate() override { size_t data_size = data.size(); data.resize(data_size + 1024); size_t read = fread(data.data() + data_size, 1, 1024, f); data.resize(data_size + read); // Now sleep for 2 seconds to simulate hard work :-) this_thread::sleep_for(chrono::seconds(2)); return read; } virtual string_piece current() const override { return string_piece(data.data(), data.size()); } virtual void consume(size_t length) override { if (length >= data.size()) data.clear(); else if (length) data.erase(data.begin(), data.begin() + length); } private: FILE* f; vector<char> data; }; public: virtual bool handle(rest_request& req) override { if (req.method != "HEAD" && req.method != "GET" && req.method != "POST") return req.respond_method_not_allowed("HEAD, GET, POST"); if (!req.url.empty()) { FILE* f = fopen(req.url.c_str() + 1, "rb"); if (f) return req.respond("application/octet-stream", new file_generator(f)); } return req.respond_not_found(); } }; int main(int argc, char* argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s port [threads] [connection_limit]\n", argv[0]); return 1; } int port = stoi(argv[1]); int threads = argc >= 3 ? stoi(argv[2]) : 0; int connection_limit = argc >= 4 ? stoi(argv[3]) : 2; rest_server server; server.set_log_file(stderr); server.set_max_connections(connection_limit); server.set_threads(threads); file_service service; if (!server.start(&service, port)) { fprintf(stderr, "Cannot start REST server!\n"); return 1; } server.wait_until_closed(); return 0; } <|endoftext|>
<commit_before>//===-- BinaryHolder.cpp --------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that aims to be a dropin replacement for // Darwin's dsymutil. // //===----------------------------------------------------------------------===// #include "BinaryHolder.h" #include "llvm/Object/MachO.h" #include "llvm/Support/raw_ostream.h" namespace llvm { namespace dsymutil { static std::vector<MemoryBufferRef> getMachOFatMemoryBuffers(StringRef Filename, MemoryBuffer &Mem, object::MachOUniversalBinary &Fat) { std::vector<MemoryBufferRef> Buffers; StringRef FatData = Fat.getData(); for (auto It = Fat.begin_objects(), End = Fat.end_objects(); It != End; ++It) { StringRef ObjData = FatData.substr(It->getOffset(), It->getSize()); Buffers.emplace_back(ObjData, Filename); } return Buffers; } void BinaryHolder::changeBackingMemoryBuffer( std::unique_ptr<MemoryBuffer> &&Buf) { CurrentArchives.clear(); CurrentObjectFiles.clear(); CurrentFatBinary.reset(); CurrentMemoryBuffer = std::move(Buf); } ErrorOr<std::vector<MemoryBufferRef>> BinaryHolder::GetMemoryBuffersForFile( StringRef Filename, sys::TimePoint<std::chrono::seconds> Timestamp) { if (Verbose) outs() << "trying to open '" << Filename << "'\n"; // Try that first as it doesn't involve any filesystem access. if (auto ErrOrArchiveMembers = GetArchiveMemberBuffers(Filename, Timestamp)) return *ErrOrArchiveMembers; // If the name ends with a closing paren, there is a huge chance // it is an archive member specification. if (Filename.endswith(")")) if (auto ErrOrArchiveMembers = MapArchiveAndGetMemberBuffers(Filename, Timestamp)) return *ErrOrArchiveMembers; // Otherwise, just try opening a standard file. If this is an // archive member specifiaction and any of the above didn't handle it // (either because the archive is not there anymore, or because the // archive doesn't contain the requested member), this will still // provide a sensible error message. auto ErrOrFile = MemoryBuffer::getFileOrSTDIN(Filename); if (auto Err = ErrOrFile.getError()) return Err; changeBackingMemoryBuffer(std::move(*ErrOrFile)); if (Verbose) outs() << "\tloaded file.\n"; auto ErrOrFat = object::MachOUniversalBinary::create( CurrentMemoryBuffer->getMemBufferRef()); if (!ErrOrFat) { consumeError(ErrOrFat.takeError()); // Not a fat binary must be a standard one. Return a one element vector. return std::vector<MemoryBufferRef>{CurrentMemoryBuffer->getMemBufferRef()}; } CurrentFatBinary = std::move(*ErrOrFat); CurrentFatBinaryName = Filename; return getMachOFatMemoryBuffers(CurrentFatBinaryName, *CurrentMemoryBuffer, *CurrentFatBinary); } ErrorOr<std::vector<MemoryBufferRef>> BinaryHolder::GetArchiveMemberBuffers( StringRef Filename, sys::TimePoint<std::chrono::seconds> Timestamp) { if (CurrentArchives.empty()) return make_error_code(errc::no_such_file_or_directory); StringRef CurArchiveName = CurrentArchives.front()->getFileName(); if (!Filename.startswith(Twine(CurArchiveName, "(").str())) return make_error_code(errc::no_such_file_or_directory); // Remove the archive name and the parens around the archive member name. Filename = Filename.substr(CurArchiveName.size() + 1).drop_back(); std::vector<MemoryBufferRef> Buffers; Buffers.reserve(CurrentArchives.size()); for (const auto &CurrentArchive : CurrentArchives) { Error Err = Error::success(); for (auto Child : CurrentArchive->children(Err)) { if (auto NameOrErr = Child.getName()) { if (*NameOrErr == Filename) { auto ModTimeOrErr = Child.getLastModified(); if (!ModTimeOrErr) return errorToErrorCode(ModTimeOrErr.takeError()); if (Timestamp != sys::TimePoint<>() && Timestamp != ModTimeOrErr.get()) { if (Verbose) outs() << "\tmember had timestamp mismatch.\n"; continue; } if (Verbose) outs() << "\tfound member in current archive.\n"; auto ErrOrMem = Child.getMemoryBufferRef(); if (!ErrOrMem) return errorToErrorCode(ErrOrMem.takeError()); Buffers.push_back(*ErrOrMem); } } } if (Err) return errorToErrorCode(std::move(Err)); } if (Buffers.empty()) return make_error_code(errc::no_such_file_or_directory); return Buffers; } ErrorOr<std::vector<MemoryBufferRef>> BinaryHolder::MapArchiveAndGetMemberBuffers( StringRef Filename, sys::TimePoint<std::chrono::seconds> Timestamp) { StringRef ArchiveFilename = Filename.substr(0, Filename.find('(')); auto ErrOrBuff = MemoryBuffer::getFileOrSTDIN(ArchiveFilename); if (auto Err = ErrOrBuff.getError()) return Err; if (Verbose) outs() << "\topened new archive '" << ArchiveFilename << "'\n"; changeBackingMemoryBuffer(std::move(*ErrOrBuff)); std::vector<MemoryBufferRef> ArchiveBuffers; auto ErrOrFat = object::MachOUniversalBinary::create( CurrentMemoryBuffer->getMemBufferRef()); if (!ErrOrFat) { consumeError(ErrOrFat.takeError()); // Not a fat binary must be a standard one. ArchiveBuffers.push_back(CurrentMemoryBuffer->getMemBufferRef()); } else { CurrentFatBinary = std::move(*ErrOrFat); CurrentFatBinaryName = ArchiveFilename; ArchiveBuffers = getMachOFatMemoryBuffers( CurrentFatBinaryName, *CurrentMemoryBuffer, *CurrentFatBinary); } for (auto MemRef : ArchiveBuffers) { auto ErrOrArchive = object::Archive::create(MemRef); if (!ErrOrArchive) return errorToErrorCode(ErrOrArchive.takeError()); CurrentArchives.push_back(std::move(*ErrOrArchive)); } return GetArchiveMemberBuffers(Filename, Timestamp); } ErrorOr<const object::ObjectFile &> BinaryHolder::getObjfileForArch(const Triple &T) { for (const auto &Obj : CurrentObjectFiles) { if (const auto *MachO = dyn_cast<object::MachOObjectFile>(Obj.get())) { if (MachO->getArchTriple().str() == T.str()) return *MachO; } else if (Obj->getArch() == T.getArch()) return *Obj; } return make_error_code(object::object_error::arch_not_found); } ErrorOr<std::vector<const object::ObjectFile *>> BinaryHolder::GetObjectFiles(StringRef Filename, sys::TimePoint<std::chrono::seconds> Timestamp) { auto ErrOrMemBufferRefs = GetMemoryBuffersForFile(Filename, Timestamp); if (auto Err = ErrOrMemBufferRefs.getError()) return Err; std::vector<const object::ObjectFile *> Objects; Objects.reserve(ErrOrMemBufferRefs->size()); CurrentObjectFiles.clear(); for (auto MemBuf : *ErrOrMemBufferRefs) { auto ErrOrObjectFile = object::ObjectFile::createObjectFile(MemBuf); if (!ErrOrObjectFile) return errorToErrorCode(ErrOrObjectFile.takeError()); Objects.push_back(ErrOrObjectFile->get()); CurrentObjectFiles.push_back(std::move(*ErrOrObjectFile)); } return std::move(Objects); } } // namespace dsymutil } // namespace llvm <commit_msg>[dsymutil] Force mmap'ing of binaries<commit_after>//===-- BinaryHolder.cpp --------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program is a utility that aims to be a dropin replacement for // Darwin's dsymutil. // //===----------------------------------------------------------------------===// #include "BinaryHolder.h" #include "llvm/Object/MachO.h" #include "llvm/Support/raw_ostream.h" namespace llvm { namespace dsymutil { static std::vector<MemoryBufferRef> getMachOFatMemoryBuffers(StringRef Filename, MemoryBuffer &Mem, object::MachOUniversalBinary &Fat) { std::vector<MemoryBufferRef> Buffers; StringRef FatData = Fat.getData(); for (auto It = Fat.begin_objects(), End = Fat.end_objects(); It != End; ++It) { StringRef ObjData = FatData.substr(It->getOffset(), It->getSize()); Buffers.emplace_back(ObjData, Filename); } return Buffers; } void BinaryHolder::changeBackingMemoryBuffer( std::unique_ptr<MemoryBuffer> &&Buf) { CurrentArchives.clear(); CurrentObjectFiles.clear(); CurrentFatBinary.reset(); CurrentMemoryBuffer = std::move(Buf); } ErrorOr<std::vector<MemoryBufferRef>> BinaryHolder::GetMemoryBuffersForFile( StringRef Filename, sys::TimePoint<std::chrono::seconds> Timestamp) { if (Verbose) outs() << "trying to open '" << Filename << "'\n"; // Try that first as it doesn't involve any filesystem access. if (auto ErrOrArchiveMembers = GetArchiveMemberBuffers(Filename, Timestamp)) return *ErrOrArchiveMembers; // If the name ends with a closing paren, there is a huge chance // it is an archive member specification. if (Filename.endswith(")")) if (auto ErrOrArchiveMembers = MapArchiveAndGetMemberBuffers(Filename, Timestamp)) return *ErrOrArchiveMembers; // Otherwise, just try opening a standard file. If this is an // archive member specifiaction and any of the above didn't handle it // (either because the archive is not there anymore, or because the // archive doesn't contain the requested member), this will still // provide a sensible error message. auto ErrOrFile = MemoryBuffer::getFileOrSTDIN(Filename, -1, false); if (auto Err = ErrOrFile.getError()) return Err; changeBackingMemoryBuffer(std::move(*ErrOrFile)); if (Verbose) outs() << "\tloaded file.\n"; auto ErrOrFat = object::MachOUniversalBinary::create( CurrentMemoryBuffer->getMemBufferRef()); if (!ErrOrFat) { consumeError(ErrOrFat.takeError()); // Not a fat binary must be a standard one. Return a one element vector. return std::vector<MemoryBufferRef>{CurrentMemoryBuffer->getMemBufferRef()}; } CurrentFatBinary = std::move(*ErrOrFat); CurrentFatBinaryName = Filename; return getMachOFatMemoryBuffers(CurrentFatBinaryName, *CurrentMemoryBuffer, *CurrentFatBinary); } ErrorOr<std::vector<MemoryBufferRef>> BinaryHolder::GetArchiveMemberBuffers( StringRef Filename, sys::TimePoint<std::chrono::seconds> Timestamp) { if (CurrentArchives.empty()) return make_error_code(errc::no_such_file_or_directory); StringRef CurArchiveName = CurrentArchives.front()->getFileName(); if (!Filename.startswith(Twine(CurArchiveName, "(").str())) return make_error_code(errc::no_such_file_or_directory); // Remove the archive name and the parens around the archive member name. Filename = Filename.substr(CurArchiveName.size() + 1).drop_back(); std::vector<MemoryBufferRef> Buffers; Buffers.reserve(CurrentArchives.size()); for (const auto &CurrentArchive : CurrentArchives) { Error Err = Error::success(); for (auto Child : CurrentArchive->children(Err)) { if (auto NameOrErr = Child.getName()) { if (*NameOrErr == Filename) { auto ModTimeOrErr = Child.getLastModified(); if (!ModTimeOrErr) return errorToErrorCode(ModTimeOrErr.takeError()); if (Timestamp != sys::TimePoint<>() && Timestamp != ModTimeOrErr.get()) { if (Verbose) outs() << "\tmember had timestamp mismatch.\n"; continue; } if (Verbose) outs() << "\tfound member in current archive.\n"; auto ErrOrMem = Child.getMemoryBufferRef(); if (!ErrOrMem) return errorToErrorCode(ErrOrMem.takeError()); Buffers.push_back(*ErrOrMem); } } } if (Err) return errorToErrorCode(std::move(Err)); } if (Buffers.empty()) return make_error_code(errc::no_such_file_or_directory); return Buffers; } ErrorOr<std::vector<MemoryBufferRef>> BinaryHolder::MapArchiveAndGetMemberBuffers( StringRef Filename, sys::TimePoint<std::chrono::seconds> Timestamp) { StringRef ArchiveFilename = Filename.substr(0, Filename.find('(')); auto ErrOrBuff = MemoryBuffer::getFileOrSTDIN(ArchiveFilename, -1, false); if (auto Err = ErrOrBuff.getError()) return Err; if (Verbose) outs() << "\topened new archive '" << ArchiveFilename << "'\n"; changeBackingMemoryBuffer(std::move(*ErrOrBuff)); std::vector<MemoryBufferRef> ArchiveBuffers; auto ErrOrFat = object::MachOUniversalBinary::create( CurrentMemoryBuffer->getMemBufferRef()); if (!ErrOrFat) { consumeError(ErrOrFat.takeError()); // Not a fat binary must be a standard one. ArchiveBuffers.push_back(CurrentMemoryBuffer->getMemBufferRef()); } else { CurrentFatBinary = std::move(*ErrOrFat); CurrentFatBinaryName = ArchiveFilename; ArchiveBuffers = getMachOFatMemoryBuffers( CurrentFatBinaryName, *CurrentMemoryBuffer, *CurrentFatBinary); } for (auto MemRef : ArchiveBuffers) { auto ErrOrArchive = object::Archive::create(MemRef); if (!ErrOrArchive) return errorToErrorCode(ErrOrArchive.takeError()); CurrentArchives.push_back(std::move(*ErrOrArchive)); } return GetArchiveMemberBuffers(Filename, Timestamp); } ErrorOr<const object::ObjectFile &> BinaryHolder::getObjfileForArch(const Triple &T) { for (const auto &Obj : CurrentObjectFiles) { if (const auto *MachO = dyn_cast<object::MachOObjectFile>(Obj.get())) { if (MachO->getArchTriple().str() == T.str()) return *MachO; } else if (Obj->getArch() == T.getArch()) return *Obj; } return make_error_code(object::object_error::arch_not_found); } ErrorOr<std::vector<const object::ObjectFile *>> BinaryHolder::GetObjectFiles(StringRef Filename, sys::TimePoint<std::chrono::seconds> Timestamp) { auto ErrOrMemBufferRefs = GetMemoryBuffersForFile(Filename, Timestamp); if (auto Err = ErrOrMemBufferRefs.getError()) return Err; std::vector<const object::ObjectFile *> Objects; Objects.reserve(ErrOrMemBufferRefs->size()); CurrentObjectFiles.clear(); for (auto MemBuf : *ErrOrMemBufferRefs) { auto ErrOrObjectFile = object::ObjectFile::createObjectFile(MemBuf); if (!ErrOrObjectFile) return errorToErrorCode(ErrOrObjectFile.takeError()); Objects.push_back(ErrOrObjectFile->get()); CurrentObjectFiles.push_back(std::move(*ErrOrObjectFile)); } return std::move(Objects); } } // namespace dsymutil } // namespace llvm <|endoftext|>
<commit_before> #include "diff_system.h" #include "libmesh_logging.h" #include "linear_solver.h" #include "newton_solver.h" #include "numeric_vector.h" #include "sparse_matrix.h" #include "dof_map.h" NewtonSolver::NewtonSolver (sys_type& s) : Parent(s), require_residual_reduction(false), minsteplength(0.0), linear_solver(LinearSolver<Number>::build()) { } NewtonSolver::~NewtonSolver () { } void NewtonSolver::reinit() { Parent::reinit(); linear_solver->clear(); } void NewtonSolver::solve() { START_LOG("solve()", "NewtonSolver"); // Amount by which nonlinear residual should exceed linear solver // tolerance const Real relative_tolerance = 1.e-3; NumericVector<Number> &solution = *(_system.solution); NumericVector<Number> &newton_iterate = _system.get_vector("_nonlinear_solution"); newton_iterate.close(); // solution.close(); NumericVector<Number> &rhs = *(_system.rhs); SparseMatrix<Number> &matrix = *(_system.matrix); // Prepare to take incomplete steps Real last_residual=0.; // Set starting linear tolerance Real current_linear_tolerance = initial_linear_tolerance; // Now we begin the nonlinear loop for (unsigned int l=0; l<max_nonlinear_iterations; ++l) { if (!quiet) std::cout << "Assembling System" << std::endl; PAUSE_LOG("solve()", "NewtonSolver"); _system.assembly(true, true); RESTART_LOG("solve()", "NewtonSolver"); rhs.close(); Real current_residual = rhs.l2_norm(); last_residual = current_residual; max_residual_norm = std::max (current_residual, max_residual_norm); // Compute the l2 norm of the whole solution Real norm_total = newton_iterate.l2_norm(); max_solution_norm = std::max(max_solution_norm, norm_total); if (!quiet) std::cout << "Nonlinear Residual: " << current_residual << std::endl; // Make sure our linear tolerance is low enough if (current_linear_tolerance > current_residual * relative_tolerance) { current_linear_tolerance = current_residual * relative_tolerance; } // But don't let it be zero if (current_linear_tolerance == 0.) { current_linear_tolerance = TOLERANCE * TOLERANCE; } // At this point newton_iterate is the current guess, and // solution is now about to become the NEGATIVE of the next // Newton step. // Our best initial guess for the solution is zero! solution.zero(); if (!quiet) std::cout << "Linear solve starting" << std::endl; PAUSE_LOG("solve()", "NewtonSolver"); // Solve the linear system. Two cases: const std::pair<unsigned int, Real> rval = (_system.have_matrix("Preconditioner")) ? // 1.) User-supplied preconditioner linear_solver->solve (matrix, _system.get_matrix("Preconditioner"), solution, rhs, current_linear_tolerance, max_linear_iterations) : // 2.) Use system matrix for the preconditioner linear_solver->solve (matrix, solution, rhs, current_linear_tolerance, max_linear_iterations); // We may need to localize a parallel solution _system.update (); RESTART_LOG("solve()", "NewtonSolver"); // The linear solver may not have fit our constraints exactly _system.get_dof_map().enforce_constraints_exactly(_system); if (!quiet) std::cout << "Linear solve finished, step " << rval.first << ", residual " << rval.second << ", tolerance " << current_linear_tolerance << std::endl; // Compute the l2 norm of the nonlinear update Real norm_delta = solution.l2_norm(); if (!quiet) std::cout << "Trying full Newton step" << std::endl; // Take a full Newton step newton_iterate.add (-1., solution); // newton_iterate.close(); // Check residual with full Newton step Real steplength = 1.; PAUSE_LOG("solve()", "NewtonSolver"); _system.assembly(true, false); RESTART_LOG("solve()", "NewtonSolver"); rhs.close(); current_residual = rhs.l2_norm(); // backtrack if necessary if (require_residual_reduction) { // but don't fiddle around if we've already converged if (test_convergence(current_residual, norm_delta)) { if (!quiet) print_convergence(l, current_residual, norm_delta); break; } while (current_residual > last_residual) { // Reduce step size to 1/2, 1/4, etc. steplength /= 2.; norm_delta /= 2.; if (!quiet) std::cout << "Shrinking Newton step to " << steplength << std::endl; newton_iterate.add (steplength, solution); // newton_iterate.close(); // Check residual with fractional Newton step PAUSE_LOG("solve()", "NewtonSolver"); _system.assembly (true, false); RESTART_LOG("solve()", "NewtonSolver"); rhs.close(); current_residual = rhs.l2_norm(); if (!quiet) std::cout << "Current Residual: " << current_residual << std::endl; if (steplength/2. < minsteplength && current_residual > last_residual) { if (!quiet) std::cout << "Inexact Newton step FAILED at step " << l << std::endl; error(); } } } // Compute the l2 norm of the whole solution norm_total = newton_iterate.l2_norm(); max_solution_norm = std::max(max_solution_norm, norm_total); // Print out information for the // nonlinear iterations. if (!quiet) std::cout << " Nonlinear step: |du|/|u| = " << norm_delta / norm_total << ", |du| = " << norm_delta << std::endl; // Terminate the solution iteration if the difference between // this iteration and the last is sufficiently small. if (!quiet) print_convergence(l, current_residual, norm_delta / steplength); if (test_convergence(current_residual, norm_delta / steplength)) { break; } if (l >= max_nonlinear_iterations - 1) { std::cout << " Nonlinear solver DIVERGED at step " << l << " with norm " << norm_total << std::endl; error(); continue; } } // end nonlinear loop // Copy the final nonlinear iterate into the current_solution, // for other libMesh functions that expect it solution = newton_iterate; // solution.close(); // We may need to localize a parallel solution _system.update (); STOP_LOG("solve()", "NewtonSolver"); } bool NewtonSolver::test_convergence(Real current_residual, Real step_norm) { // We haven't converged unless we pass a convergence test bool has_converged = false; // Is our absolute residual low enough? if (current_residual < absolute_residual_tolerance) has_converged = true; // Is our relative residual low enough? if ((current_residual / max_residual_norm) < relative_residual_tolerance) has_converged = true; // Is our absolute Newton step size small enough? if (step_norm < absolute_step_tolerance) has_converged = true; // Is our relative Newton step size small enough? if (step_norm / max_solution_norm < relative_step_tolerance) has_converged = true; return has_converged; } void NewtonSolver::print_convergence(unsigned int step_num, Real current_residual, Real step_norm) { // Is our absolute residual low enough? if (current_residual < absolute_residual_tolerance) { std::cout << " Nonlinear solver converged, step " << step_num << ", residual " << current_residual << std::endl; } else if (absolute_residual_tolerance) { std::cout << " Nonlinear solver current_residual " << current_residual << " > " << (absolute_residual_tolerance) << std::endl; } // Is our relative residual low enough? if ((current_residual / max_residual_norm) < relative_residual_tolerance) { std::cout << " Nonlinear solver converged, step " << step_num << ", residual reduction " << current_residual / max_residual_norm << " < " << relative_residual_tolerance << std::endl; } else if (relative_residual_tolerance) { if (!quiet) std::cout << " Nonlinear solver relative residual " << (current_residual / max_residual_norm) << " > " << relative_residual_tolerance << std::endl; } // Is our absolute Newton step size small enough? if (step_norm < absolute_step_tolerance) { std::cout << " Nonlinear solver converged, step " << step_num << ", absolute step size " << step_norm << " < " << absolute_step_tolerance << std::endl; } else if (absolute_step_tolerance) { std::cout << " Nonlinear solver absolute step size " << step_norm << " > " << absolute_step_tolerance << std::endl; } // Is our relative Newton step size small enough? if (step_norm / max_solution_norm < relative_step_tolerance) { std::cout << " Nonlinear solver converged, step " << step_num << ", relative step size " << (step_norm / max_solution_norm) << " < " << relative_step_tolerance << std::endl; } else if (relative_step_tolerance) { std::cout << " Nonlinear solver relative step size " << (step_norm / max_solution_norm) << " > " << relative_step_tolerance << std::endl; } } <commit_msg>Solver error messages should distinguish between running out of iterations vs. getting NaN solutions<commit_after> #include "diff_system.h" #include "libmesh_logging.h" #include "linear_solver.h" #include "newton_solver.h" #include "numeric_vector.h" #include "sparse_matrix.h" #include "dof_map.h" NewtonSolver::NewtonSolver (sys_type& s) : Parent(s), require_residual_reduction(false), minsteplength(0.0), linear_solver(LinearSolver<Number>::build()) { } NewtonSolver::~NewtonSolver () { } void NewtonSolver::reinit() { Parent::reinit(); linear_solver->clear(); } void NewtonSolver::solve() { START_LOG("solve()", "NewtonSolver"); // Amount by which nonlinear residual should exceed linear solver // tolerance const Real relative_tolerance = 1.e-3; NumericVector<Number> &solution = *(_system.solution); NumericVector<Number> &newton_iterate = _system.get_vector("_nonlinear_solution"); newton_iterate.close(); // solution.close(); NumericVector<Number> &rhs = *(_system.rhs); SparseMatrix<Number> &matrix = *(_system.matrix); // Prepare to take incomplete steps Real last_residual=0.; // Set starting linear tolerance Real current_linear_tolerance = initial_linear_tolerance; // Now we begin the nonlinear loop for (unsigned int l=0; l<max_nonlinear_iterations; ++l) { if (!quiet) std::cout << "Assembling System" << std::endl; PAUSE_LOG("solve()", "NewtonSolver"); _system.assembly(true, true); RESTART_LOG("solve()", "NewtonSolver"); rhs.close(); Real current_residual = rhs.l2_norm(); last_residual = current_residual; if (isnan(current_residual)) { std::cout << " Nonlinear solver DIVERGED at step " << l << " with norm Not-a-Number" << std::endl; error(); continue; } max_residual_norm = std::max (current_residual, max_residual_norm); // Compute the l2 norm of the whole solution Real norm_total = newton_iterate.l2_norm(); max_solution_norm = std::max(max_solution_norm, norm_total); if (!quiet) std::cout << "Nonlinear Residual: " << current_residual << std::endl; // Make sure our linear tolerance is low enough if (current_linear_tolerance > current_residual * relative_tolerance) { current_linear_tolerance = current_residual * relative_tolerance; } // But don't let it be zero if (current_linear_tolerance == 0.) { current_linear_tolerance = TOLERANCE * TOLERANCE; } // At this point newton_iterate is the current guess, and // solution is now about to become the NEGATIVE of the next // Newton step. // Our best initial guess for the solution is zero! solution.zero(); if (!quiet) std::cout << "Linear solve starting" << std::endl; PAUSE_LOG("solve()", "NewtonSolver"); // Solve the linear system. Two cases: const std::pair<unsigned int, Real> rval = (_system.have_matrix("Preconditioner")) ? // 1.) User-supplied preconditioner linear_solver->solve (matrix, _system.get_matrix("Preconditioner"), solution, rhs, current_linear_tolerance, max_linear_iterations) : // 2.) Use system matrix for the preconditioner linear_solver->solve (matrix, solution, rhs, current_linear_tolerance, max_linear_iterations); // We may need to localize a parallel solution _system.update (); RESTART_LOG("solve()", "NewtonSolver"); // The linear solver may not have fit our constraints exactly _system.get_dof_map().enforce_constraints_exactly(_system); if (!quiet) std::cout << "Linear solve finished, step " << rval.first << ", residual " << rval.second << ", tolerance " << current_linear_tolerance << std::endl; // Compute the l2 norm of the nonlinear update Real norm_delta = solution.l2_norm(); if (!quiet) std::cout << "Trying full Newton step" << std::endl; // Take a full Newton step newton_iterate.add (-1., solution); // newton_iterate.close(); // Check residual with full Newton step Real steplength = 1.; PAUSE_LOG("solve()", "NewtonSolver"); _system.assembly(true, false); RESTART_LOG("solve()", "NewtonSolver"); rhs.close(); current_residual = rhs.l2_norm(); // backtrack if necessary if (require_residual_reduction) { // but don't fiddle around if we've already converged if (test_convergence(current_residual, norm_delta)) { if (!quiet) print_convergence(l, current_residual, norm_delta); break; } while (current_residual > last_residual) { // Reduce step size to 1/2, 1/4, etc. steplength /= 2.; norm_delta /= 2.; if (!quiet) std::cout << "Shrinking Newton step to " << steplength << std::endl; newton_iterate.add (steplength, solution); // newton_iterate.close(); // Check residual with fractional Newton step PAUSE_LOG("solve()", "NewtonSolver"); _system.assembly (true, false); RESTART_LOG("solve()", "NewtonSolver"); rhs.close(); current_residual = rhs.l2_norm(); if (!quiet) std::cout << "Current Residual: " << current_residual << std::endl; if (steplength/2. < minsteplength && current_residual > last_residual) { std::cout << "Inexact Newton step FAILED at step " << l << std::endl; error(); } } } // Compute the l2 norm of the whole solution norm_total = newton_iterate.l2_norm(); max_solution_norm = std::max(max_solution_norm, norm_total); // Print out information for the // nonlinear iterations. if (!quiet) std::cout << " Nonlinear step: |du|/|u| = " << norm_delta / norm_total << ", |du| = " << norm_delta << std::endl; // Terminate the solution iteration if the difference between // this iteration and the last is sufficiently small. if (!quiet) print_convergence(l, current_residual, norm_delta / steplength); if (test_convergence(current_residual, norm_delta / steplength)) { break; } if (l >= max_nonlinear_iterations - 1) { std::cout << " Nonlinear solver FAILED TO CONVERGE by step " << l << " with norm " << norm_total << std::endl; error(); continue; } } // end nonlinear loop // Copy the final nonlinear iterate into the current_solution, // for other libMesh functions that expect it solution = newton_iterate; // solution.close(); // We may need to localize a parallel solution _system.update (); STOP_LOG("solve()", "NewtonSolver"); } bool NewtonSolver::test_convergence(Real current_residual, Real step_norm) { // We haven't converged unless we pass a convergence test bool has_converged = false; // Is our absolute residual low enough? if (current_residual < absolute_residual_tolerance) has_converged = true; // Is our relative residual low enough? if ((current_residual / max_residual_norm) < relative_residual_tolerance) has_converged = true; // Is our absolute Newton step size small enough? if (step_norm < absolute_step_tolerance) has_converged = true; // Is our relative Newton step size small enough? if (step_norm / max_solution_norm < relative_step_tolerance) has_converged = true; return has_converged; } void NewtonSolver::print_convergence(unsigned int step_num, Real current_residual, Real step_norm) { // Is our absolute residual low enough? if (current_residual < absolute_residual_tolerance) { std::cout << " Nonlinear solver converged, step " << step_num << ", residual " << current_residual << std::endl; } else if (absolute_residual_tolerance) { std::cout << " Nonlinear solver current_residual " << current_residual << " > " << (absolute_residual_tolerance) << std::endl; } // Is our relative residual low enough? if ((current_residual / max_residual_norm) < relative_residual_tolerance) { std::cout << " Nonlinear solver converged, step " << step_num << ", residual reduction " << current_residual / max_residual_norm << " < " << relative_residual_tolerance << std::endl; } else if (relative_residual_tolerance) { if (!quiet) std::cout << " Nonlinear solver relative residual " << (current_residual / max_residual_norm) << " > " << relative_residual_tolerance << std::endl; } // Is our absolute Newton step size small enough? if (step_norm < absolute_step_tolerance) { std::cout << " Nonlinear solver converged, step " << step_num << ", absolute step size " << step_norm << " < " << absolute_step_tolerance << std::endl; } else if (absolute_step_tolerance) { std::cout << " Nonlinear solver absolute step size " << step_norm << " > " << absolute_step_tolerance << std::endl; } // Is our relative Newton step size small enough? if (step_norm / max_solution_norm < relative_step_tolerance) { std::cout << " Nonlinear solver converged, step " << step_num << ", relative step size " << (step_norm / max_solution_norm) << " < " << relative_step_tolerance << std::endl; } else if (relative_step_tolerance) { std::cout << " Nonlinear solver relative step size " << (step_norm / max_solution_norm) << " > " << relative_step_tolerance << std::endl; } } <|endoftext|>
<commit_before>#include "ModuleManager.h" #include "module/ReseedableOps.h" #include <random> #include <time.h> #include <algorithm> #include <fstream> #include <iostream> #include <boost/filesystem.hpp> #include "EncodedModuleGroup.h" #include "codecs/EncodedModuleGroupCodec.h" namespace noise { ModuleManager::ModuleManager(const Options & options) : mRNG((unsigned int)time(nullptr)) { boost::filesystem::path p(options.directory); p /= options.combinerModuleGroup; mCombiner = loadModuleGroup(p.string()); p.remove_filename(); for (auto it : options.centralModuleGroups) { p /= it.filename; auto inserted = mCentres.insert({it.terrain, loadModuleGroup(p.string())}); p.remove_filename(); if (!inserted.second) throw std::runtime_error("Tried to load two central module groups with the same terrain"); } for (auto it : options.horizontalBorderModuleGroups) { p /= options.combinerModuleGroup; auto inserted = mHorizotalBorders.insert({it.terrains, loadModuleGroup(p.string())}); p.remove_filename(); if (!inserted.second) throw std::runtime_error("Tried to load two horizontal border module groups with the same terrain pair"); inserted.first->second.setSeeds(mRNG()); } for (auto it : options.verticalBorderModuleGroups) { p /= options.combinerModuleGroup; auto inserted = mVerticalBorders.insert({it.terrains, loadModuleGroup(p.string())}); p.remove_filename(); if (!inserted.second) throw std::runtime_error("Tried to load two vertical border module groups with the same terrain pair"); inserted.first->second.setSeeds(mRNG()); } // TODO: Put a default module group field in options. // Use it for all module groups which aren't individually specified in options. for (const auto& terrain : options.terrains) { mStochasticMasks.insert({terrain.first, module::scaleBias(module::makePlaceholder(), 0.5, 0.5)}); } for (const auto& clique : options.cliques) { // At least n*(n-1)/2 duplicates will be checked in each clique. for (const auto& t1 : clique) for (const auto& t2 : clique) { TerrainIDPair tp{t1, t2}; if (mBordersHorizontal.find(tp) == mBordersHorizontal.end()) mBordersHorizontal.insert({tp, module::makePlaceholder(mRNG())}); if (mBordersVertical.find(tp) == mBordersVertical.end()) mBordersVertical.insert({tp, module::makePlaceholder(mRNG())}); } } } module::ReseedablePtr ModuleManager::getBorderVertical(TerrainID top, TerrainID bottom, bool x_positive) { ReseedablePtr& r = mBordersVertical.at({top, bottom}); return module::selectQuadrant(r, x_positive, true); } module::ReseedablePtr ModuleManager::getBorderHorizontal(TerrainID left, TerrainID right, bool y_positive) { ReseedablePtr& r = mBordersHorizontal.at({left, right}); return module::selectQuadrant(r, true, y_positive); } module::ReseedablePtr& ModuleManager::getStochastic(TerrainID terrain) { ReseedablePtr& r = mStochasticMasks.at(terrain); r->setSeed(mRNG()); return r; } ModuleGroup ModuleManager::loadModuleGroup(std::string filename) { std::ifstream ifs(filename); if (!ifs.good()) { throw std::runtime_error("Could not open options file"); } std::string str{std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()}; EncodedModuleGroup encoded_module_group; try { encoded_module_group = spotify::json::decode<EncodedModuleGroup>(str.c_str()); } catch (const spotify::json::decode_exception& e) { std::cout << "spotify::json::decode_exception encountered at " << e.offset() << ": " << e.what(); throw; } encoded_module_group.decode(); return encoded_module_group.moduleGroup; } } // namespace noise <commit_msg>Load border module groups from correct file<commit_after>#include "ModuleManager.h" #include "module/ReseedableOps.h" #include <random> #include <time.h> #include <algorithm> #include <fstream> #include <iostream> #include <boost/filesystem.hpp> #include "EncodedModuleGroup.h" #include "codecs/EncodedModuleGroupCodec.h" namespace noise { ModuleManager::ModuleManager(const Options & options) : mRNG((unsigned int)time(nullptr)) { boost::filesystem::path p(options.directory); p /= options.combinerModuleGroup; mCombiner = loadModuleGroup(p.string()); p.remove_filename(); for (auto it : options.centralModuleGroups) { p /= it.filename; auto inserted = mCentres.insert({it.terrain, loadModuleGroup(p.string())}); p.remove_filename(); if (!inserted.second) throw std::runtime_error("Tried to load two central module groups with the same terrain"); } for (auto it : options.horizontalBorderModuleGroups) { p /= it.filename; auto inserted = mHorizotalBorders.insert({it.terrains, loadModuleGroup(p.string())}); p.remove_filename(); if (!inserted.second) throw std::runtime_error("Tried to load two horizontal border module groups with the same terrain pair"); inserted.first->second.setSeeds(mRNG()); } for (auto it : options.verticalBorderModuleGroups) { p /= it.filename; auto inserted = mVerticalBorders.insert({it.terrains, loadModuleGroup(p.string())}); p.remove_filename(); if (!inserted.second) throw std::runtime_error("Tried to load two vertical border module groups with the same terrain pair"); inserted.first->second.setSeeds(mRNG()); } // TODO: Put a default module group field in options. // Use it for all module groups which aren't individually specified in options. for (const auto& terrain : options.terrains) { mStochasticMasks.insert({terrain.first, module::scaleBias(module::makePlaceholder(), 0.5, 0.5)}); } for (const auto& clique : options.cliques) { // At least n*(n-1)/2 duplicates will be checked in each clique. for (const auto& t1 : clique) for (const auto& t2 : clique) { TerrainIDPair tp{t1, t2}; if (mBordersHorizontal.find(tp) == mBordersHorizontal.end()) mBordersHorizontal.insert({tp, module::makePlaceholder(mRNG())}); if (mBordersVertical.find(tp) == mBordersVertical.end()) mBordersVertical.insert({tp, module::makePlaceholder(mRNG())}); } } } module::ReseedablePtr ModuleManager::getBorderVertical(TerrainID top, TerrainID bottom, bool x_positive) { ReseedablePtr& r = mBordersVertical.at({top, bottom}); return module::selectQuadrant(r, x_positive, true); } module::ReseedablePtr ModuleManager::getBorderHorizontal(TerrainID left, TerrainID right, bool y_positive) { ReseedablePtr& r = mBordersHorizontal.at({left, right}); return module::selectQuadrant(r, true, y_positive); } module::ReseedablePtr& ModuleManager::getStochastic(TerrainID terrain) { ReseedablePtr& r = mStochasticMasks.at(terrain); r->setSeed(mRNG()); return r; } ModuleGroup ModuleManager::loadModuleGroup(std::string filename) { std::ifstream ifs(filename); if (!ifs.good()) { throw std::runtime_error("Could not open options file"); } std::string str{std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()}; EncodedModuleGroup encoded_module_group; try { encoded_module_group = spotify::json::decode<EncodedModuleGroup>(str.c_str()); } catch (const spotify::json::decode_exception& e) { std::cout << "spotify::json::decode_exception encountered at " << e.offset() << ": " << e.what(); throw; } encoded_module_group.decode(); return encoded_module_group.moduleGroup; } } // namespace noise <|endoftext|>
<commit_before>/* Copyright 2016 Nervana Systems Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <math.h> #include "buffer.hpp" #include "sequential_batch_iterator.hpp" SequentialBatchIterator::SequentialBatchIterator(shared_ptr<BatchLoader> loader, uint block_size) : _loader(loader), _block_size(block_size) { _i = 0; _count = ceil((float)_loader->objectCount() / (float)_block_size); }; void SequentialBatchIterator::read(BufferPair& dest) { _loader->loadBlock(dest, _i, _block_size); _i += 1; if(_i >= _count) { _i = 0; } } void SequentialBatchIterator::reset() { _i = 0; } <commit_msg>standardize batch_iterator pattern some<commit_after>/* Copyright 2016 Nervana Systems Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <math.h> #include "buffer.hpp" #include "sequential_batch_iterator.hpp" SequentialBatchIterator::SequentialBatchIterator(shared_ptr<BatchLoader> loader, uint block_size) : _loader(loader), _block_size(block_size) { _count = ceil((float)_loader->objectCount() / (float)_block_size); reset(); }; void SequentialBatchIterator::read(BufferPair& dest) { _loader->loadBlock(dest, _i, _block_size); ++_i; if(_i != _count) { reset(); } } void SequentialBatchIterator::reset() { _i = 0; } <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2015 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include <sstream> #include <utility> #include <typeinfo> #include <memory> #include <tuple> #include <string> #include <gtest/gtest.h> #include "joynr/JoynrMessage.h" #include "joynr/JoynrMessageFactory.h" #include "joynr/MessagingQos.h" #include "joynr/Request.h" #include "joynr/Reply.h" #include "joynr/exceptions/JoynrException.h" #include "joynr/Logger.h" #include "joynr/types/TestTypes/TEverythingStruct.h" #include "joynr/types/TestTypes/TStruct.h" #include "joynr/types/TestTypes/TEnum.h" #include "joynr/types/TestTypes/TEverythingMap.h" #include "joynr/types/TestTypes/TStringKeyMap.h" #include "joynr/types/TestTypes/TStringToByteBufferMap.h" #include "joynr/tests/test/MethodWithErrorEnumExtendedErrorEnum.h" #include "joynr/types/Localisation/GpsLocation.h" #include "joynr/types/Localisation/Trip.h" #include "joynr/types/Version.h" #include "joynr/system/RoutingTypes/ChannelAddress.h" #include "joynr/types/GlobalDiscoveryEntry.h" #include "joynr/serializer/Serializer.h" template <typename Serializer> class RequestReplySerializerTest : public ::testing::Test { public: RequestReplySerializerTest() : Test(), complexParametersDatatypes({ "joynr.types.TestTypes.TEverythingStruct", "joynr.types.TestTypes.TEverythingExtendedStruct", "joynr.types.TestTypes.TEnum" }), primitiveParametersDatatypes({ "String", "Integer", "SomeOtherType", "Float", "Bool" }), complexParametersValues(), primitiveParametersValues(std::string("Hello World"), 101, 9.99f, true), responseValues(std::string("Hello World"), 101, 9.99f, true, {1,2,3,4}) { } protected: using OutputStream = muesli::StringOStream; using InputStream = muesli::StringIStream; using OutputArchive = typename Serializer::template OutputArchive<OutputStream>; using InputArchive = typename Serializer::template InputArchive<InputStream>; template <typename T> std::string serialize(const T& value) { OutputStream stream; OutputArchive oarchive(stream); oarchive(value); JOYNR_LOG_TRACE(logger, "serialized to " + stream.getString()); return stream.getString(); } template <typename T> void deserialize(std::string str, T& value) { JOYNR_LOG_TRACE(logger, "trying to deserialize from JSON: {}", str); InputStream stream(std::move(str)); InputArchive iarchive(stream); iarchive(value); } // we need to serialize, then deserialize the request/reply to get it in a state to get the data out again template <typename T> T initOutgoingIncoming(const T& outgoingType) { T incomingType; deserialize(serialize(outgoingType), incomingType); return incomingType; } template <typename Tuple, std::size_t... Indices> void setRequestParamsFromTuple(joynr::Request& request, Tuple tuple, std::index_sequence<Indices...>) { request.setParams(std::move(std::get<Indices>(tuple))...); } template <typename Tuple, std::size_t... Indices> void setReplyResponseFromTuple(joynr::Reply& reply, Tuple tuple, std::index_sequence<Indices...>) { reply.setResponse(std::move(std::get<Indices>(tuple))...); } template <typename... Ts> joynr::Request initRequest(std::string methodName, std::string requestReplyId, std::vector<std::string> paramDataTypes, std::tuple<Ts...> paramValues) { joynr::Request outgoingRequest; outgoingRequest.setMethodName(methodName); outgoingRequest.setRequestReplyId(requestReplyId); outgoingRequest.setParamDatatypes(std::move(paramDataTypes)); setRequestParamsFromTuple(outgoingRequest, paramValues, std::index_sequence_for<Ts...>{}); return initOutgoingIncoming(outgoingRequest); } template <typename T> joynr::Reply initReply(std::string requestReplyId, std::shared_ptr<T> error) { joynr::Reply outgoingReply; outgoingReply.setRequestReplyId(requestReplyId); outgoingReply.setError(error); return initOutgoingIncoming(outgoingReply); } template <typename... Ts> joynr::Reply initReply(std::string requestReplyId, std::tuple<Ts...> responseTuple) { joynr::Reply outgoingReply; outgoingReply.setRequestReplyId(requestReplyId); setReplyResponseFromTuple(outgoingReply, responseTuple, std::index_sequence_for<Ts...>{}); return initOutgoingIncoming(outgoingReply); } joynr::Request initializeRequestWithComplexValues() { return initRequest("methodWithComplexParameters", "000-10000-01100", complexParametersDatatypes, complexParametersValues ); } joynr::Request initializeRequestWithPrimitiveValues() { return initRequest("realMethod", "000-10000-01011", primitiveParametersDatatypes, primitiveParametersValues ); } template <typename Tuple, std::size_t... Indices> void compareRequestData(joynr::Request& request, Tuple expectedData, std::index_sequence<Indices...>) { Tuple extractedData; request.getParams(std::get<Indices>(extractedData)...); EXPECT_EQ(expectedData, extractedData); } template <typename Tuple, std::size_t... Indices> void compareReplyData(joynr::Reply& reply, Tuple expectedData) { Tuple extractedData; reply.getResponse(extractedData); EXPECT_EQ(expectedData, extractedData); } template <typename Tuple> using IndicesForTuple = std::make_index_sequence<std::tuple_size<Tuple>::value>; template <typename Tuple> auto getIndicesForTuple(Tuple&) { return IndicesForTuple<Tuple>{}; } void compareRequestWithComplexValues(joynr::Request& request) { EXPECT_EQ(complexParametersDatatypes, request.getParamDatatypes()); compareRequestData(request, complexParametersValues, getIndicesForTuple(complexParametersValues)); } void compareRequestWithPrimitiveValues(joynr::Request& request) { EXPECT_EQ(primitiveParametersDatatypes, request.getParamDatatypes()); compareRequestData(request, primitiveParametersValues, getIndicesForTuple(primitiveParametersValues)); } void compareReplyWithExpectedResponse(joynr::Reply& reply) { ASSERT_TRUE(reply.hasResponse()); compareReplyData(reply, responseValues); } std::vector<std::string> complexParametersDatatypes; std::vector<std::string> primitiveParametersDatatypes; std::tuple<joynr::types::TestTypes::TEverythingStruct, joynr::types::TestTypes::TEverythingExtendedStruct, joynr::types::TestTypes::TEnum::Enum> complexParametersValues; std::tuple<std::string, int, float, bool> primitiveParametersValues; std::tuple<std::string, int, float, bool, std::vector<int32_t>> responseValues; ADD_LOGGER(RequestReplySerializerTest); }; template <typename Serializer> INIT_LOGGER(RequestReplySerializerTest<Serializer>); struct JsonSerializer { template <typename Stream> using OutputArchive = muesli::JsonOutputArchive<Stream>; template <typename Stream> using InputArchive = muesli::JsonInputArchive<Stream>; }; // typelist of serializers which shall be tested in the following tests using Serializers = ::testing::Types<JsonSerializer>; TYPED_TEST_CASE(RequestReplySerializerTest, Serializers); TYPED_TEST(RequestReplySerializerTest, exampleDeserializerJoynrReplyWithProviderRuntimeException) { auto error = std::make_shared<joynr::exceptions::ProviderRuntimeException>("Message of ProviderRuntimeException"); joynr::Reply reply = this->initReply("does-not-matter", error); auto deserializedError = reply.getError(); ASSERT_EQ(typeid(*error), typeid(*deserializedError)); ASSERT_EQ(deserializedError->getMessage(), error->getMessage()); } TYPED_TEST(RequestReplySerializerTest, exampleDeserializerJoynrReplyWithApplicationException) { using namespace joynr::tests; std::string literal = test::MethodWithErrorEnumExtendedErrorEnum::getLiteral( test::MethodWithErrorEnumExtendedErrorEnum::BASE_ERROR_TYPECOLLECTION); // Create a ApplicationException auto error = std::make_shared<joynr::exceptions::ApplicationException>( literal, std::make_shared<test::MethodWithErrorEnumExtendedErrorEnum::ApplicationExceptionErrorImpl>()); joynr::Reply reply = this->initReply("does-not-matter", error); auto deserializedError = reply.getError(); ASSERT_EQ(typeid(*error), typeid(*deserializedError)); auto deserializedApplicationException = std::dynamic_pointer_cast<joynr::exceptions::ApplicationException>(deserializedError); ASSERT_TRUE(deserializedApplicationException != nullptr); ASSERT_EQ(deserializedApplicationException, error); } TYPED_TEST(RequestReplySerializerTest, exampleDeserializerJoynrReply) { joynr::Reply reply = this->initReply("000-10000-01100", this->responseValues); this->compareReplyWithExpectedResponse(reply); } TYPED_TEST(RequestReplySerializerTest, exampleSerializerTestWithJoynrRequestOfPrimitiveParameters) { // Create, initialize & check request with primitive parameters joynr::Request request = this->initializeRequestWithPrimitiveValues(); this->compareRequestWithPrimitiveValues(request); } TYPED_TEST(RequestReplySerializerTest, exampleSerializerTestWithJoynrRequestOfComplexParameters) { // Create, initialize & check request with complex parameters joynr::Request request = this->initializeRequestWithComplexValues(); this->compareRequestWithComplexValues(request); } TYPED_TEST(RequestReplySerializerTest, serializeJoynrMessage) { // Create a Request joynr::Request outgoingRequest = this->initializeRequestWithPrimitiveValues(); joynr::JoynrMessage outgoingMessage = joynr::JoynrMessageFactory().createRequest("sender", "receiver", joynr::MessagingQos(), outgoingRequest); JOYNR_LOG_TRACE(this->logger, "outgoing JoynrMessage payload JSON: {}", outgoingMessage.getPayload()); joynr::JoynrMessage incomingMessage; this->deserialize(this->serialize(outgoingMessage), incomingMessage); joynr::Request incomingRequest; this->deserialize(incomingMessage.getPayload(), incomingRequest); this->compareRequestWithPrimitiveValues(incomingRequest); } TYPED_TEST(RequestReplySerializerTest, serialize_deserialize_RequestWithGpsLocationList) { using joynr::types::Localisation::GpsLocation; using joynr::types::Localisation::GpsFixEnum; using joynr::types::Localisation::Trip; using GpsLocationList = std::vector<GpsLocation>; GpsLocationList locations; locations.emplace_back(1.1, 1.2, 1.3, GpsFixEnum::MODE2D, 1.4, 1.5, 1.6, 1.7, 18, 19, 110); locations.emplace_back(2.1, 2.2, 2.3, GpsFixEnum::MODE2D, 2.4, 2.5, 2.6, 2.7, 28, 29, 210); locations.emplace_back(3.1, 3.2, 3.3, GpsFixEnum::MODE2D, 3.4, 3.5, 3.6, 3.7, 38, 39, 310); Trip trip1(locations, "trip1_name"); std::string stringParam("contentParam1"); int intParam = 2; auto requestParamTuple = std::make_tuple(stringParam, trip1, intParam); joynr::Request request = this->initRequest("", "", {}, requestParamTuple); this->compareRequestData(request, requestParamTuple, this->getIndicesForTuple(requestParamTuple)); } TYPED_TEST(RequestReplySerializerTest, serialize_deserialize_ReplyWithArrayAsResponse) { using joynr::types::GlobalDiscoveryEntry; using joynr::types::ProviderQos; joynr::types::Version providerVersion(47, 11); std::int64_t lastSeenMs = 3; std::int64_t expiryDateMs = 7; std::string publicKeyId("publicKeyId"); joynr::system::RoutingTypes::ChannelAddress channelAddress1("localhost", "channelId1"); std::string serializedAddress1 = joynr::serializer::serializeToJson(channelAddress1); joynr::system::RoutingTypes::ChannelAddress channelAddress2("localhost", "channelId2"); std::string serializedAddress2 = joynr::serializer::serializeToJson(channelAddress2); std::vector<GlobalDiscoveryEntry> globalDiscoveryEntries; globalDiscoveryEntries.emplace_back(providerVersion, "domain1", "interface1", "participant1", ProviderQos(), lastSeenMs, expiryDateMs, publicKeyId, serializedAddress1); globalDiscoveryEntries.emplace_back(providerVersion, "domain2", "interface2", "participant2", ProviderQos(), lastSeenMs, expiryDateMs, publicKeyId, serializedAddress2); const std::string requestReplyId("serialize_deserialize_Reply_with_Array_as_Response"); using ResponseTuple = std::tuple<std::vector<GlobalDiscoveryEntry>>; ResponseTuple responseTuple {globalDiscoveryEntries}; joynr::Reply reply = this->initReply(requestReplyId, responseTuple); this->compareReplyData(reply, responseTuple); } <commit_msg>[C++] fixed RequestReplySerializerTest<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2015 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include <sstream> #include <utility> #include <typeinfo> #include <memory> #include <tuple> #include <string> #include <gtest/gtest.h> #include "joynr/JoynrMessage.h" #include "joynr/JoynrMessageFactory.h" #include "joynr/MessagingQos.h" #include "joynr/Request.h" #include "joynr/Reply.h" #include "joynr/exceptions/JoynrException.h" #include "joynr/Logger.h" #include "joynr/types/TestTypes/TEverythingStruct.h" #include "joynr/types/TestTypes/TStruct.h" #include "joynr/types/TestTypes/TEnum.h" #include "joynr/types/TestTypes/TEverythingMap.h" #include "joynr/types/TestTypes/TStringKeyMap.h" #include "joynr/types/TestTypes/TStringToByteBufferMap.h" #include "joynr/tests/test/MethodWithErrorEnumExtendedErrorEnum.h" #include "joynr/types/Localisation/GpsLocation.h" #include "joynr/types/Localisation/Trip.h" #include "joynr/types/Version.h" #include "joynr/system/RoutingTypes/ChannelAddress.h" #include "joynr/types/GlobalDiscoveryEntry.h" #include "joynr/serializer/Serializer.h" template <typename Serializer> class RequestReplySerializerTest : public ::testing::Test { public: RequestReplySerializerTest() : Test(), complexParametersDatatypes({ "joynr.types.TestTypes.TEverythingStruct", "joynr.types.TestTypes.TEverythingExtendedStruct", "joynr.types.TestTypes.TEnum" }), primitiveParametersDatatypes({ "String", "Integer", "Float", "Bool" }), complexParametersValues(), primitiveParametersValues(std::string("Hello World"), 101, 9.99f, true), responseValues(std::string("Hello World"), 101, 9.99f, true, {1,2,3,4}) { } protected: using OutputStream = muesli::StringOStream; using InputStream = muesli::StringIStream; using OutputArchive = typename Serializer::template OutputArchive<OutputStream>; using InputArchive = typename Serializer::template InputArchive<InputStream>; template <typename T> std::string serialize(const T& value) { OutputStream stream; OutputArchive oarchive(stream); oarchive(value); JOYNR_LOG_TRACE(logger, "serialized to " + stream.getString()); return stream.getString(); } template <typename T> void deserialize(std::string str, T& value) { JOYNR_LOG_TRACE(logger, "trying to deserialize from JSON: {}", str); InputStream stream(std::move(str)); auto iarchive = std::make_shared<InputArchive>(stream); (*iarchive)(value); } // we need to serialize, then deserialize the request/reply to get it in a state to get the data out again template <typename T> T initOutgoingIncoming(const T& outgoingType) { T incomingType; deserialize(serialize(outgoingType), incomingType); return incomingType; } template <typename Tuple, std::size_t... Indices> void setRequestParamsFromTuple(joynr::Request& request, Tuple tuple, std::index_sequence<Indices...>) { request.setParams(std::move(std::get<Indices>(tuple))...); } template <typename Tuple, std::size_t... Indices> void setReplyResponseFromTuple(joynr::Reply& reply, Tuple tuple, std::index_sequence<Indices...>) { reply.setResponse(std::move(std::get<Indices>(tuple))...); } template <typename... Ts> joynr::Request initRequest(std::string methodName, std::string requestReplyId, std::vector<std::string> paramDataTypes, std::tuple<Ts...> paramValues) { joynr::Request outgoingRequest; outgoingRequest.setMethodName(methodName); outgoingRequest.setRequestReplyId(requestReplyId); outgoingRequest.setParamDatatypes(std::move(paramDataTypes)); setRequestParamsFromTuple(outgoingRequest, paramValues, std::index_sequence_for<Ts...>{}); return outgoingRequest; } template <typename T> joynr::Reply initReply(std::string requestReplyId, std::shared_ptr<T> error) { joynr::Reply outgoingReply; outgoingReply.setRequestReplyId(requestReplyId); outgoingReply.setError(error); return initOutgoingIncoming(outgoingReply); } template <typename... Ts> joynr::Reply initReply(std::string requestReplyId, std::tuple<Ts...> responseTuple) { joynr::Reply outgoingReply; outgoingReply.setRequestReplyId(requestReplyId); setReplyResponseFromTuple(outgoingReply, responseTuple, std::index_sequence_for<Ts...>{}); return initOutgoingIncoming(outgoingReply); } joynr::Request initializeRequestWithComplexValues() { return initRequest("methodWithComplexParameters", "000-10000-01100", complexParametersDatatypes, complexParametersValues ); } joynr::Request initializeRequestWithPrimitiveValues() { return initRequest("realMethod", "000-10000-01011", primitiveParametersDatatypes, primitiveParametersValues ); } template <typename Tuple, std::size_t... Indices> void compareRequestData(joynr::Request& request, Tuple expectedData, std::index_sequence<Indices...>) { Tuple extractedData; request.getParams(std::get<Indices>(extractedData)...); EXPECT_EQ(expectedData, extractedData); } template <typename Tuple, std::size_t... Indices> void compareReplyData(joynr::Reply& reply, Tuple expectedData, std::index_sequence<Indices...>) { Tuple extractedData; reply.getResponse(std::get<Indices>(extractedData)...); EXPECT_EQ(expectedData, extractedData); } template <typename Tuple> using IndicesForTuple = std::make_index_sequence<std::tuple_size<Tuple>::value>; template <typename Tuple> auto getIndicesForTuple(Tuple&) { return IndicesForTuple<Tuple>{}; } void compareRequestWithComplexValues(joynr::Request& request) { EXPECT_EQ(complexParametersDatatypes, request.getParamDatatypes()); compareRequestData(request, complexParametersValues, getIndicesForTuple(complexParametersValues)); } void compareRequestWithPrimitiveValues(joynr::Request& request) { EXPECT_EQ(primitiveParametersDatatypes, request.getParamDatatypes()); compareRequestData(request, primitiveParametersValues, getIndicesForTuple(primitiveParametersValues)); } void compareReplyWithExpectedResponse(joynr::Reply& reply) { ASSERT_TRUE(reply.hasResponse()); compareReplyData(reply, responseValues, this->getIndicesForTuple(responseValues)); } std::vector<std::string> complexParametersDatatypes; std::vector<std::string> primitiveParametersDatatypes; std::tuple<joynr::types::TestTypes::TEverythingStruct, joynr::types::TestTypes::TEverythingExtendedStruct, joynr::types::TestTypes::TEnum::Enum> complexParametersValues; std::tuple<std::string, int, float, bool> primitiveParametersValues; std::tuple<std::string, int, float, bool, std::vector<int32_t>> responseValues; ADD_LOGGER(RequestReplySerializerTest); }; template <typename Serializer> INIT_LOGGER(RequestReplySerializerTest<Serializer>); struct JsonSerializer { template <typename Stream> using OutputArchive = muesli::JsonOutputArchive<Stream>; template <typename Stream> using InputArchive = muesli::JsonInputArchive<Stream>; }; // typelist of serializers which shall be tested in the following tests using Serializers = ::testing::Types<JsonSerializer>; TYPED_TEST_CASE(RequestReplySerializerTest, Serializers); TYPED_TEST(RequestReplySerializerTest, exampleDeserializerJoynrReplyWithProviderRuntimeException) { auto error = std::make_shared<joynr::exceptions::ProviderRuntimeException>("Message of ProviderRuntimeException"); joynr::Reply reply = this->initReply("does-not-matter", error); auto deserializedError = reply.getError(); ASSERT_EQ(typeid(*error), typeid(*deserializedError)); ASSERT_EQ(deserializedError->getMessage(), error->getMessage()); } TYPED_TEST(RequestReplySerializerTest, exampleDeserializerJoynrReplyWithApplicationException) { using namespace joynr::tests; std::string literal = test::MethodWithErrorEnumExtendedErrorEnum::getLiteral( test::MethodWithErrorEnumExtendedErrorEnum::BASE_ERROR_TYPECOLLECTION); // Create a ApplicationException auto error = std::make_shared<joynr::exceptions::ApplicationException>( literal, std::make_shared<test::MethodWithErrorEnumExtendedErrorEnum::ApplicationExceptionErrorImpl>()); joynr::Reply reply = this->initReply("does-not-matter", error); auto deserializedError = reply.getError(); ASSERT_EQ(typeid(*error), typeid(*deserializedError)); auto deserializedApplicationException = std::dynamic_pointer_cast<joynr::exceptions::ApplicationException>(deserializedError); ASSERT_TRUE(deserializedApplicationException != nullptr); ASSERT_EQ(*deserializedApplicationException, *error); } TYPED_TEST(RequestReplySerializerTest, exampleDeserializerJoynrReply) { joynr::Reply reply = this->initReply("000-10000-01100", this->responseValues); this->compareReplyWithExpectedResponse(reply); } TYPED_TEST(RequestReplySerializerTest, exampleSerializerTestWithJoynrRequestOfPrimitiveParameters) { // Create, initialize & check request with primitive parameters joynr::Request request = this->initializeRequestWithPrimitiveValues(); this->compareRequestWithPrimitiveValues(request); } TYPED_TEST(RequestReplySerializerTest, exampleSerializerTestWithJoynrRequestOfComplexParameters) { // Create, initialize & check request with complex parameters joynr::Request request = this->initializeRequestWithComplexValues(); this->compareRequestWithComplexValues(request); } TYPED_TEST(RequestReplySerializerTest, serializeJoynrMessage) { // Create a Request joynr::Request outgoingRequest = this->initializeRequestWithPrimitiveValues(); joynr::JoynrMessage outgoingMessage = joynr::JoynrMessageFactory().createRequest("sender", "receiver", joynr::MessagingQos(), outgoingRequest); JOYNR_LOG_TRACE(this->logger, "outgoing JoynrMessage payload JSON: {}", outgoingMessage.getPayload()); joynr::JoynrMessage incomingMessage; this->deserialize(this->serialize(outgoingMessage), incomingMessage); joynr::Request incomingRequest; this->deserialize(incomingMessage.getPayload(), incomingRequest); this->compareRequestWithPrimitiveValues(incomingRequest); } TYPED_TEST(RequestReplySerializerTest, serialize_deserialize_RequestWithGpsLocationList) { using joynr::types::Localisation::GpsLocation; using joynr::types::Localisation::GpsFixEnum; using joynr::types::Localisation::Trip; using GpsLocationList = std::vector<GpsLocation>; GpsLocationList locations; locations.emplace_back(1.1, 1.2, 1.3, GpsFixEnum::MODE2D, 1.4, 1.5, 1.6, 1.7, 18, 19, 110); locations.emplace_back(2.1, 2.2, 2.3, GpsFixEnum::MODE2D, 2.4, 2.5, 2.6, 2.7, 28, 29, 210); locations.emplace_back(3.1, 3.2, 3.3, GpsFixEnum::MODE2D, 3.4, 3.5, 3.6, 3.7, 38, 39, 310); Trip trip1(locations, "trip1_name"); std::string stringParam("contentParam1"); int intParam = 2; auto requestParamTuple = std::make_tuple(stringParam, trip1, intParam); joynr::Request request = this->initRequest("", "", {}, requestParamTuple); this->compareRequestData(request, requestParamTuple, this->getIndicesForTuple(requestParamTuple)); } TYPED_TEST(RequestReplySerializerTest, serialize_deserialize_ReplyWithArrayAsResponse) { using joynr::types::GlobalDiscoveryEntry; using joynr::types::ProviderQos; joynr::types::Version providerVersion(47, 11); std::int64_t lastSeenMs = 3; std::int64_t expiryDateMs = 7; std::string publicKeyId("publicKeyId"); joynr::system::RoutingTypes::ChannelAddress channelAddress1("localhost", "channelId1"); std::string serializedAddress1 = joynr::serializer::serializeToJson(channelAddress1); joynr::system::RoutingTypes::ChannelAddress channelAddress2("localhost", "channelId2"); std::string serializedAddress2 = joynr::serializer::serializeToJson(channelAddress2); std::vector<GlobalDiscoveryEntry> globalDiscoveryEntries; globalDiscoveryEntries.emplace_back(providerVersion, "domain1", "interface1", "participant1", ProviderQos(), lastSeenMs, expiryDateMs, publicKeyId, serializedAddress1); globalDiscoveryEntries.emplace_back(providerVersion, "domain2", "interface2", "participant2", ProviderQos(), lastSeenMs, expiryDateMs, publicKeyId, serializedAddress2); const std::string requestReplyId("serialize_deserialize_Reply_with_Array_as_Response"); using ResponseTuple = std::tuple<std::vector<GlobalDiscoveryEntry>>; ResponseTuple responseTuple {globalDiscoveryEntries}; joynr::Reply reply = this->initReply(requestReplyId, responseTuple); this->compareReplyData(reply, responseTuple, this->getIndicesForTuple(responseTuple)); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: webdavresultset.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 16:17:36 $ * * 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 _WEBDAV_UCP_RESULTSET_HXX #define _WEBDAV_UCP_RESULTSET_HXX #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _UCBHELPER_RESULTSETHELPER_HXX #include <ucbhelper/resultsethelper.hxx> #endif #ifndef _WEBDAV_UCP_CONTENT_HXX #include "webdavcontent.hxx" #endif #ifndef _WEBDAV_UCP_DATASUPPLIER_HXX #include "webdavdatasupplier.hxx" #endif namespace webdav_ucp { class DynamicResultSet : public ::ucb::ResultSetImplHelper { rtl::Reference< Content > m_xContent; com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > m_xEnv; private: virtual void initStatic(); virtual void initDynamic(); public: DynamicResultSet( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, const rtl::Reference< Content >& rxContent, const com::sun::star::ucb::OpenCommandArgument2& rCommand, const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& rxEnv ); }; } #endif <commit_msg>INTEGRATION: CWS bgdlremove (1.4.108); FILE MERGED 2007/05/18 11:37:19 kso 1.4.108.1: #i77419# - cleanup of ucbhelper namespaces.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: webdavresultset.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ihi $ $Date: 2007-06-05 18:22:42 $ * * 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 _WEBDAV_UCP_RESULTSET_HXX #define _WEBDAV_UCP_RESULTSET_HXX #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _UCBHELPER_RESULTSETHELPER_HXX #include <ucbhelper/resultsethelper.hxx> #endif #ifndef _WEBDAV_UCP_CONTENT_HXX #include "webdavcontent.hxx" #endif #ifndef _WEBDAV_UCP_DATASUPPLIER_HXX #include "webdavdatasupplier.hxx" #endif namespace webdav_ucp { class DynamicResultSet : public ::ucbhelper::ResultSetImplHelper { rtl::Reference< Content > m_xContent; com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > m_xEnv; private: virtual void initStatic(); virtual void initDynamic(); public: DynamicResultSet( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, const rtl::Reference< Content >& rxContent, const com::sun::star::ucb::OpenCommandArgument2& rCommand, const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& rxEnv ); }; } #endif <|endoftext|>
<commit_before>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file SiconosShape.hpp \brief Definition of an abstract rigid shape */ #ifndef SiconosShape_h #define SiconosShape_h #include "MechanicsFwd.hpp" #include <SiconosVisitor.hpp> #include <SiconosSerialization.hpp> #include <SiconosVector.hpp> #include <SiconosMatrix.hpp> class SiconosShape { protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosShape); double _inside_margin; double _outside_margin; unsigned int _version; // version number tracks changes to shape properties SiconosShape() : _inside_margin(0.1) , _outside_margin(0.1) , _version(0) {} public: virtual ~SiconosShape() {} void setInsideMargin (double margin) { _inside_margin = margin; _version ++; } void setOutsideMargin(double margin) { _outside_margin = margin; _version ++; } double insideMargin() { return _inside_margin; } double outsideMargin() { return _outside_margin; } unsigned int version() const { return _version; } /** visitors hook */ VIRTUAL_ACCEPT_VISITORS(); }; class SiconosPlane : public SiconosShape, public std11::enable_shared_from_this<SiconosPlane> { protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosPlane); public: SiconosPlane() : SiconosShape() {} virtual ~SiconosPlane() {} /** visitors hook */ ACCEPT_VISITORS(); }; class SiconosSphere : public SiconosShape, public std11::enable_shared_from_this<SiconosSphere> { private: SiconosSphere() : SiconosShape() {}; protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosSphere); float _radius; public: SiconosSphere(float radius) : SiconosShape(), _radius(radius) {} virtual ~SiconosSphere() {} float radius() const { return _radius; } void setRadius(float r) { _radius = r; _version ++; } /** visitors hook */ ACCEPT_VISITORS(); }; class SiconosBox : public SiconosShape, public std11::enable_shared_from_this<SiconosBox> { private: SiconosBox() : SiconosShape() {}; protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosBox); SP::SiconosVector _dimensions; public: SiconosBox(double width, double height, double depth) : SiconosShape(), _dimensions(new SiconosVector(3)) { (*_dimensions)(0) = width; (*_dimensions)(1) = height; (*_dimensions)(2) = depth; } SiconosBox(SP::SiconosVector dimensions) : SiconosShape(), _dimensions(dimensions) {} virtual ~SiconosBox() {} SP::SiconosVector dimensions() const { return _dimensions; } void setDimensions(double width, double height, double depth) { (*_dimensions)(0) = width; (*_dimensions)(1) = height; (*_dimensions)(2) = depth; _version ++; } void setDimensions(SP::SiconosVector dim) { _dimensions = dim; _version ++; } void setDimensions(const SiconosVector& dim) { (*_dimensions)(0) = dim(0); (*_dimensions)(1) = dim(1); (*_dimensions)(2) = dim(2); _version ++; } /** visitors hook */ ACCEPT_VISITORS(); }; class SiconosCylinder : public SiconosShape, public std11::enable_shared_from_this<SiconosCylinder> { private: SiconosCylinder() : SiconosShape() {}; protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosCylinder); double _radius; double _length; public: SiconosCylinder(float radius, float length) : SiconosShape(), _radius(radius), _length(length) { } virtual ~SiconosCylinder() {} void setRadius(double radius) { _radius = radius; _version ++; } double radius() { return _radius; } void setLength(double length) { _length = length; _version ++; } double length() { return _length; } /** visitors hook */ ACCEPT_VISITORS(); }; class SiconosConvexHull : public SiconosShape, public std11::enable_shared_from_this<SiconosConvexHull> { private: SiconosConvexHull() : SiconosShape() {}; protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosConvexHull); SP::SiconosMatrix _vertices; public: SiconosConvexHull(SP::SiconosMatrix vertices) : SiconosShape(), _vertices(vertices) { if (_vertices && _vertices->size(1) != 3) throw SiconosException("Convex hull vertices matrix must have 3 columns."); } virtual ~SiconosConvexHull() {} SP::SiconosMatrix vertices() const { return _vertices; } void setVertices(SP::SiconosMatrix vertices) { _vertices = vertices; _version ++; } /** visitors hook */ ACCEPT_VISITORS(); }; typedef std::vector<unsigned int> VUInt; TYPEDEF_SPTR(VUInt) class SiconosMesh : public SiconosShape, public std11::enable_shared_from_this<SiconosMesh> { private: SiconosMesh() : SiconosShape() {}; protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosMesh); SP::VUInt _indexes; SP::SiconosMatrix _vertices; public: SiconosMesh(SP::VUInt indexes, SP::SiconosMatrix vertices) : SiconosShape(), _indexes(indexes), _vertices(vertices) { if (!_indexes || (_indexes->size() % 3) != 0) throw SiconosException("Mesh indexes size must be divisible by 3."); if (!_vertices || _vertices->size(1) != 3) throw SiconosException("Mesh vertices matrix must have 3 columns."); } SP::VUInt indexes() { return _indexes; } SP::SiconosMatrix vertices() { return _vertices; } virtual ~SiconosMesh() {} /** visitors hook */ ACCEPT_VISITORS(); }; class SiconosHeightMap : public SiconosShape, public std11::enable_shared_from_this<SiconosHeightMap> { private: SiconosHeightMap() : SiconosShape() {}; protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosHeightMap); SP::SiconosMatrix _height_data; double _length_x; double _length_y; public: SiconosHeightMap(SP::SiconosMatrix height_data, double length_x, double length_y) : SiconosShape(), _height_data(height_data), _length_x(length_x), _length_y(length_y) { } SP::SiconosMatrix height_data() { return _height_data; } double length_x() { return _length_x; } double length_y() { return _length_y; } virtual ~SiconosHeightMap() {} /** visitors hook */ ACCEPT_VISITORS(); }; #endif /* SiconosShape_h */ <commit_msg>[mechanics] suppress a default outsideMargin<commit_after>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file SiconosShape.hpp \brief Definition of an abstract rigid shape */ #ifndef SiconosShape_h #define SiconosShape_h #include "MechanicsFwd.hpp" #include <SiconosVisitor.hpp> #include <SiconosSerialization.hpp> #include <SiconosVector.hpp> #include <SiconosMatrix.hpp> class SiconosShape { protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosShape); double _inside_margin; double _outside_margin; unsigned int _version; // version number tracks changes to shape properties SiconosShape() : _inside_margin(0.1) , _outside_margin(0.0) , _version(0) {} public: virtual ~SiconosShape() {} void setInsideMargin (double margin) { _inside_margin = margin; _version ++; } void setOutsideMargin(double margin) { _outside_margin = margin; _version ++; } double insideMargin() { return _inside_margin; } double outsideMargin() { return _outside_margin; } unsigned int version() const { return _version; } /** visitors hook */ VIRTUAL_ACCEPT_VISITORS(); }; class SiconosPlane : public SiconosShape, public std11::enable_shared_from_this<SiconosPlane> { protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosPlane); public: SiconosPlane() : SiconosShape() {} virtual ~SiconosPlane() {} /** visitors hook */ ACCEPT_VISITORS(); }; class SiconosSphere : public SiconosShape, public std11::enable_shared_from_this<SiconosSphere> { private: SiconosSphere() : SiconosShape() {}; protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosSphere); float _radius; public: SiconosSphere(float radius) : SiconosShape(), _radius(radius) {} virtual ~SiconosSphere() {} float radius() const { return _radius; } void setRadius(float r) { _radius = r; _version ++; } /** visitors hook */ ACCEPT_VISITORS(); }; class SiconosBox : public SiconosShape, public std11::enable_shared_from_this<SiconosBox> { private: SiconosBox() : SiconosShape() {}; protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosBox); SP::SiconosVector _dimensions; public: SiconosBox(double width, double height, double depth) : SiconosShape(), _dimensions(new SiconosVector(3)) { (*_dimensions)(0) = width; (*_dimensions)(1) = height; (*_dimensions)(2) = depth; } SiconosBox(SP::SiconosVector dimensions) : SiconosShape(), _dimensions(dimensions) {} virtual ~SiconosBox() {} SP::SiconosVector dimensions() const { return _dimensions; } void setDimensions(double width, double height, double depth) { (*_dimensions)(0) = width; (*_dimensions)(1) = height; (*_dimensions)(2) = depth; _version ++; } void setDimensions(SP::SiconosVector dim) { _dimensions = dim; _version ++; } void setDimensions(const SiconosVector& dim) { (*_dimensions)(0) = dim(0); (*_dimensions)(1) = dim(1); (*_dimensions)(2) = dim(2); _version ++; } /** visitors hook */ ACCEPT_VISITORS(); }; class SiconosCylinder : public SiconosShape, public std11::enable_shared_from_this<SiconosCylinder> { private: SiconosCylinder() : SiconosShape() {}; protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosCylinder); double _radius; double _length; public: SiconosCylinder(float radius, float length) : SiconosShape(), _radius(radius), _length(length) { } virtual ~SiconosCylinder() {} void setRadius(double radius) { _radius = radius; _version ++; } double radius() { return _radius; } void setLength(double length) { _length = length; _version ++; } double length() { return _length; } /** visitors hook */ ACCEPT_VISITORS(); }; class SiconosConvexHull : public SiconosShape, public std11::enable_shared_from_this<SiconosConvexHull> { private: SiconosConvexHull() : SiconosShape() {}; protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosConvexHull); SP::SiconosMatrix _vertices; public: SiconosConvexHull(SP::SiconosMatrix vertices) : SiconosShape(), _vertices(vertices) { if (_vertices && _vertices->size(1) != 3) throw SiconosException("Convex hull vertices matrix must have 3 columns."); } virtual ~SiconosConvexHull() {} SP::SiconosMatrix vertices() const { return _vertices; } void setVertices(SP::SiconosMatrix vertices) { _vertices = vertices; _version ++; } /** visitors hook */ ACCEPT_VISITORS(); }; typedef std::vector<unsigned int> VUInt; TYPEDEF_SPTR(VUInt) class SiconosMesh : public SiconosShape, public std11::enable_shared_from_this<SiconosMesh> { private: SiconosMesh() : SiconosShape() {}; protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosMesh); SP::VUInt _indexes; SP::SiconosMatrix _vertices; public: SiconosMesh(SP::VUInt indexes, SP::SiconosMatrix vertices) : SiconosShape(), _indexes(indexes), _vertices(vertices) { if (!_indexes || (_indexes->size() % 3) != 0) throw SiconosException("Mesh indexes size must be divisible by 3."); if (!_vertices || _vertices->size(1) != 3) throw SiconosException("Mesh vertices matrix must have 3 columns."); } SP::VUInt indexes() { return _indexes; } SP::SiconosMatrix vertices() { return _vertices; } virtual ~SiconosMesh() {} /** visitors hook */ ACCEPT_VISITORS(); }; class SiconosHeightMap : public SiconosShape, public std11::enable_shared_from_this<SiconosHeightMap> { private: SiconosHeightMap() : SiconosShape() {}; protected: /** serialization hooks */ ACCEPT_SERIALIZATION(SiconosHeightMap); SP::SiconosMatrix _height_data; double _length_x; double _length_y; public: SiconosHeightMap(SP::SiconosMatrix height_data, double length_x, double length_y) : SiconosShape(), _height_data(height_data), _length_x(length_x), _length_y(length_y) { } SP::SiconosMatrix height_data() { return _height_data; } double length_x() { return _length_x; } double length_y() { return _length_y; } virtual ~SiconosHeightMap() {} /** visitors hook */ ACCEPT_VISITORS(); }; #endif /* SiconosShape_h */ <|endoftext|>