source: src/Actions/ActionQueue.cpp@ 76a109

Last change on this file since 76a109 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
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 CurrentAction(0),
68 lastActionOk(true),
69 run_thread(boost::bind(&ActionQueue::run, this)),
70 run_thread_isIdle(true)
71#endif
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}
80
81ActionQueue::~ActionQueue()
82{
83#ifdef HAVE_ACTION_THREAD
84 stop();
85
86 clearTempQueue();
87#endif
88
89 clearQueue();
90
91 delete history;
92 delete AR;
93}
94
95void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
96{
97 const Action * const registryaction = AR->getActionByName(name);
98 queueAction(registryaction, state);
99}
100
101void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
102{
103 Action *newaction = _action->clone(state);
104 newaction->prepare(state);
105#ifdef HAVE_ACTION_THREAD
106 mtx_queue.lock();
107#endif
108 actionqueue.push_back( newaction );
109#ifndef HAVE_ACTION_THREAD
110 try {
111 newaction->call();
112 lastActionOk = true;
113 } catch(ActionFailureException &e) {
114 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
115 World::getInstance().setExitFlag(5);
116 clearQueue(actionqueue.size()-1);
117 lastActionOk = false;
118 std::cerr << "Remaining Actions cleared from queue." << std::endl;
119 } catch (std::exception &e) {
120 pushStatus("FAIL: General exception caught, aborting.");
121 World::getInstance().setExitFlag(134);
122 clearQueue(actionqueue.size()-1);
123 lastActionOk = false;
124 std::cerr << "Remaining Actions cleared from queue." << std::endl;
125 }
126 if (lastActionOk) {
127 OBSERVE;
128 NOTIFY(ActionQueued);
129 _lastchangedaction = newaction;
130 }
131#else
132 setRunThreadIdle(CurrentAction == actionqueue.size());
133 mtx_queue.unlock();
134#endif
135}
136
137void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
138{
139#ifndef HAVE_ACTION_THREAD
140 queueAction(_action, state);
141#else
142 Action *newaction = _action->clone(state);
143 newaction->prepare(state);
144 mtx_queue.lock();
145 tempqueue.push_back( newaction );
146 setRunThreadIdle( !((CurrentAction != actionqueue.size()) || !tempqueue.empty()) );
147 mtx_queue.unlock();
148#endif
149}
150
151#ifdef HAVE_ACTION_THREAD
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
161 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
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();
178 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
179 lastActionOk = true;
180 } catch(ActionFailureException &e) {
181 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
182 World::getInstance().setExitFlag(5);
183 clearQueue(CurrentAction);
184 clearTempQueue();
185 lastActionOk = false;
186 std::cerr << "Remaining Actions cleared from queue." << std::endl;
187 } catch (std::exception &e) {
188 pushStatus("FAIL: General exception caught, aborting.");
189 World::getInstance().setExitFlag(134);
190 clearQueue(CurrentAction);
191 clearTempQueue();
192 std::cerr << "Remaining Actions cleared from queue." << std::endl;
193 }
194 if (lastActionOk) {
195 OBSERVE;
196 NOTIFY(ActionQueued);
197 _lastchangedaction = actionqueue[CurrentAction];
198 mtx_queue.lock();
199 CurrentAction++;
200 mtx_queue.unlock();
201 }
202 if (lastActionOk) {
203 OBSERVE;
204 NOTIFY(ActionQueued);
205 _lastchangedaction = actionqueue[CurrentAction];
206 }
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 }
216 setRunThreadIdle( !((CurrentAction != actionqueue.size()) || !tempqueue.empty()) );
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}
240#endif
241
242#ifdef HAVE_ACTION_THREAD
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();
249}
250#endif
251
252Action* ActionQueue::getActionByName(const std::string &name)
253{
254 return AR->getActionByName(name);
255}
256
257bool ActionQueue::isActionKnownByName(const std::string &name) const
258{
259 return AR->isActionPresentByName(name);
260}
261
262void ActionQueue::registerAction(Action *_action)
263{
264 AR->registerInstance(_action);
265}
266
267void ActionQueue::outputAsCLI(std::ostream &output) const
268{
269 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
270 iter != actionqueue.end();
271 ++iter) {
272 // skip store-session in printed list
273 if ( ((*iter)->getName() != std::string("store-session"))
274 && ((*iter)->getName() != std::string("load-session"))) {
275 if (iter != actionqueue.begin())
276 output << " ";
277 (*iter)->outputAsCLI(output);
278 }
279 }
280 output << std::endl;
281}
282
283void ActionQueue::outputAsPython(std::ostream &output) const
284{
285 const std::string prefix("pyMoleCuilder");
286 output << "import " << prefix << std::endl;
287 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
288 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
289 iter != actionqueue.end();
290 ++iter) {
291 // skip store-session in printed list
292 if ( ((*iter)->getName() != std::string("store-session"))
293 && ((*iter)->getName() != std::string("load-session")))
294 (*iter)->outputAsPython(output, prefix);
295 }
296 output << "# =========================== Stored Session END ===========================" << std::endl;
297}
298
299const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
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
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
316void ActionQueue::clearQueue(const size_t _fromAction)
317{
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)
326 delete *iter;
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{
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 }
344}
345
346void ActionQueue::setRunThreadIdle(const bool _flag)
347{
348 {
349 boost::unique_lock<boost::mutex> lock(mtx_idle);
350 run_thread_isIdle = _flag;
351 }
352}
353#endif
354
355const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
356{
357 ActionTokens_t returnlist;
358
359 returnlist.insert(
360 returnlist.end(),
361 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
362 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
363
364 return returnlist;
365}
366
367void ActionQueue::undoLast()
368{
369 history->undoLast();
370}
371
372bool ActionQueue::canUndo() const
373{
374 return history->hasUndo();
375}
376
377void ActionQueue::redoLast()
378{
379 history->redoLast();
380}
381
382bool ActionQueue::canRedo() const
383{
384 return history->hasRedo();
385}
386
387
388CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.