Generalized Undo Support in Eclipse

Last updated:  Feb. 22, 2005

Status:  Proposal – Implemented in 3.1M5

(see also bug  37716)

Problem Description

In R3.0.1 of the Eclipse SDK, there is no generalized support for undoing user actions.  Each plug-in is left to implement its own strategy for undo, if at all.  This approach can cause problems for both Eclipse users and plug-in developers:

 

 

Further, the meaning of undo can be very different depending on what the user is doing.  The most common type of undo is text undo.  The user can undo lightweight edit operations such as inserting, replacing, or deleting text.  Other types of undo may involve more complex, heavyweight operations that affect an underlying model of many elements.  For example, the JDT refactoring support provides undo support for refactoring operations that involve many Java elements at different levels, such as Java packages, compilation units, classes, and methods.

Operations Framework

The proposed framework defines an interface for describing work, called an “undoable operation” (IUndoableOperation), that can be executed, undone, and redone.  Undoable operations are created, executed, and added to an operations history (IOperationHistory).  Operations which are comprised of distinct steps should be represented as compound operations, which are executed, undone, or redone as a unit, and can never be partially undone. 

 

Operations can be assigned one or more contexts (IUndoContext) to which they apply.  An undo context describes the context in which the user is working when an operation is performed, undone, or redone.  Undo contexts can be used by workbench parts to filter the operations history, so that only those operations that have been assigned the context of interest to a particular part are available for undo/redo when that part is active.

 

The interface for undo contexts is left very general so that operation implementers may choose the appropriate representation for their contexts.  In some cases, a part-oriented context may be appropriate. For example, a text editor’s context is related to the editor itself and its life-cycle is similar to that of the editor.  The resource navigator’s context is closely related to the workspace model objects, and the context related to the workspace has a life cycle to similar to that of the workspace itself.

 

Contexts can be assigned to operations in multiple ways:

 

1.       The context can be assigned initially when the operation is created.  For example, text operations are triggered by typing in the editor, and the editor can assign its context to the operation before adding it to the history. 

2.       A listener interface on the operations history allows listeners to detect when an operation is added to the history.  Listeners can decide if their context should be added to the operation. 

3.       Operations can be executed in a batch mode.  When a batching operation is being executed, any other operations that execute have their contexts assigned to the batch operation.

 

An operation may have more than one context.  For example, an operation may affect many elements in the workspace, including one that is currently open in an editor.  That operation could be assigned two independent contexts, so that it can be undone from both the editor and the view manipulating the model.  

 

Levels of Integration and Migration

Many plug-ins have already invested heavily in building objects that describe undoable user commands or operations.  It is not expected that all plug-ins will adopt the framework completely, given the individual schedules and other constraints for each plug-in.  However, the integration can be achieved in phases that will immediately provide value to dependent plug-ins.  The following adoption strategy is strongly encouraged:

 

  1. Existing command/undo frameworks can implement the IUndoableOperation interface on their existing command objects, while still maintaining their individual strategies for managing undo stacks or histories.  If there is a substantial investment in an existing model-based operation or command framework, wrappers could be used to map IUndoableOperation protocol to the existing protocol.  The commands/operations need not be assigned a context or added to a common operation history.  This level of integration allows command hierarchies built in different frameworks to be treated the same by plug-ins that depend upon these different frameworks.  Clients of existing command frameworks may then use the workbench operation history, assign contexts to operations as needed, and even add operations to the history, while still using commands built on earlier frameworks.
  2. Existing command/undo frameworks may use the listener interfaces provided by the operations history to listen for operations that are of interest.  These commands may be wrapped or otherwise recorded so that they can be undone from privately maintained undo implementations.  This level of integration allows views and editors to appear more tightly integrated with the operations framework, since workbench operations of interest can be undone or redone from private undo implementations.
  3. Full integration is achieved by using the workbench operation history to record the undo and redo history as operations occur.  Once all plug-ins share an operation history, clients will be able to use unified listeners and handlers to track execution of operations, undo, and redo them. 

 

Framework interfaces will be defined in the org.eclipse.core.commands.operations package in the org.eclipse.core.commands plug-in.  This plug-in has no dependencies on the Eclipse runtime architecture (apart from some runtime classes such as IProgressMonitor, IStatus, IAdaptable), so raw JFace clients may make use of it.

Operations and Concurrency

The operations framework relies on the notion of sequential execution of undoable operations.  For R3.1, there will be no specific support built into the framework for concurrent operations that execute inside platform Jobs.  Actions whose work is currently executed inside a Job may be converted to IUndoableOperation, but they should not be added to the operation history until after they have finished their execution.  The undo and redo behavior for these kinds of IUndoableOperation must be implemented in a synchronous manner for R3.1, since the validity of other operations in the operation history may not be properly determined if an undo or redo is executing asynchronously in a Job.  More robust support for concurrent, undoable operations may be considered in future releases as requirements are discovered.

Framework interfaces

Initial implementations of the proposed framework interfaces appear in R3.1 M5.  See the Javadoc for the described classes for the complete specification.   Please note that the specification is still evolving and early adopters should be prepared for API changes throughout the R3.1 development cycle.

IUndoableOperation

IUndoableOperation defines an operation that can be executed, undone, and redone.  Operations typically have fully defined parameters. That is, they are usually created after the user has been queried for any input needed to define the operation.

 

Operations determine their ability to execute, undo, or redo according to the current state of the application. They do not make decisions about their validity based on where they occur in the operation history. That is left to the particular operation history.

 

IOperationHistory

IOperationHistory tracks a history of operations that can be undone or redone. Operations are added to the history after they have been initially executed. Clients may choose whether to have the operations history perform the initial execution or simply add the operation to the history. Once operations are added to the history, the methods canRedo() and canUndo() are used to determine whether there is an operation available for undo and redo in a given undo context.  The context-based protocol implies that there is only one operation that can be undone or redone at a given time in a given context. This is typical of a linear undo model, when only the most recently executed operation is available for undo. When this protocol is used, a linear model is enforced by the history. It is up to clients to determine how to maintain a history that is invalid or stale. For example, when the most recent operation for a context cannot be performed, clients may wish to flush the history for that context.

 

Additional protocol allows direct undo and redo of a specified operation, regardless of its position in the history. When a more flexible undo model is supported, these methods can be implemented to undo and redo directly specified operations. If an implementer of IOperationHistory does not allow direct undo and redo, these methods can return a status indicating that it is not allowed.

 

Listeners (IOperationHistoryListener) can listen for notifications about changes in the history (operations added or removed), and for notification before and after any operation is executed, undone or redone. Notification of operation execution only occurs when clients direct the history to execute the operation. If the operation is added after it is executed, there can be no notification of its execution.

 

IOperationApprover defines an interface for approving an undo or redo before it occurs. This is useful for injecting policy-decisions into the model - whether direct undo and redo are supported, or warning the user about certain kinds of operations. It can also be used when objects have state related to the operation and need to determine whether an undo or redo will cause any conflicts with their local state.

IOperationApprover

IOperationApprover defines an interface for approving the undo or redo of a particular operation within an operation history. Operations that are candidates for undo or redo have already been validated against their current state and according to the rules of the history.

 

By the time an IOperationApprover is consulted, the undo has already been requested. Approvers should true if the operation should proceed, and false if it should not. When an operation is rejected, it is expected that the object rejecting the operation has already consulted the user if necessary or otherwise provided any necessary information to the user about the rejection.  If an undo or redo is triggered from the UI, clients provide UI info (such as an org.eclipse.swt.Shell) to assist in prompting the user where necessary.

IOperationHistoryListener

IOperationHistoryListener defines the interface for being notified about particular events that take place inside the operation history.

OperationHistoryEvent

OperationHistoryEvent defines the different types of events that occur inside an operation history.  Listeners are notified before and after an operation is executed, undone, or redone.  Listeners are also notified when operations are added or removed from the history.

OperationHistoryFactory

OperationHistoryFactory provides access to a singleton instance of an operation history.  This factory will provide a default implementation for an operation history if one is not set by a caller.  Once the singleton is obtained by any client, the instance cannot be reset.

UI Support Classes

Additional support classes are provided in the package org.eclipse.ui.operations.  These classes handle policy decisions about the undo model to be used by the workbench.  Access to the undo and redo handlers, as well as the operations history, will be provided through workbench.

Workbench Operation History

The workbench will configure the default operation history supplied by the OperationHistoryFactory and register an IUndoContext adapter onto the workspace.  Configuration of the operation history includes setting an undo limit for the workspace undo context and adding an IOperationApprover that enforces a per-context linear undo model. 

 

Undo contexts will be defined for text editors and for the workspace.  Throughout the development of R3.1, plug-ins will be encouraged to define operations that represent their existing actions or command handlers.  Additional contexts may be defined by plug-ins as necessary.  Undoable operations will be added incrementally once the framework is in place. 

IWorkbenchOperationSupport

IWorkbenchOperationSupport provides access to the workbench operation history and the workspace undo context.  Although these objects are actually managed elsewhere (in the OperationHistoryFactory and as an adapter on the workspace), IWorkbenchOperationSupport provides integrated access to all undo facilities used by the workbench.  Plug-ins aware of the workbench will typically get the IWorkbenchOperationSupport from the workbench to obtain the appropriate context and operation history.  Lower-level (headless) plug-ins that implement undo support will use the lower level constructs, such as the OperationHistoryFactory, to obtain these objects.

UndoActionHandler and RedoActionHandler

The Edit>Undo and Edit>Redo commands should be handled by any parts that wish to support undo.  Common handlers for the undo and redo commands will be provided.  These handlers can be assigned an undo context that should be used to filter the undo and redo history.  The handlers are responsible for the following:

Undo and Redo Toolbar Items

Time permitting, classes that support toolbar dropdown items for undo and redo will be developed.  These will also be assigned a context.  By clicking on the drop-down arrow, the user will see the history for that particular context.  The user will only be able to select a range, starting from the top item, to be undone or redone.  It is expected that the ability to view the history is more valuable to the user than the ability to multi-select operations for undo.

Operation Approvers

The IOperationApprover installed by the workbench enforces a per-context linear undo model by consulting all contexts of an operation to determine whether undo or redo should proceed.  The policy is described as follows:

 

The workbench will allow undo or redo of any valid operation in the history, as long as there are no more recent operations in the history that share a context with the operation to be executed.   If the operation to be undone or redone has contexts that are also present in operations appearing later in the history, then the undo or redo of the operation will not be permitted.

 

A concrete example will help explain this. 

  1. The user makes local edits in editor A.
  2. The user initiates a refactoring operation whose context is “A” and “workspace.”
  3. The user makes additional local edits to editor A.
  4. The user goes to the navigator and selects Undo.

 

In the proposed implementation, the navigator requests an undo for the workspace context.  The refactoring operation triggered in the editor is the most recent operation that has the workspace context, but it also contains context “A.”  Since subsequent operations in the history also have context “A,”, the operation will not be allowed.  An explanation will be provided to the user after the fact:  “Cannot undo the refactoring operation because there have been subsequent changes to A.” 

 

Future releases may warn the user or provide a preference to determine whether the undo should proceed anyway, and whether the subsequent changes to “A” should also be undone, or be flushed from the history. Early prototypes of the framework showed that such warnings interrupt workflow and can be very difficult to understand, so the initial UI will be to prohibit the undo, explaining why.  

Migration Examples

The following examples explain how existing code can be migrated to use the operations framework.  An early prototype used these techniques to integrate the SDK text editor, refactoring framework, and sample applications into a common undo framework. 

Mapping existing actions or command handlers to operations

Converting an existing action to use operations is straightforward, apart from implementing the undo and redo behavior for the action.  The run() or runWithEvent method inside the action should create an operation, execute it, and add it to the operations history, rather than run the code inside the method.  The following code shows the existing run() method in the EditorAction of the readme tool example (org.eclipse.ui.examples.readmetool):

 

public void run() {
            String editorName = MessageUtil.getString("Empty_Editor_Name"); 
            if (activeEditor != null)
                editorName = activeEditor.getTitle();
            MessageDialog
                    .openInformation(
                            shell,
                            MessageUtil.getString("Readme_Editor"), 
                            MessageUtil.format("ReadmeEditorActionExecuted", 
                               new Object[] { getText(), editorName })); 
        }
Using operations, the run method simplifies:
 
        public void run() {
            String editorName = MessageUtil.getString("Empty_Editor_Name"); 
            if (activeEditor != null)
                editorName = activeEditor.getTitle();
            // create the operation
            IUndoableOperation operation = new EditorOperation(
               getText(),shell, editorName);
            // execute (and add to the history)
            history.execute(operation, null, null);  
        }
The operation encapsulates the old run behavior, as well as the undo and redo for the operation:
 
class EditorOperation extends AbstractOperation {
        Shell fShell;
        String fEditorName;
        public EditorOperation(String label, Shell shell, String editorName) {
            super(label);
            fShell = shell;
            fEditorName = editorName;
            
        }
        public IStatus execute(IProgressMonitor monitor) {
            MessageDialog.openInformation(
                    fShell,
                    MessageUtil.getString("Readme_Editor"), 
                    MessageUtil.format("ReadmeEditorActionExecuted", 
                       new Object[] { getLabel(), fEditorName }));  
            return Status.OK_STATUS;
        }
        public IStatus undo(IProgressMonitor monitor) {
            // implement the undo here
            return Status.OK_STATUS;
        }
        public IStatus redo(IProgressMonitor monitor) {
            // implement the redo here
            return Status.OK_STATUS;
        }
    }
 
If an IHandler is provided for a command instead of using actions, the execute method of the handler is mapped similarly to the run method in an action:
 
        public Object execute(Map params) throws ExecutionException {
        try {
            IEditorPart activeEditor = params.get("ACTIVE_EDITOR");
            Shell shell = params.get("SHELL");
            String label = params.get("NAME");
            String editorName = MessageUtil.getString("Empty_Editor_Name"); 
            if (activeEditor != null)
                editorName = activeEditor.getTitle();
            // create the operation
            IUndoableOperation operation =new EditorOperation(label, shell, editorName);
 
            // execute (and add to the history)
            history.execute(operation, null, null);
        } catch (Exception e) {
            throw new ExecutionException(
                    "While executing the operation, an exception occurred", e); 
        }
        return null;
    }
 

When an action launches a wizard. then the operation is typically created as part of processing the “Finish” button in the wizard.  Some restructuring may be required.  For example, wizards are often implemented in hierarchies and make use of convenience methods in the wizard hierarchy.  Some of these methods may have to move to a corresponding hierarchy of operations.

Refactoring example:  mapping existing protocol to IUndoableOperation

In the current SDK implementation, org.eclipse.ltk.core.refactoring provides an undo framework for undoing refactoring operations.  This framework is based on the notion of “Change” objects.  Change objects that can be undone are responsible for returning the undo version of a change when they are executed.  An undo stack is maintained by an internal undo manager.  This undo manager invalidates the history whenever an unknown workspace change occurs.  Undo-aware objects send signals to the undo manager as they perform operations, so that the undo manager will not invalidate the history.

 

A prototype integrated the refactoring change framework with the operations framework as follows:

1.       The change objects are wrappered with a class that implements IUndoableOperation and maps the operation protocol to the Change protocol.

2.       The refactoring undo manager is replaced with an alternate implementation that uses the operations history to maintain the undo and redo history.

3.       The workspace listener and validation strategy used in the Change framework is maintained, since the timing of the notifications was critical.  Additional integration work could be done to use the operations history listeners for the same purpose, or to change the validation strategy as more workspace operations are supported outside of refactoring.

4.       When a refactoring change is executed, an operation is “opened” in the operations history.  Subsequent operations added to the history are considered part of the open operation, and their contexts are assigned to the original operation.  When the refactoring change is finished, the operation is closed. 

5.       Refactoring operations could be undone and redone from any view or editor that installed the undo and redo handlers on the workspace context.

Text editor example:  implementing IUndoableOperation in preexisting commands

The JFace text framework supports undo and redo of text editing operations.  This implementation relies on private undo stacks that are maintained by each editor.  The JFace IUndoManager listens to text changes coming from the underlying widget, and builds a TextCommand for each undoable edit. 

 

A prototype integrated the text undo in JFace with the operations framework as follows:

  1. The existing TextCommand was altered to implement the IUndoableOperation interface.
  2. Specialized contexts (one instance for each text editor) are assigned to the operations.
  3. The existing UndoManager was replaced with an alternate implementation that added text commands to the operations history instead of a local stack, and used the operation history protocol when handling undo and redo commands.