source: src/Actions/ActionQueue.cpp@ 5061d9

Candidate_v1.7.0 stable
Last change on this file since 5061d9 was 559293, checked in by Frederik Heber <frederik.heber@…>, 7 years ago

ActionQueue has predicates to check if current Action is Process or MakroAction.

  • Property mode set to 100644
File size: 11.9 KB
RevLine 
[628577]1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 Frederik Heber. All rights reserved.
5 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * ActionQueue.cpp
25 *
26 * Created on: Aug 16, 2013
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
[9eb71b3]35//#include "CodePatterns/MemDebug.hpp"
[628577]36
[1d3563]37#include "Actions/ActionQueue.hpp"
[628577]38
[690741]39#include "CodePatterns/Assert.hpp"
40#include "CodePatterns/IteratorAdaptors.hpp"
[46b181]41#include "CodePatterns/Log.hpp"
[628577]42#include "CodePatterns/Singleton_impl.hpp"
43
[415ddd]44#include <boost/date_time/posix_time/posix_time.hpp>
45#include <boost/version.hpp>
[601ef8]46#include <iterator>
[46b181]47#include <string>
48#include <sstream>
[690741]49#include <vector>
50
[0d4168]51#include "Actions/ActionExceptions.hpp"
[6367dd]52#include "Actions/ActionHistory.hpp"
[ed3944]53#include "Actions/ActionRegistry.hpp"
[559293]54#include "Actions/MakroAction.hpp"
55#include "Actions/Process.hpp"
[0d4168]56#include "World.hpp"
[ed3944]57
[628577]58using namespace MoleCuilder;
59
[29b52b]60const Action* ActionQueue::_lastchangedaction = NULL;
61
[ed3944]62ActionQueue::ActionQueue() :
[29b52b]63 Observable("ActionQueue"),
[6367dd]64 AR(new ActionRegistry()),
[af5384]65 history(new ActionHistory),
[f3db60]66 lastActionOk(true),
[601ef8]67 CurrentAction(0),
[a87d1e2]68#ifdef HAVE_ACTION_THREAD
[415ddd]69 run_thread(boost::bind(&ActionQueue::run, this)),
[f3db60]70 run_thread_isIdle(true),
[74459a]71#endif
[f3db60]72 dryrun_flag(false)
[29b52b]73{
74 // channels of observable
75 Channels *OurChannel = new Channels;
[574d377]76 Observable::insertNotificationChannel( std::make_pair(static_cast<Observable *>(this), OurChannel) );
[29b52b]77 // add instance for each notification type
78 for (size_t type = 0; type < NotificationType_MAX; ++type)
79 OurChannel->addChannel(type);
80}
[628577]81
82ActionQueue::~ActionQueue()
[ed3944]83{
[74459a]84#ifdef HAVE_ACTION_THREAD
[415ddd]85 stop();
[601ef8]86
87 clearTempQueue();
[74459a]88#endif
[415ddd]89
[7f1a1a]90 clearQueue();
[af5384]91
[6367dd]92 delete history;
[ed3944]93 delete AR;
94}
[628577]95
[f54cda]96void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
[05c989]97{
[10aee4]98 const Action & registryaction = AR->getActionByName(name);
99 queueAction(&registryaction, state);
[f54cda]100}
101
[7f1a1a]102void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
[f54cda]103{
[af5384]104 Action *newaction = _action->clone(state);
105 newaction->prepare(state);
[74459a]106#ifdef HAVE_ACTION_THREAD
[415ddd]107 mtx_queue.lock();
[74459a]108#endif
[7fc447]109 actionqueue.push_back( newaction );
[74459a]110#ifndef HAVE_ACTION_THREAD
111 try {
[a87d1e2]112 if (!isDryRun(newaction)) {
113 CurrentAction = actionqueue.size()-1;
[f3db60]114 newaction->call();
[a87d1e2]115 CurrentAction = actionqueue.size();
116 }
[a61dbb]117 lastActionOk = true;
[74459a]118 } catch(ActionFailureException &e) {
119 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
120 World::getInstance().setExitFlag(5);
[601ef8]121 clearQueue(actionqueue.size()-1);
[a61dbb]122 lastActionOk = false;
[601ef8]123 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[11d433]124 } catch (std::exception &e) {
125 pushStatus("FAIL: General exception caught, aborting.");
126 World::getInstance().setExitFlag(134);
[601ef8]127 clearQueue(actionqueue.size()-1);
[11d433]128 lastActionOk = false;
[601ef8]129 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[74459a]130 }
[cfb9c5]131 if (lastActionOk) {
132 OBSERVE;
133 NOTIFY(ActionQueued);
134 _lastchangedaction = newaction;
135 }
[74459a]136#else
[415ddd]137 mtx_queue.unlock();
[a87d1e2]138 setRunThreadIdle(isIdle());
[74459a]139#endif
[05c989]140}
141
[975b83]142void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
143{
[74459a]144#ifndef HAVE_ACTION_THREAD
145 queueAction(_action, state);
146#else
[415ddd]147 Action *newaction = _action->clone(state);
148 newaction->prepare(state);
149 mtx_queue.lock();
150 tempqueue.push_back( newaction );
[a87d1e2]151 const bool tempqueue_notempty = !tempqueue.empty();
[415ddd]152 mtx_queue.unlock();
[a87d1e2]153 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
154#endif
155}
156
157bool ActionQueue::isIdle() const
158{
159#ifdef HAVE_ACTION_THREAD
160 boost::unique_lock<boost::mutex> lock(mtx_queue);
[74459a]161#endif
[a87d1e2]162 bool status = (CurrentAction == actionqueue.size());
163 return status;
[415ddd]164}
165
[559293]166bool ActionQueue::isProcess() const
167{
168 if (isIdle())
169 return false;
170 const Process *possibleprocess = dynamic_cast<const Process *>(&getCurrentAction());
171 if (possibleprocess == NULL)
172 return false;
173 else
174 return true;
175}
176
177bool ActionQueue::isMakroAction() const
178{
179 if (isIdle())
180 return false;
181 const MakroAction *possiblemakroaction = dynamic_cast<const MakroAction *>(&getCurrentAction());
182 if (possiblemakroaction == NULL)
183 return false;
184 else
185 return true;
186}
187
188const Action& ActionQueue::getCurrentAction() const
189{
190 return *const_cast<const Action *>(actionqueue[CurrentAction]);
191}
192
[74459a]193#ifdef HAVE_ACTION_THREAD
[415ddd]194void ActionQueue::run()
195{
196 bool Interrupted = false;
197 do {
198 // sleep for some time and wait for queue to fill up again
199 try {
200#if BOOST_VERSION < 105000
201 run_thread.sleep(boost::get_system_time() + boost::posix_time::milliseconds(100));
202#else
[d93b4b3]203 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
[415ddd]204#endif
205 } catch(boost::thread_interrupted &e) {
206 LOG(2, "INFO: ActionQueue has received stop signal.");
207 Interrupted = true;
208 }
209// LOG(1, "DEBUG: Start of ActionQueue's run() loop.");
210 // call all currently present Actions
211 mtx_queue.lock();
212 insertTempQueue();
213 mtx_queue.unlock();
[a87d1e2]214 bool status = !isIdle();
[415ddd]215 while (status) {
216 // boost::this_thread::disable_interruption di;
217 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
218 try {
[f3db60]219 if (!isDryRun(actionqueue[CurrentAction]))
220 actionqueue[CurrentAction]->call();
[0b6b77]221 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
[a61dbb]222 lastActionOk = true;
[415ddd]223 } catch(ActionFailureException &e) {
[0b6b77]224 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
[415ddd]225 World::getInstance().setExitFlag(5);
[601ef8]226 clearQueue(CurrentAction);
227 clearTempQueue();
[a61dbb]228 lastActionOk = false;
[601ef8]229 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[11d433]230 } catch (std::exception &e) {
231 pushStatus("FAIL: General exception caught, aborting.");
232 World::getInstance().setExitFlag(134);
[601ef8]233 clearQueue(CurrentAction);
234 clearTempQueue();
[d8255b]235 lastActionOk = false;
[601ef8]236 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[415ddd]237 }
[cfb9c5]238 if (lastActionOk) {
239 OBSERVE;
240 NOTIFY(ActionQueued);
241 _lastchangedaction = actionqueue[CurrentAction];
[601ef8]242 mtx_queue.lock();
243 CurrentAction++;
244 mtx_queue.unlock();
[cfb9c5]245 }
[415ddd]246 // access actionqueue, hence using mutex
247 mtx_queue.lock();
248 // insert new actions (before [CurrentAction]) if they have been spawned
249 // we must have an extra vector for this, as we cannot change actionqueue
250 // while an action instance is "in-use"
251 insertTempQueue();
252 mtx_queue.unlock();
[a87d1e2]253 status = !isIdle();
[415ddd]254 }
[a87d1e2]255 mtx_queue.lock();
256 const bool tempqueue_notempty = !tempqueue.empty();
257 mtx_queue.unlock();
258 setRunThreadIdle( !((!isIdle()) || tempqueue_notempty) );
[415ddd]259 cond_idle.notify_one();
260// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
261 } while (!Interrupted);
262}
263
264void ActionQueue::insertTempQueue()
265{
266 if (!tempqueue.empty()) {
267 ActionQueue_t::iterator InsertionIter = actionqueue.begin();
268 std::advance(InsertionIter, CurrentAction);
269 actionqueue.insert( InsertionIter, tempqueue.begin(), tempqueue.end() );
270 tempqueue.clear();
271 }
272}
273
274void ActionQueue::wait()
275{
276 boost::unique_lock<boost::mutex> lock(mtx_idle);
277 while(!run_thread_isIdle)
278 {
279 cond_idle.wait(lock);
280 }
281}
[74459a]282#endif
[415ddd]283
[74459a]284#ifdef HAVE_ACTION_THREAD
[415ddd]285void ActionQueue::stop()
286{
287 // notify actionqueue thread that we wish to terminate
288 run_thread.interrupt();
289 // wait till it ends
290 run_thread.join();
[975b83]291}
[74459a]292#endif
[975b83]293
[10aee4]294const Action& ActionQueue::getActionByName(const std::string &name)
[1d3563]295{
[ed3944]296 return AR->getActionByName(name);
[1d3563]297}
298
[a6ceab]299bool ActionQueue::isActionKnownByName(const std::string &name) const
[1d3563]300{
[ed3944]301 return AR->isActionPresentByName(name);
[1d3563]302}
303
[126867]304void ActionQueue::registerAction(Action *_action)
305{
306 AR->registerInstance(_action);
307}
308
[46b181]309void ActionQueue::outputAsCLI(std::ostream &output) const
310{
[7fc447]311 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
312 iter != actionqueue.end();
[46b181]313 ++iter) {
[bad589]314 // skip store-session in printed list
[12d946]315 if ( ((*iter)->getName() != std::string("store-session"))
316 && ((*iter)->getName() != std::string("load-session"))) {
[7fc447]317 if (iter != actionqueue.begin())
[bad589]318 output << " ";
319 (*iter)->outputAsCLI(output);
320 }
[46b181]321 }
322 output << std::endl;
323}
324
[477012]325void ActionQueue::outputAsPython(std::ostream &output) const
326{
327 const std::string prefix("pyMoleCuilder");
328 output << "import " << prefix << std::endl;
[9e4655]329 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
[7fc447]330 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
331 iter != actionqueue.end();
[477012]332 ++iter) {
333 // skip store-session in printed list
[12d946]334 if ( ((*iter)->getName() != std::string("store-session"))
335 && ((*iter)->getName() != std::string("load-session")))
[477012]336 (*iter)->outputAsPython(output, prefix);
337 }
[9e4655]338 output << "# =========================== Stored Session END ===========================" << std::endl;
[477012]339}
340
[a6ceab]341const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
[690741]342{
343 // this const_cast is just required as long as we have a non-const getActionByName
[10aee4]344 const Action & action = const_cast<ActionQueue *>(this)->getActionByName(name);
345 return action.Traits;
[690741]346}
347
[6367dd]348void ActionQueue::addElement(Action* _Action,ActionState::ptr _state)
349{
350 history->addElement(_Action, _state);
351}
352
353void ActionQueue::clear()
354{
355 history->clear();
356}
357
[601ef8]358void ActionQueue::clearQueue(const size_t _fromAction)
[7f1a1a]359{
[601ef8]360#ifdef HAVE_ACTION_THREAD
361 mtx_queue.lock();
362#endif
363 LOG(1, "Removing all Actions from position " << _fromAction << " onward.");
364 // free all actions still to be called contained in actionqueue
365 ActionQueue_t::iterator inititer = actionqueue.begin();
366 std::advance(inititer, _fromAction);
367 for (ActionQueue_t::iterator iter = inititer; iter != actionqueue.end(); ++iter)
[7f1a1a]368 delete *iter;
[601ef8]369 actionqueue.erase(inititer, actionqueue.end());
370 LOG(1, "There are " << actionqueue.size() << " remaining Actions.");
371#ifdef HAVE_ACTION_THREAD
372 CurrentAction = actionqueue.size();
373 mtx_queue.unlock();
374#endif
375}
376
377#ifdef HAVE_ACTION_THREAD
378void ActionQueue::clearTempQueue()
379{
[7f1a1a]380 // free all actions contained in tempqueue
381 for (ActionQueue_t::iterator iter = tempqueue.begin();
382 !tempqueue.empty(); iter = tempqueue.begin()) {
383 delete *iter;
384 tempqueue.erase(iter);
385 }
[601ef8]386}
387
388void ActionQueue::setRunThreadIdle(const bool _flag)
389{
[06b5df]390 {
391 boost::unique_lock<boost::mutex> lock(mtx_idle);
[601ef8]392 run_thread_isIdle = _flag;
[06b5df]393 }
[7f1a1a]394}
[601ef8]395#endif
[6367dd]396
[690741]397const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
398{
399 ActionTokens_t returnlist;
400
401 returnlist.insert(
402 returnlist.end(),
[ed3944]403 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
404 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
[690741]405
406 return returnlist;
407}
408
[6367dd]409void ActionQueue::undoLast()
410{
411 history->undoLast();
412}
413
[c01fec]414bool ActionQueue::canUndo() const
415{
416 return history->hasUndo();
417}
418
[6367dd]419void ActionQueue::redoLast()
420{
421 history->redoLast();
422}
423
[c01fec]424bool ActionQueue::canRedo() const
425{
426 return history->hasRedo();
427}
428
[f3db60]429bool ActionQueue::isDryRun(const Action *_nextaction) const
430{
431 bool status = dryrun_flag;
432 status &= (_nextaction->getName() != "no-dry-run");
433 return status;
434}
[6367dd]435
[628577]436CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.