source: src/Actions/Action.hpp@ 23359f

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 23359f was df32ee, checked in by Frederik Heber <heber@…>, 14 years ago

New class ActionTrait(s).

  • ActionTrait is the template class that is specialized for every Action.
  • ActionTraits is the interface that is inherited by every specialization.
  • the interface Action contains AcionTraits itself.
  • each specific Action has a specialized ActionTrait<> contained.

note

  • so far, everything is short-wired through MapOfActions.
  • later the specialization will have specific constructors and get info therein.
  • Property mode set to 100644
File size: 23.4 KB
Line 
1/*
2 * Action.h
3 *
4 * Created on: Dec 8, 2009
5 * Author: crueger
6 */
7
8#ifndef ACTION_H_
9#define ACTION_H_
10
11#include <string>
12#include <boost/shared_ptr.hpp>
13
14// forward declaration
15
16class ActionState;
17class ActionSequence;
18class Dialog;
19
20#include "Actions/ActionTraits.hpp"
21
22/**
23 * @file
24 * <H1> Action Howto </H1>
25 *
26 * <H2> Introduction </H2>
27 *
28 * Actions are used in object oriented design as a replacement for callback functions.
29 * In most ways Actions can be used in the same way that callbacks were used in non
30 * OO-Systems, but can contain support for several extra mechanism such as undo/redo
31 * or progress indicators.
32 *
33 * The main purpose of an action class is to contain small procedures, that can be repeatedly
34 * called. These procedures can also be stored, passed around, so that the execution of an
35 * action can happen quite far away from the place of creation. For a detailed description of
36 * the Action pattern see GOF:1996.
37 *
38 * <H3> How to use an action </H3>
39 *
40 * The process of using an action is as easy as calling the call() method of the action. The
41 * action will then do whatever it is supposed to do. If it is an action that can be undone, it
42 * will also register itself in the history to make itself available for undo. To undo the last
43 * action, you can either use the undoLast() method inside the ActionHistory class or call the
44 * UndoAction also provided by the ActionHistory. If an action was undone it will be available for
45 * redo, using the redoLast() method of the ActionHistory or the RedoAction also provided by this
46 * class. To check whether undo/redo is available at any moment you can use the hasUndo() or
47 * hasRedo() method respectively.
48 *
49 * Note that an Action always has two functions createDialog() and performCall(). The former
50 * returns a Dialog filled with query...() functions for all information that we need from the
51 * user. The latter must not contain any interaction but just uses these values (which are
52 * temporarily stored by class ValueStorage) to perform the Action.
53 *
54 * Furthermore, there is a global action function that makes the action callable with already
55 * present parameters (i.e. without user interaction and for internal use within the code only).
56 * This function is basically just a macro, that puts the parameters into the ValueStorage and
57 * calls Action::call(Action::NonInteractive).
58 *
59 * Actions can be set to be active or inactive. If an action is set to inactive it is signaling, that
60 * some condition necessary for this action to be executed is not currently met. For example the
61 * UndoAction will set itself to inactive, when there is no action at that time that can be undone.
62 * Using call() on an inactive Action results in a no-op. You can query the state of an action using
63 * the isActive() method.
64 *
65 * The undo capabilities of actions come in three types as signaled by two boolean flags (one
66 * combination of these flags is left empty as can be seen later).
67 * <ul>
68 * <li/> The first flag indicates if the undo mechanism for this action should be considered at all, i.e.
69 * if the state of the application changes in a way that needs to be reverted. Actions that should
70 * consider the undo mechanism are for example adding a molecule, moving atoms, changing
71 * the name of a molecule etc. Changing the View-Area on the other hand should be an action that
72 * does not consider the undo mechanism. This flag can be queried using the shouldUndo() method.
73 *
74 * <li/> The second flag indicates whether the changes can be undo for this action. If this flag is true
75 * the action will be made available for undo using the ActionHistory class and the actions of this
76 * class. If this flag is false while the shoudlUndo() flag is true this means that this action
77 * changes the state of the application changes in a way that cannot be undone, but might cause
78 * the undo of previous actions to fail. In this case the whole History is cleared, as to keep
79 * the state of the application intact by avoiding dangerous undos. This flag can be queried
80 * using the canUndo() method.
81 *</ul>
82 *
83 * Each action has a name, that can be used to identify it throughout the run of the application.
84 * This name can be retrieved using the getName() method. Most actions also register themselves with
85 * a global structure, called the ActionRegistry. Actions that register themselves need to have a
86 * unique name for the whole application. If the name is known these actions can be retrieved from
87 * the registry by their name and then be used as normal.
88 *
89 * <H2> Building your own actions </H2>
90 *
91 * Building actions is easy. Each specific ...Action is derived from the base class Action.
92 * In order to create all the reoccuring stuff, macros have been created which you can simply
93 * include and then don't need to worry about it.
94 * There are three major virtual functions: performCall(), performUndo(), performRedo() which
95 * you have to write, to equip your action with some actual capabilities.
96 * Each Action definition and implementation consists of of three files:
97 * -# cpp: contains performX() which you have to write, also some boilerplate functions which are
98 * constructed automatically when including your def and "Actions/action_impl_pre.hpp"
99 * -# hpp: boilerplate definitions created simply by including your def and
100 * "Actions/action_impl_header.hpp"
101 * -# def: macro definitions of all your parameters and additional variables needed for the state,
102 * also name and category and token of your action.
103 *
104 * Best thing to do is look at one of the already present triples and you should soon understand
105 * what you have to add:
106 * -# pick the right category, i.e. the right folder in src/Actions
107 * -# pick the right name
108 * -# decide which parameters your actions need and what the type, the variable name and the token
109 * to reference it from the command-line should be. Check whether already present and fitting
110 * tokens exists, e.g. "position" as token for a Vector representing a position.
111 * -# consider which additional information you need to undo your action
112 * -# don't forget to include your .def file followed by "action_impl_pre.hpp" in .cpp or
113 * "action_impl_header.hpp" in the .hpp
114 * -# continue to write the functionality of your action in performCall(), undo and redo in performUndo()
115 * and performRedo().
116 * -# You should indicate whether the action supports undo by implementing the shouldUndo() and
117 * canUndo() methods to return the appropriate flags.
118 *
119 * <H3> Specific notes on the macros </H3>
120 *
121 * The following functions are created by the macros, i.e. you don't need to worry about it:
122 *
123 * Any user interaction should be placed into the dialog returned by fillDialog().
124 *
125 * Also, create the global function to allow for easy calling of your function internally (i.e.
126 * without user interaction). It should have the name of the Action class without the suffix Action.
127 *
128 * The constructor of your derived class also needs to call the Base constructor, passing it the
129 * name of the Action and a flag indicating whether this action should be made available in the
130 * registry. WARNING: Do not use the virtual getName() method of the derived action to provide the
131 * constructor with the name, even if you overloaded this method to return a constant. Doing this
132 * will most likely not do what you think it does (see: http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.5
133 * if you want to know why this wont work)
134 *
135 * <H3> Interfacing your Action with the Undo mechanism </H3>
136 *
137 * The performX() methods need to comply to a simple standard to allow for undo and redo. The first
138 * convention in this standard concerns the return type. All methods that handle calling, undoing
139 * or redoing return an object of Action::state_ptr. This is a smart pointer to a State object, that
140 * can be used to store state information that is needed by your action for later redo. A rename
141 * Action for example would need to store which object has been renamed and what the old name was.
142 * A move Action on the other hand would need to store the object that has been moved as well as the
143 * old position. If your Action does not need to store any kind of information for redo you can
144 * simply return Action::success and skip the rest of this paragraph. If your action has been
145 * abborted you can return Action::failure, which indicates to the history mechanism that this
146 * action should not be stored.
147 *
148 * If your Action needs any kind of information to undo its execution, you need to store this
149 * information in the state that is returned by the performCall() method. Since no assumptions
150 * can be made on the type or amount of information the ActionState base class is left empty.
151 * To use this class you need to derive a YourActionState class from the ActionState base class
152 * adding your data fields and accessor functions. Upon undo the ActionState object produced
153 * by the corresponding performCall() is then passed to the performUndo() method which should
154 * typecast the ActionState to the appropriate sub class, undo all the changes and produce
155 * a State object that can be used to redo the action if neccessary. This new state object is
156 * then used if the redo mechanism is invoked and passed to the performRedo() function, which
157 * again produces a State that can be used for performUndo().
158 *
159 * <H3> Outline of the implementation of Actions </H3>
160 *
161 * To sum up the actions necessary to build actions here is a brief outline of things methioned
162 * in the last paragraphs:
163 *
164 * <H4> Basics </H4>
165 *
166 * <ul>
167 * <li/> create parameter tupels (type, token, reference), put into def. Access them later in
168 * the performX() via the structure params.###.
169 * <li/> think of name, category and token for your action, put into def
170 * <li/> create additional state variables tupels (type, reference) for storing extra information
171 * that you need for undo/redo in the ActionState. You can always access the parameters
172 * of your Action by state.params.### (i.e. they are copied to the state by default).
173 * <li/> implement performCall(), first line should be calling of getParametersfromValueStorage().
174 * <li/> performUndo(), performRedo()
175 * <li/> implement the functions that return the flags for the undo mechanism, i.e. true/false.
176 * </ul>
177 *
178 * <H4> Implementing performX() methods </H4>
179 *
180 * <ul>
181 * <li/> performCall():
182 * <ul>
183 * <li/> first line should be calling of getParametersfromValueStorage().
184 * <li/> Access your parameters by the structure params.### (where ### stands for the reference/
185 * variable name chosen in the tupel).
186 * <li/> do whatever is needed to make the action work
187 * <li/> if the action was abborted return Action::failure
188 * <li/> if the action needs to save a state return a custom state object
189 * <li/> otherwise return Action::success
190 * </ul>
191 * <li/> performUndo():
192 * <ul>
193 * <li/> typecast the ActionState pointer to a Pointer to YourActionState if necessary
194 * <li/> undo the action using the extra information and the Action's parameters in the state
195 * <li/> produce a new state that can be used for redoing and return it
196 * </ul>
197 * <li/> performRedo():
198 * <ul>
199 * <li/> take the ActionState produced by performUndo and typecast it to a pointer to YourActionState if necessary
200 * <li/> redo the undone action using the extra information and the Action's parameters in the state
201 * <li/> produce a new state that can be used by performUndo() and return it
202 * </ul>
203 * </ul>
204 *
205 * <H2> Advanced techniques </H2>
206 *
207 * <H3> Predefined Actions </H3>
208 *
209 * To make construction of actions easy there are some predefined actions. Namely these are
210 * the MethodAction and the ErrorAction.
211 *
212 * The method action can be used to turn any function with empty arguments and return type void
213 * into an action (also works for functors with those types). Simply pass the constructor for the
214 * MethodAction a name to use for this action, the function to call inside the performCall()
215 * method and a flag indicating if this action should be made retrievable inside the registry
216 * (default is true). MethodActions always report themselves as changing the state of the
217 * application but cannot be undone. i.e. calling MethodActions will always cause the ActionHistory
218 * to be cleared.
219 *
220 * ErrorActions can be used to produce a short message using the Log() << Verbose() mechanism of
221 * the molecuilder. Simply pass the constructor a name for the action, the message to show upon
222 * calling this action and the flag for the registry (default is again true). Error action
223 * report that they do not change the state of the application and are therefore not considered
224 * for undo.
225 *
226 * <H3> Sequences of Actions and MakroActions </H3>
227 *
228 * <H4> Building sequences of Actions </H4>
229 *
230 * Actions can be chained to sequences using the ActionSequence class. Once an ActionSequence is
231 * constructed it will be initially empty. Any Actions can then be added to the sequence using the
232 * addAction() method of the ActionSequence class. The last added action can be removed using the
233 * removeLastAction() method. If the construction of the sequence is done, you can use the
234 * callAll() method. Each action called this way will register itself with the History to allow
235 * separate undo of all actions in the sequence.
236 *
237 * <H4> Building larger Actions from simple ones </H4>
238 *
239 * Using the pre-defined class MakroAction it is possible to construct bigger actions from a sequence
240 * of smaller ones. For this you first have to build a sequence of the actions using the ActionSequence
241 * as described above. Then you can construct a MakroAction passing it a name, the sequence to use
242 * and as usual a flag for the registry. You can then simply call the complete action-sequence through
243 * this makro action using the normal interface. Other than with the direct use of the action sequence
244 * only the complete MakroAction is registered inside the history, i.e. the complete sequence can be
245 * undone at once. Also there are a few caveats you have to take care of when using the MakroAction:
246 * <ul>
247 * <li/> All Actions as well as the sequence should exclusively belong to the MakroAction. This
248 * especially means, that the destruction of these objects should be handled by the MakroAction.
249 * <li/> none of the Actions inside the MakroAction should be registered with the registry, since the
250 * registry also assumes sole ownership of the actions.
251 * <li/> Do not remove or add actions from the sequence once the MakroAction has been constructed, since this
252 * might brake important assumptions for the undo/redo mechanism
253 * </ul>
254 *
255 * <H3> Special kinds of Actions </H3>
256 *
257 * To make the usage of Actions more versatile there are two special kinds of actions defined,
258 * that contain special mechanisms. These are defined inside the class Process, for actions that
259 * take some time and indicate their own progress, and in the class Calculations for actions that
260 * have a retrievable result.
261 *
262 * <H4> Processes </H4>
263 *
264 * Processes are Actions that might take some time and therefore contain special mechanisms
265 * to indicate their progress to the user. If you want to implement a process you can follow the
266 * guidelines for implementing actions. In addition to the normal Action constructor parameters,
267 * you also need to define the number of steps the process takes to finish (use 0 if that number is
268 * not known upon construction). At the beginning of your process you then simply call start() to
269 * indicate that the process is taking up its work. You might also want to set the number of steps it
270 * needs to finish, if it has changed since the last invocation/construction. You can use the
271 * setMaxSteps() method for this. Then after each finished step of calulation simply call step(),
272 * to let the indicators know that it should update itself. If the number of steps is not known
273 * at the time of calculation, you should make sure the maxSteps field is set to 0, either through
274 * the constructor or by using setMaxSteps(0). Indicators are required to handle both processes that
275 * know the number of steps needed as well as processes that cannot predict when they will be finished.
276 * Once your calculation is done call stop() to let every indicator know that the process is done with
277 * the work and to let the user know.
278 *
279 * Indicators that want to know about processes need to implement the Observer class with all the
280 * methods defined there. They can then globally sign on to all processes using the static
281 * Process::AddObserver() method and remove themselves using the Process::RemoveObserver()
282 * methods. When a process starts it will take care that the notification for this process
283 * is invoked at the right time. Indicators should not try to observe a single process, but rather
284 * be ready to observe the status of any kind of process using the methods described here.
285 *
286 * <H4> Calculations </H4>
287 *
288 * Calculations are special Actions that also return a result when called. Calculations are
289 * always derived from Process, so that the progress of a calculation can be shown. Also
290 * Calculations should not contain side-effects and not consider the undo mechanism.
291 * When a Calculation is called using the Action mechanism this will cause it to calculate
292 * the result and make it available using the getResult() method. Another way to have a Calculation
293 * produce a result is by using the function-call operator. When this operator is used, the Calculation
294 * will try to return a previously calculated and cached result and only do any actuall calculations
295 * when no such result is available. You can delete the cached result using the reset() method.
296 */
297
298
299/**
300 * Base class for all actions.
301 *
302 * Actions describe something that has to be done.
303 * Actions can be passed around, stored, performed and undone (Command-Pattern).
304 */
305class Action
306{
307friend class ActionSequence;
308friend class ActionHistory;
309public:
310
311 enum QueryOptions {Interactive, NonInteractive};
312
313 /**
314 * This type is used to store pointers to ActionStates while allowing multiple ownership
315 */
316 typedef boost::shared_ptr<ActionState> state_ptr;
317
318 /**
319 * Standard constructor of Action Base class
320 *
321 * All Actions need to have a name. The second flag indicates, whether the action should
322 * be registered with the ActionRegistry. If the Action is registered the name of the
323 * Action needs to be unique for all Actions that are registered.
324 */
325 Action(std::string _name,bool _doRegister=true);
326 virtual ~Action();
327
328 /**
329 * This method is used to call an action. The basic operations for the Action
330 * are carried out and if necessary/possible the Action is added to the History
331 * to allow for undo of this action.
332 *
333 * If the call needs to undone you have to use the History, to avoid destroying
334 * invariants used by the History.
335 *
336 * Note that this call can be Interactive (i.e. a dialog will ask the user for
337 * necessary information) and NonInteractive (i.e. the information will have to
338 * be present already within the ValueStorage class or else a MissingArgumentException
339 * is thrown)
340 */
341 void call(enum QueryOptions state = Interactive);
342
343 /**
344 * This method provides a flag that indicates if an undo mechanism is implemented
345 * for this Action. If this is true, and this action was called last, you can
346 * use the History to undo this action.
347 */
348 virtual bool canUndo()=0;
349
350 /**
351 * This method provides a flag, that indicates if the Action changes the state of
352 * the application in a way that needs to be undone for the History to work.
353 *
354 * If this is false the Action will not be added to the History upon calling. However
355 * Actions called before this one will still be available for undo.
356 */
357 virtual bool shouldUndo()=0;
358
359 /**
360 * Indicates whether the Action can do it's work at the moment. If this
361 * is false calling the action will result in a no-op.
362 */
363 virtual bool isActive();
364
365 /**
366 * Returns the name of the Action.
367 */
368 virtual const std::string getName();
369
370 ActionTraits Traits;
371
372protected:
373 /**
374 * This method is called by the History, when an undo is performed. It is
375 * provided with the corresponding state produced by the performCall or
376 * performRedo method and needs to provide a state that can be used for redo.
377 */
378 state_ptr undo(state_ptr);
379
380 /**
381 * This method is called by the Histor, when a redo is performed. It is
382 * provided with the corresponding state produced by the undo method and
383 * needs to produce a State that can then be used for another undo.
384 */
385 state_ptr redo(state_ptr);
386
387 /**
388 * This special state can be used to indicate that the Action was successfull
389 * without providing a special state. Use this if your Action does not need
390 * a speciallized state.
391 */
392 static state_ptr success;
393
394 /**
395 * This special state can be returned, to indicate that the action could not do it's
396 * work, was abborted by the user etc. If you return this state make sure to transactionize
397 * your Actions and unroll the complete transaction before this is returned.
398 */
399 static state_ptr failure;
400
401 /**
402 * This creates the dialog requesting the information needed for this action from the user
403 * via means of the user interface.
404 */
405 Dialog * createDialog();
406
407private:
408
409 /**
410 * This is called internally before the Action::performCall(). It initializes the
411 * necessary ActionParameters by retrieving the values from ValueStorage.
412 */
413 virtual void getParametersfromValueStorage()=0;
414
415 /**
416 * This is called internally before the action is processed. This adds necessary queries
417 * to a given dialog to obtain parameters for the user for processing the action accordingly.
418 * The dialog will be given to the user before Action::performCall() is initiated, values
419 * are transfered via ValueStorage.
420 */
421 virtual Dialog * fillDialog(Dialog*)=0;
422
423 /**
424 * This is called internally when the call is being done. Implement this method to do the actual
425 * work of the Action. Implement this in your Derived classes. Needs to return a state that can be
426 * used to undo the action.
427 */
428 virtual state_ptr performCall()=0;
429
430 /**
431 * This is called internally when the undo process is chosen. This Method should use the state
432 * produced by the performCall method to return the state of the application to the state
433 * it had before the Action.
434 */
435 virtual state_ptr performUndo(state_ptr)=0;
436
437 /**
438 * This is called internally when the redo process is chosen. This method shoudl use the state
439 * produced by the performUndo method to return the application to the state it should have after
440 * the action.
441 *
442 * Often this method can be implement to re-use the performCall method. However if user interaction
443 * or further parameters are needed, those should be taken from the state and not query the user
444 * again.
445 */
446 virtual state_ptr performRedo(state_ptr)=0;
447
448 std::string name;
449};
450
451/**
452 * This class can be used by actions to save the state.
453 *
454 * It is implementing a memento pattern. The base class is completely empty,
455 * since no general state internals can be given. The Action performing
456 * the Undo should downcast to the apropriate type.
457 */
458class ActionState{
459public:
460 ActionState(){}
461 virtual ~ActionState(){}
462};
463
464/**
465 * This class can be used by actions to contain parameters.
466 *
467 * The base class is completely empty, since no general parameters can be given. The
468 * Action performing the function should construct its own parameter class derived
469 * from it.
470 */
471class ActionParameters{
472public:
473 ActionParameters(){}
474 virtual ~ActionParameters(){}
475};
476
477#endif /* ACTION_H_ */
Note: See TracBrowser for help on using the repository browser.