source: src/Actions/ActionQueue.cpp@ 7e6c0d

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

Merge branch 'ThreadFixes' into Candidate_v1.4.10

Conflicts:

src/Actions/ActionQueue.cpp
src/Actions/ActionQueue.hpp

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