source: src/Actions/Action.hpp@ 8f4df1

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 8f4df1 was 047878, checked in by Tillmann Crueger <crueger@…>, 14 years ago

made all actions pass on the dialogs and add the corresponding queries

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