source: src/Actions/ActionQueue.cpp@ 6bbdfb

Last change on this file since 6bbdfb was 6bbdfb, checked in by Frederik Heber <heber@…>, 11 years ago

tempcommit: Trying to make run_thread relaunchable whenever new Action is queued and not running.

  • Property mode set to 100644
File size: 12.3 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
35#include "CodePatterns/MemDebug.hpp"
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"
[0d4168]54#include "World.hpp"
[ed3944]55
[628577]56using namespace MoleCuilder;
57
[29b52b]58const Action* ActionQueue::_lastchangedaction = NULL;
59
[ed3944]60ActionQueue::ActionQueue() :
[29b52b]61 Observable("ActionQueue"),
[6367dd]62 AR(new ActionRegistry()),
[af5384]63 history(new ActionHistory),
[74459a]64#ifndef HAVE_ACTION_THREAD
[a61dbb]65 lastActionOk(true)
[74459a]66#else
[a61dbb]67 lastActionOk(true),
[7e6c0d]68 CurrentAction(0),
[6bbdfb]69 run_thread_isIdle(true)
[74459a]70#endif
[29b52b]71{
72 // channels of observable
73 Channels *OurChannel = new Channels;
74 NotificationChannels.insert( std::make_pair(static_cast<Observable *>(this), OurChannel) );
75 // add instance for each notification type
76 for (size_t type = 0; type < NotificationType_MAX; ++type)
77 OurChannel->addChannel(type);
78}
[628577]79
80ActionQueue::~ActionQueue()
[ed3944]81{
[74459a]82#ifdef HAVE_ACTION_THREAD
[415ddd]83 stop();
[601ef8]84
85 clearTempQueue();
[74459a]86#endif
[415ddd]87
[7f1a1a]88 clearQueue();
[af5384]89
[6367dd]90 delete history;
[ed3944]91 delete AR;
92}
[628577]93
[f54cda]94void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
[05c989]95{
[7f1a1a]96 const Action * const registryaction = AR->getActionByName(name);
97 queueAction(registryaction, state);
[f54cda]98}
99
[7f1a1a]100void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
[f54cda]101{
[af5384]102 Action *newaction = _action->clone(state);
103 newaction->prepare(state);
[74459a]104#ifdef HAVE_ACTION_THREAD
[6bbdfb]105 {
106 boost::mutex::scoped_lock trylock(mtx_run_thread_running, boost::try_to_lock);
107 if (trylock) {
108 trylock.unlock();
109 run_thread = boost::thread(&ActionQueue::run, this);
110 }
111 }
112
[fff8fc]113 mtx_actionqueue.lock();
[74459a]114#endif
[7fc447]115 actionqueue.push_back( newaction );
[74459a]116#ifndef HAVE_ACTION_THREAD
117 try {
118 newaction->call();
[a61dbb]119 lastActionOk = true;
[74459a]120 } catch(ActionFailureException &e) {
121 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
122 World::getInstance().setExitFlag(5);
[7e6c0d]123// clearQueue(actionqueue.size()-1);
[a61dbb]124 lastActionOk = false;
[7e6c0d]125// std::cerr << "Remaining Actions cleared from queue." << std::endl;
[11d433]126 } catch (std::exception &e) {
127 pushStatus("FAIL: General exception caught, aborting.");
128 World::getInstance().setExitFlag(134);
[7e6c0d]129// clearQueue(actionqueue.size()-1);
[11d433]130 lastActionOk = false;
[7e6c0d]131// std::cerr << "Remaining Actions cleared from queue." << std::endl;
[74459a]132 }
[cfb9c5]133 if (lastActionOk) {
134 OBSERVE;
135 NOTIFY(ActionQueued);
136 _lastchangedaction = newaction;
137 }
[74459a]138#else
[fff8fc]139 mtx_actionqueue.unlock();
[7e6c0d]140 const bool new_run_thread_isIdle = isActionQueueDone();
141 setrun_thread_isIdle(new_run_thread_isIdle);
[74459a]142#endif
[05c989]143}
144
[7e6c0d]145#ifdef HAVE_ACTION_THREAD
[fff8fc]146bool ActionQueue::isActionQueueDone() const
147{
148 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
149 return (CurrentAction == actionqueue.size());
150}
151
[6bbdfb]152void ActionQueue::setActionQueueDone()
153{
154 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
155 CurrentAction = actionqueue.size();
156}
157
[fff8fc]158bool ActionQueue::isTempQueueDone() const
159{
160 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
161 return tempqueue.empty();
162}
[7e6c0d]163#endif
[fff8fc]164
[975b83]165void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
166{
[74459a]167#ifndef HAVE_ACTION_THREAD
168 queueAction(_action, state);
169#else
[415ddd]170 Action *newaction = _action->clone(state);
171 newaction->prepare(state);
172 {
[fff8fc]173 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
174 tempqueue.push_back( newaction );
175 }
176 {
177 bool new_run_thread_isIdle = getrun_thread_isIdle();
178 new_run_thread_isIdle &= isTempQueueDone();
179 setrun_thread_isIdle(new_run_thread_isIdle);
[415ddd]180 }
[74459a]181#endif
[415ddd]182}
183
[74459a]184#ifdef HAVE_ACTION_THREAD
[415ddd]185void ActionQueue::run()
186{
[6bbdfb]187 // only a single thread may run this
188 boost::mutex::scoped_lock trylock(mtx_run_thread_running, boost::try_to_lock);
189 if (trylock) {
[415ddd]190 bool Interrupted = false;
191 do {
192 // sleep for some time and wait for queue to fill up again
193 try {
194#if BOOST_VERSION < 105000
[23b6cf]195 boost::this_thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(100));
[415ddd]196#else
[d93b4b3]197 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
[415ddd]198#endif
199 } catch(boost::thread_interrupted &e) {
200 LOG(2, "INFO: ActionQueue has received stop signal.");
201 Interrupted = true;
202 }
203// LOG(1, "DEBUG: Start of ActionQueue's run() loop.");
204 // call all currently present Actions
205 insertTempQueue();
[fff8fc]206 while ((!Interrupted) && (!isActionQueueDone())) {
[415ddd]207 // boost::this_thread::disable_interruption di;
[23b6cf]208 // access actionqueue, hence using mutex
[fff8fc]209 mtx_actionqueue.lock();
[415ddd]210 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
211 try {
212 actionqueue[CurrentAction]->call();
[0b6b77]213 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
[a61dbb]214 lastActionOk = true;
[415ddd]215 } catch(ActionFailureException &e) {
[0b6b77]216 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
[415ddd]217 World::getInstance().setExitFlag(5);
[a61dbb]218 lastActionOk = false;
[601ef8]219 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[6bbdfb]220 } /* catch (std::exception &e) {
[11d433]221 pushStatus("FAIL: General exception caught, aborting.");
222 World::getInstance().setExitFlag(134);
[6bbdfb]223 lastActionOk = false;
[601ef8]224 std::cerr << "Remaining Actions cleared from queue." << std::endl;
[6bbdfb]225 }*/
226 // remember action we just executed
[23b6cf]227 const Action *lastaction = actionqueue[CurrentAction];
[6bbdfb]228 // step on to next action if last ok
[419fa2]229 if (lastActionOk)
230 CurrentAction++;
[6bbdfb]231
[fff8fc]232 mtx_actionqueue.unlock();
233
[6bbdfb]234 // remove following Actions outside mutex if current failed
[419fa2]235 if (!lastActionOk) {
[6bbdfb]236 clearQueue(CurrentAction); // was not incremented
[419fa2]237 clearTempQueue();
[6bbdfb]238 setActionQueueDone();
239 }
240
241 // insert new actions (before [CurrentAction]) if they have been spawned
242 // we must have an extra vector for this, as we cannot change actionqueue
243 // while an action instance is "in-use"
[419fa2]244
[415ddd]245 insertTempQueue();
[fff8fc]246
[6bbdfb]247 // set last action when all is done for this Action call
[23b6cf]248 if (lastActionOk) {
249 OBSERVE;
250 NOTIFY(ActionQueued);
251 _lastchangedaction = lastaction;
252 }
[415ddd]253 }
254 {
[fff8fc]255 bool new_run_thread_isIdle = isActionQueueDone();
256 new_run_thread_isIdle &= isTempQueueDone();
257 setrun_thread_isIdle(new_run_thread_isIdle);
[415ddd]258 }
259 cond_idle.notify_one();
260// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
[6bbdfb]261 } while ((!Interrupted) && (!isActionQueueDone()));
262 trylock.unlock();
[9a4949]263 }
[415ddd]264}
265
266void ActionQueue::insertTempQueue()
267{
[fff8fc]268 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
[415ddd]269 if (!tempqueue.empty()) {
[fff8fc]270 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
[415ddd]271 ActionQueue_t::iterator InsertionIter = actionqueue.begin();
272 std::advance(InsertionIter, CurrentAction);
273 actionqueue.insert( InsertionIter, tempqueue.begin(), tempqueue.end() );
274 tempqueue.clear();
275 }
276}
277
[fff8fc]278void ActionQueue::setrun_thread_isIdle(
279 const bool _run_thread_isIdle)
[415ddd]280{
[23b6cf]281 boost::unique_lock<boost::mutex> lock(mtx_run_thread_isIdle);
[fff8fc]282 run_thread_isIdle = _run_thread_isIdle;
283}
284
285bool ActionQueue::getrun_thread_isIdle() const
286{
287 boost::unique_lock<boost::mutex> lock(mtx_run_thread_isIdle);
288 return run_thread_isIdle;
289}
290
[415ddd]291void ActionQueue::wait()
292{
[6bbdfb]293 boost::mutex::scoped_lock trylock(mtx_run_thread_running, boost::try_to_lock);
294 if (!trylock) {
[fff8fc]295 boost::unique_lock<boost::mutex> lock(mtx_run_thread_isIdle);
[9a4949]296 while(!run_thread_isIdle)
297 {
298 cond_idle.wait(lock);
299 }
[415ddd]300 }
301}
302
303void ActionQueue::stop()
304{
305 // notify actionqueue thread that we wish to terminate
306 run_thread.interrupt();
307 // wait till it ends
308 run_thread.join();
[975b83]309}
[74459a]310#endif
[975b83]311
[a6ceab]312Action* ActionQueue::getActionByName(const std::string &name)
[1d3563]313{
[ed3944]314 return AR->getActionByName(name);
[1d3563]315}
316
[a6ceab]317bool ActionQueue::isActionKnownByName(const std::string &name) const
[1d3563]318{
[ed3944]319 return AR->isActionPresentByName(name);
[1d3563]320}
321
[126867]322void ActionQueue::registerAction(Action *_action)
323{
324 AR->registerInstance(_action);
325}
326
[46b181]327void ActionQueue::outputAsCLI(std::ostream &output) const
328{
[7fc447]329 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
330 iter != actionqueue.end();
[46b181]331 ++iter) {
[bad589]332 // skip store-session in printed list
[12d946]333 if ( ((*iter)->getName() != std::string("store-session"))
334 && ((*iter)->getName() != std::string("load-session"))) {
[7fc447]335 if (iter != actionqueue.begin())
[bad589]336 output << " ";
337 (*iter)->outputAsCLI(output);
338 }
[46b181]339 }
340 output << std::endl;
341}
342
[477012]343void ActionQueue::outputAsPython(std::ostream &output) const
344{
345 const std::string prefix("pyMoleCuilder");
346 output << "import " << prefix << std::endl;
[9e4655]347 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
[7fc447]348 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
349 iter != actionqueue.end();
[477012]350 ++iter) {
351 // skip store-session in printed list
[12d946]352 if ( ((*iter)->getName() != std::string("store-session"))
353 && ((*iter)->getName() != std::string("load-session")))
[477012]354 (*iter)->outputAsPython(output, prefix);
355 }
[9e4655]356 output << "# =========================== Stored Session END ===========================" << std::endl;
[477012]357}
358
[a6ceab]359const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
[690741]360{
361 // this const_cast is just required as long as we have a non-const getActionByName
362 const Action * const action = const_cast<ActionQueue *>(this)->getActionByName(name);
363 return action->Traits;
364}
365
[6367dd]366void ActionQueue::addElement(Action* _Action,ActionState::ptr _state)
367{
368 history->addElement(_Action, _state);
369}
370
371void ActionQueue::clear()
372{
373 history->clear();
374}
375
[601ef8]376void ActionQueue::clearQueue(const size_t _fromAction)
[7f1a1a]377{
378 // free all actions contained in actionqueue
[fff8fc]379 {
[601ef8]380#ifdef HAVE_ACTION_THREAD
[fff8fc]381 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
[601ef8]382#endif
[7e6c0d]383 LOG(1, "Removing all Actions from position " << _fromAction << " onward.");
384 // free all actions still to be called contained in actionqueue
385 ActionQueue_t::iterator inititer = actionqueue.begin();
386 std::advance(inititer, _fromAction);
387 for (ActionQueue_t::iterator iter = inititer; iter != actionqueue.end(); ++iter)
[fff8fc]388 delete *iter;
[7e6c0d]389 actionqueue.erase(inititer, actionqueue.end());
390 LOG(1, "There are " << actionqueue.size() << " remaining Actions.");
[7f1a1a]391 }
[601ef8]392}
393
394#ifdef HAVE_ACTION_THREAD
395void ActionQueue::clearTempQueue()
396{
[7f1a1a]397 // free all actions contained in tempqueue
[06b5df]398 {
[fff8fc]399 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
400 for (ActionQueue_t::iterator iter = tempqueue.begin();
401 !tempqueue.empty(); iter = tempqueue.begin()) {
402 delete *iter;
403 tempqueue.erase(iter);
404 }
[06b5df]405 }
[7f1a1a]406}
[601ef8]407#endif
[6367dd]408
[690741]409const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
410{
411 ActionTokens_t returnlist;
412
413 returnlist.insert(
414 returnlist.end(),
[ed3944]415 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
416 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
[690741]417
418 return returnlist;
419}
420
[6367dd]421void ActionQueue::undoLast()
422{
423 history->undoLast();
424}
425
[c01fec]426bool ActionQueue::canUndo() const
427{
428 return history->hasUndo();
429}
430
[6367dd]431void ActionQueue::redoLast()
432{
433 history->redoLast();
434}
435
[c01fec]436bool ActionQueue::canRedo() const
437{
438 return history->hasRedo();
439}
440
[6367dd]441
[628577]442CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.