source: src/Actions/ActionQueue.cpp@ 3e6b93

Last change on this file since 3e6b93 was 76a109, checked in by Frederik Heber <heber@…>, 11 years ago

FIX: Setting ActionQueue::_lastchangedaction without heeding whether Action failed is bad.

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