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
Line 
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
37#include "Actions/ActionQueue.hpp"
38
39#include "CodePatterns/Assert.hpp"
40#include "CodePatterns/IteratorAdaptors.hpp"
41#include "CodePatterns/Log.hpp"
42#include "CodePatterns/Singleton_impl.hpp"
43
44#include <boost/date_time/posix_time/posix_time.hpp>
45#include <boost/version.hpp>
46#include <iterator>
47#include <string>
48#include <sstream>
49#include <vector>
50
51#include "Actions/ActionExceptions.hpp"
52#include "Actions/ActionHistory.hpp"
53#include "Actions/ActionRegistry.hpp"
54#include "World.hpp"
55
56using namespace MoleCuilder;
57
58const Action* ActionQueue::_lastchangedaction = NULL;
59
60ActionQueue::ActionQueue() :
61 Observable("ActionQueue"),
62 AR(new ActionRegistry()),
63 history(new ActionHistory),
64#ifndef HAVE_ACTION_THREAD
65 lastActionOk(true)
66#else
67 lastActionOk(true),
68 CurrentAction(0),
69 run_thread_isIdle(true)
70#endif
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}
79
80ActionQueue::~ActionQueue()
81{
82#ifdef HAVE_ACTION_THREAD
83 stop();
84
85 clearTempQueue();
86#endif
87
88 clearQueue();
89
90 delete history;
91 delete AR;
92}
93
94void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
95{
96 const Action * const registryaction = AR->getActionByName(name);
97 queueAction(registryaction, state);
98}
99
100void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
101{
102 Action *newaction = _action->clone(state);
103 newaction->prepare(state);
104#ifdef HAVE_ACTION_THREAD
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
113 mtx_actionqueue.lock();
114#endif
115 actionqueue.push_back( newaction );
116#ifndef HAVE_ACTION_THREAD
117 try {
118 newaction->call();
119 lastActionOk = true;
120 } catch(ActionFailureException &e) {
121 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
122 World::getInstance().setExitFlag(5);
123// clearQueue(actionqueue.size()-1);
124 lastActionOk = false;
125// std::cerr << "Remaining Actions cleared from queue." << std::endl;
126 } catch (std::exception &e) {
127 pushStatus("FAIL: General exception caught, aborting.");
128 World::getInstance().setExitFlag(134);
129// clearQueue(actionqueue.size()-1);
130 lastActionOk = false;
131// std::cerr << "Remaining Actions cleared from queue." << std::endl;
132 }
133 if (lastActionOk) {
134 OBSERVE;
135 NOTIFY(ActionQueued);
136 _lastchangedaction = newaction;
137 }
138#else
139 mtx_actionqueue.unlock();
140 const bool new_run_thread_isIdle = isActionQueueDone();
141 setrun_thread_isIdle(new_run_thread_isIdle);
142#endif
143}
144
145#ifdef HAVE_ACTION_THREAD
146bool ActionQueue::isActionQueueDone() const
147{
148 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
149 return (CurrentAction == actionqueue.size());
150}
151
152void ActionQueue::setActionQueueDone()
153{
154 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
155 CurrentAction = actionqueue.size();
156}
157
158bool ActionQueue::isTempQueueDone() const
159{
160 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
161 return tempqueue.empty();
162}
163#endif
164
165void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
166{
167#ifndef HAVE_ACTION_THREAD
168 queueAction(_action, state);
169#else
170 Action *newaction = _action->clone(state);
171 newaction->prepare(state);
172 {
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);
180 }
181#endif
182}
183
184#ifdef HAVE_ACTION_THREAD
185void ActionQueue::run()
186{
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) {
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
195 boost::this_thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(100));
196#else
197 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
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();
206 while ((!Interrupted) && (!isActionQueueDone())) {
207 // boost::this_thread::disable_interruption di;
208 // access actionqueue, hence using mutex
209 mtx_actionqueue.lock();
210 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
211 try {
212 actionqueue[CurrentAction]->call();
213 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
214 lastActionOk = true;
215 } catch(ActionFailureException &e) {
216 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
217 World::getInstance().setExitFlag(5);
218 lastActionOk = false;
219 std::cerr << "Remaining Actions cleared from queue." << std::endl;
220 } /* catch (std::exception &e) {
221 pushStatus("FAIL: General exception caught, aborting.");
222 World::getInstance().setExitFlag(134);
223 lastActionOk = false;
224 std::cerr << "Remaining Actions cleared from queue." << std::endl;
225 }*/
226 // remember action we just executed
227 const Action *lastaction = actionqueue[CurrentAction];
228 // step on to next action if last ok
229 if (lastActionOk)
230 CurrentAction++;
231
232 mtx_actionqueue.unlock();
233
234 // remove following Actions outside mutex if current failed
235 if (!lastActionOk) {
236 clearQueue(CurrentAction); // was not incremented
237 clearTempQueue();
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"
244
245 insertTempQueue();
246
247 // set last action when all is done for this Action call
248 if (lastActionOk) {
249 OBSERVE;
250 NOTIFY(ActionQueued);
251 _lastchangedaction = lastaction;
252 }
253 }
254 {
255 bool new_run_thread_isIdle = isActionQueueDone();
256 new_run_thread_isIdle &= isTempQueueDone();
257 setrun_thread_isIdle(new_run_thread_isIdle);
258 }
259 cond_idle.notify_one();
260// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
261 } while ((!Interrupted) && (!isActionQueueDone()));
262 trylock.unlock();
263 }
264}
265
266void ActionQueue::insertTempQueue()
267{
268 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
269 if (!tempqueue.empty()) {
270 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
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
278void ActionQueue::setrun_thread_isIdle(
279 const bool _run_thread_isIdle)
280{
281 boost::unique_lock<boost::mutex> lock(mtx_run_thread_isIdle);
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
291void ActionQueue::wait()
292{
293 boost::mutex::scoped_lock trylock(mtx_run_thread_running, boost::try_to_lock);
294 if (!trylock) {
295 boost::unique_lock<boost::mutex> lock(mtx_run_thread_isIdle);
296 while(!run_thread_isIdle)
297 {
298 cond_idle.wait(lock);
299 }
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();
309}
310#endif
311
312Action* ActionQueue::getActionByName(const std::string &name)
313{
314 return AR->getActionByName(name);
315}
316
317bool ActionQueue::isActionKnownByName(const std::string &name) const
318{
319 return AR->isActionPresentByName(name);
320}
321
322void ActionQueue::registerAction(Action *_action)
323{
324 AR->registerInstance(_action);
325}
326
327void ActionQueue::outputAsCLI(std::ostream &output) const
328{
329 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
330 iter != actionqueue.end();
331 ++iter) {
332 // skip store-session in printed list
333 if ( ((*iter)->getName() != std::string("store-session"))
334 && ((*iter)->getName() != std::string("load-session"))) {
335 if (iter != actionqueue.begin())
336 output << " ";
337 (*iter)->outputAsCLI(output);
338 }
339 }
340 output << std::endl;
341}
342
343void ActionQueue::outputAsPython(std::ostream &output) const
344{
345 const std::string prefix("pyMoleCuilder");
346 output << "import " << prefix << std::endl;
347 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
348 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
349 iter != actionqueue.end();
350 ++iter) {
351 // skip store-session in printed list
352 if ( ((*iter)->getName() != std::string("store-session"))
353 && ((*iter)->getName() != std::string("load-session")))
354 (*iter)->outputAsPython(output, prefix);
355 }
356 output << "# =========================== Stored Session END ===========================" << std::endl;
357}
358
359const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
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
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
376void ActionQueue::clearQueue(const size_t _fromAction)
377{
378 // free all actions contained in actionqueue
379 {
380#ifdef HAVE_ACTION_THREAD
381 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
382#endif
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)
388 delete *iter;
389 actionqueue.erase(inititer, actionqueue.end());
390 LOG(1, "There are " << actionqueue.size() << " remaining Actions.");
391 }
392}
393
394#ifdef HAVE_ACTION_THREAD
395void ActionQueue::clearTempQueue()
396{
397 // free all actions contained in tempqueue
398 {
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 }
405 }
406}
407#endif
408
409const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
410{
411 ActionTokens_t returnlist;
412
413 returnlist.insert(
414 returnlist.end(),
415 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
416 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
417
418 return returnlist;
419}
420
421void ActionQueue::undoLast()
422{
423 history->undoLast();
424}
425
426bool ActionQueue::canUndo() const
427{
428 return history->hasUndo();
429}
430
431void ActionQueue::redoLast()
432{
433 history->redoLast();
434}
435
436bool ActionQueue::canRedo() const
437{
438 return history->hasRedo();
439}
440
441
442CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.