TweetFollow Us on Twitter

Commands and Undo CPX
Volume Number:11
Issue Number:1
Column Tag:Visual Programming

Commands and Undo in Prograph CPX

Command objects to do, redo, and undo

By Kurt Schmucker, Apple Computer, Inc.

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

When the Macintosh first came out in ‘84, there was one feature that users loved and developers hated: undo. For users, knowing that any action could be undone reduced dramatically the level of tension associated with using a new feature in a familiar application, with using a new app, or even with using a computer in general. Developers, unfortunately, had to implement this great functionality, and it wasn’t easy. Storing sufficient state in an event-driven application so that any user action could be undone was simply very difficult.

Command objects in MacApp 1.0 offered a way around this problem - a way that was easy for developers both to comprehend and to implement. A command object is an encapsulation of a user request for some action. It stores enough information to be able to perform the action, to be able to undo the action, and to be able to redo the action, and the methods of that command object perform exactly these functions. In response to a user action, your code allocates an appropriate command object, initializes that object, and then returns that object to the framework. The framework will immediately send the “DoIt” message to this object to have the desired action performed. The framework will hold onto that command object and will automatically send the “UndoIt” and “RedoIt” messages to the object if the user chooses the Undo or Redo menu items from the Edit menu. The developer is completely relieved of the responsibility for the run-time handling of Undo.

To illustrate these ideas, I have implemented an enhanced version of the MiniQuadWorld [1] application in CPX. The Prograph version of this app is on the source code disks and the online sites, along with the full source code (both in standard Prograph project and section files - for those of you who have CPX - and in PICTs for those of you who don’t). Also, the code for this application follows the latest version of the emerging Prograph coding style [2, 3].

Brief Review of Commands in MacApp

Both MacApp and CPX have basically the same approach to menu operation, so let’s do a quick review of command handling in MacApp 2 and MacApp 3 before we talk about the details of CPX’s. The command handling designs of MacApp 2 and MacApp 3 are different enough that we will examine each separately.

Commands in MacApp 2

You access the command handling apparatus of MacApp 2 with “hook” methods like DoMenuCommand and DoMouseCommand. (Figure 1 depicts the classes and important methods in this apparatus.) MacApp will call these methods when a menu item is chosen (DoMenuCommand) or when the user clicks in one of your views (DoMouseCommand). (In the case of DoMenuCommand, the argument will be the command number of the desired command. In the case of DoMouseCommand, the arguments will include the click point, from which you need to determine the right type of command.) You override these methods to allocate an instance of one of your command objects, and then return that object as the return value of the method. TApplication.PerformCommand will eventually call that command object’s DoIt method and, if it is an undoable command, will store the command object in TApplication.fLastCommand. Should the user choose the Undo menu item, then TApplication.DoMenuCommand will allocate an instance of TUndoRedoCommand which in turn will call the UndoIt method of the stored command. (Naturally, TUndoRedoCommand is not itself an undoable command.)

There is also a command queue for handling commands in the background and a mechanism for executing a command on a recurring basis.

Figure 1. The classes, methods, and fields that play important roles
in command handling in MacApp 2.

Most of the basic operations that MacApp performs automatically (or semi-automatically) like saving documents, reverting, quitting, opening and closing windows, and such are done with specific TCommand subclasses that are built into MacApp. These include the classes TAboutAppCommand, TCloseWindowCommand, TNewDocCommand, TRowSelectCommand (for a grid).

Commands in MacApp 3

The command apparatus for MacApp 3 is similar but somewhat more complex than that of MacApp 2. (Figure 2 depicts the classes and important methods in this apparatus.) There is an additional class, TCommandHandler, which provides the functionality for storing the last command, processing undo requests, etc. Since the main abstract superclasses that a programmer deals with (TApplication, TDocument, TView) are subclasses of TCommandHandler, this gives each of these objects the ability to undo its own last command. Thus each user context (window or document) has its own undo.

Figure 2. The classes, methods, and fields
that play important roles in command handling in MacApp 3.
(Note the addition of several new classes compared to that of MacApp 2.)

An additional change is that the old “hook” methods, DoMenuCommand and DoMouseCommand, no longer return the command object to the framework. Rather the programmer posts the command (using TApplication.PostCommand) which adds the command to the end of the event list. (TView and TDocument have a PostCommand method, but all these methods do is pass the command on to the application object.) These hook methods are still invoked by the framework, however, so that your code knows the appropriate time to instantiate a new command object.

As in MacApp 2, most of the basic operations that MacApp performs automatically (or semi-automatically) like saving documents, reverting, publishing and subscribing, etc. are done with specific TCommand subclasses that are built into MacApp. These include the classes TQuitCommand, TPrintCommand, TNewSubscriberCommand, TShowTearOffWindowCommand, and TECutCopyCommand.

Commands In CPX

Approach

The CPX approach to commands is somewhere between that of MacApp 2 and MacApp 3. In CPX there is a global command and event handler (Commander) which processes commands by executing their Do methods and processes events by passing them to a special event handler that it owns. Figure 3 shows some of the classes and methods important to the CPX command handling.

Figure 3. The classes, methods, and fields
that play important roles in command handling in Prograph CPX.
Note that Prograph’s approach contains ideas from
both the MacApp 2 and MacApp 3 algorithms.

Figure 4. The Click Behavior editor.
Note that this allows the programmer to, in effect,
custom design the hook method
for the processing of this mouse event.

There are no hook methods in CPX for returning the newly instantiated command objects to the framework. Instead, the commands are posted. Unlike MacApp 3, commands can post themselves. In addition, there is no need for hook methods like those in MacApp 3, since the Behavior mechanism in CPX provides a way for your code to get control when a user event like choosing a menu item or clicking in a view occurs. In fact, the Behavior editor can reduce the need for some of the code you would have to have written in a MacApp implementation, and in some simple cases, can even obviate the need for any code at all. Figure 4 shows the Click Behavior editor for a view. What this editor enables the programmer to do is, in effect, to custom design the hook method to be used in exactly this situation. As part of the specification of this behavior, you can have an instance of any class allocated, or have the value of any window item obtained, among many other things.

Figure 5. The basic command processing method in CPX.
(The comments have been added and the names of some of the locals changed
to make these clearer as static figures.)

In CPX, posting an ordinary command does not enter it into a list for later processing, but rather immediately causes the Commander to execute the command. There are special subclasses of Command, Deferred Task and Periodic Task, which will delay or repeat the execution of the command. Figure 5 shows some of the Prograph code from the ABC class library for command processing.

Periodic Task, a subclass of Command, is the mechanism for performing a recurring activity or processing during idle time. There is no use of Periodic Task in MiniQuadWorld+, but the Prograph implementation of the MacApp DemoDialogs sample program uses Periodic Tasks to refresh the view and target inspector windows. (CPX DemoDialogs was described in the March/April ‘94 issue of FrameWorks).

Unlike MacApp, Prograph class library itself doesn’t use commands very much. Features like printing, closing windows, and quitting the application, etc. for which MacApp has a specific TCommand subclass, CPX just uses its behavior mechanism to perform directly. For example, in MacApp 2, closing a window via the Close menu item is accomplished as follows: TWindow.DoMenuCommand is called by MacApp with the parameter cClose. This allocates a TCloseWindowCommand object, initializes it, and then returns it to MacApp. MacApp calls the command object’s DoIt method to tell the window’s main view to Close. This eventually causes the window, its document, etc. to close. Here is the MacApp 2 code:

TWindow.DoMenuCommand

FUNCTION TWindow.DoMenuCommand(
 aCmdNumber: CmdNumber): TCommand; OVERRIDE;
VAR
 aCloseWindowCommand: TCloseWindowCommand;
 oldObjectPerm:  BOOLEAN;
BEGIN
 DoMenuCommand := NIL;

 CASE aCmdNumber OF
 cClose:
 BEGIN
 oldObjectPerm := AllocateObjectsFromPerm(FALSE); 
 New(aCloseWindowCommand);
 IF AllocateObjectsFromPerm(oldObjectPerm) THEN;
 FailNil(aCloseWindowCommand);{ just in case }
 aCloseWindowCommand.ICloseWindowCommand(aCmdNumber,           
 SELF);
 DoMenuCommand := aCloseWindowCommand;
 END;
 OTHERWISE
 DoMenuCommand := INHERITED DoMenuCommand(aCmdNumber);
 END;
END;


TCloseWindowCommand.DoIt

PROCEDURE TCloseWindowCommand.DoIt;
BEGIN
 IF fView <> NIL THEN
 TWindow(fView).CloseByUser;
END;

The corresponding functionality in CPX is implemented with a behavior. Figure 6 shows the specification of this menu behavior, and the code that it calls. Since the MacApp TCloseWindowCommand is not an undoable command, there isn’t too much difference in the real functionality of these two approaches.

Figure 6. The implementation of the window closing functionality in Prograph CPX.
Note that this does not use a command object.

Implementing Some Command Subclasses

I implemented a very small sample app that contains three command classes. The app, MiniQuadWorld+, is a slight extension of the MiniQuadWorld app that I did years ago. This app merely displays five quadrilaterals and enables the user to select any number of them. The selected quadrilateral(s) can be rotated or removed. In addition, the interior color of any quad can be changed. Note that there is no capability for the entry of new quadrilaterals. This is basically what differentiates MiniQuadWorld from (full) QuadWorld. Figure 7 shows a screen dump of this app.

Figure 7. Screen dump of the MiniQuadWorld+ application. This application has three command subclasses that implement the user interactions with the quadrilaterals.

The three command classes in MiniQuadWorld+ are Rotate Quad Cmd, Clear Quad Cmd, and Recolor Quad Cmd. The rotation and clearing operations are accessed via a menu item to perform the desired operation on all the currently selected quads, and thus the associated commands are subclasses of Menu Behavior. Recoloring a quad is accomplished by option-clicking on the quad, and it not accessible via a menu. (Note that I am not implying that this is necessarily the best user interface, but rather that it demonstrates different ways in which commands might be instantiated.)

Because any number of quads can be selected and rotated and cleared, the only practical way to support undo for rotation is for each quadrilateral to store its old position. Storing this data in the command object itself would be cumbersome at best, and totally unmanageable at worst. It also turned out to simplify the implementation if each quadrilateral also recorded its selection state. Thus the Rotate Quad Cmd causes each selected quad to copy the current position values into the corresponding ‘old’ attributes, calculate the new position, and then cause a screen refresh. Undo just copies the old values back. Figure 8 shows the Do method for this class, and the method invoked by the menu behavior associated with the Rotate menu item.

The clear operation works by just removing the currently selected quads from the list of objects in the document, and its undo merely copies them back. The clear all quads operation is not implemented with a distinct TCommand subclass, but just selects all the quads and does a clear.

Recoloring a quad, since it is not a menu operation, works differently than all the other operations. The click method for the Quad Graphical View class checks to see if the option key is held down, and if so, allocates and posts an instance of Recolor Quad Cmd. The internals of the methods of that class are very similar to the other MiniQuadWorld+ command classes.

What Worked and What Didn’t

I was able to get every piece of functionality for MiniQuadWorld+ implemented and working correctly. The actions of rotating, clearing, or recoloring a quad are undoable, as is the clearing of all the quads. This isn’t too surprising given the limited features of this toy application, but it is still good to know. However, I did have to correct a significant bug in the CPX command processing to get the undo features of MiniQuadWorld+ to work the way they should.

Undo worked correctly as long as the user didn’t perform any action between the execution of the undoable command and the undo request. Any action. Scrolling the window, moving the window, and clicking in the window’s content region (among other things) all committed the previous command. This is an example of prematurely committing a command. (‘Committing’ a command is term from MacApp, not from CPX. It means that the user has just performed another undoable action, and since only single level undo is supported by MacApp, it is time to ‘throw away’ the last command object. Just before this is done, the command object is given one last chance to do any clean up processing. This last chance processing is implemented in TCommand.Commit. Then the framework disposes of the command object. CPX does not have the notion of committing a command, so it just ‘throws away’ the old command object at this time. (Since Prograph has garbage collection, throwing away the command just means letting go of any references to it.) Premature commitment of a command object is a bug that prematurely takes away from the user the ability to undo an action.

Figure 8. The code for instantiating, initializing, and performing
the Rotate Quad Cmd object.
This operation is initiated via a menu item and a CPX Menu Behavior
associated with that item invokes this code.

Figure 9. The correction to the Premature Command Commitment bug.
Rather than always executing a Window/Bring to Front,
the modified method first checks to see if the window is already the frontmost one.
If so (and this is often the case), then nothing is done.
This small fix eliminates most, but not all, of the premature commitments.

I have traced down this bug and implemented a new CPX section that corrects most, but not all, of the problem. The problem - at least insofar as I figured it out - was that the Window/Bring to Front method caused the last command to be committed and this method was being invoked MUCH too often. One portion of my fix (Figure 9) just checks to see if the window that is about to be brought to the front is already in front, and if it is, then the call to Window/Bring to Front is not made. Thus the last command is not committed, and everything works a little more as it should. This fix is in the Desktop class, so I have subclassed Desktop and overloaded the appropriate method (Desktop/Mouse Down). I also added a method to the Application subclass that causes this corrected Desktop subclass to be instantiated as the application’s Desktop instead of the normal one. Another part of my fix is a method to be placed into any movable window subclass. This Window method does the same sort of ‘Bring to Front, if necessary’ modification for the operation of moving the window.

I have packaged this patch in its own section so that I (and you) can easily add it to other applications until the next maintenance release of CPX by PI.

Both I and the PI Tech Support staff were surprised that such a bug as the premature command commitment discussed above had gone unreported until now - almost a year since CPX’s initial release. The only reason that we could think of for this was that CPX programmers were not putting undo support into their applications. Hopefully this section I have implemented and this article will encourage greater use of undo.

In addition, several other things were harder than expected. Having a visible indication that a quadrilateral was selected was tricky. This was not because it was hard to XOR small squares at the vertices of the quad, but rather because it was not easy to hook into the CPX drawing code in the correct way. Overriding the view or the window’s Draw method worked correctly for the initial draw of the window, but didn’t work for redraws. The solution I ended up using was to add code to the Quad/Draw method. Since a quad stores its own selection state, this was easy, and not too ugly a design.

Implementing the color changing was a little more difficult than necessary since there was no abstract superclass for commands initiated with the mouse rather than a menu item. What I wanted was something like the Menu Behavior class. I added a Mouse Behavior class and subclassed it for the Recolor Quad Cmd class.

Overall the impression that I got was that while it was not too difficult to do MacDraw-like user interfaces in CPX, this was not the design center for CPX. (Probably implementing database front ends was.) However, everything was doable.

References

[1] Schmucker, Kurt. Object Oriented Programming for the Macintosh, Hayden Book Company, 1986.

[2] Artman, Gerald. “More on Style in Prograph,” Visual News, April 1994, pp. 14-15.

[3] Schmucker, Kurt. “Toward a Prograph Coding Style,” Visual News, May 1994, pp. 16-17.

 
AAPL
$111.78
Apple Inc.
-0.87
MSFT
$47.66
Microsoft Corpora
+0.14
GOOG
$516.35
Google Inc.
+5.25

MacTech Search:
Community Search:

Software Updates via MacUpdate

CleanApp 5.0.0 Beta 5 - Application dein...
CleanApp is an application deinstaller and archiver.... Your hard drive gets fuller day by day, but do you know why? CleanApp 5 provides you with insights how to reclaim disk space. There are... Read more
Monolingual 1.6.2 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
NetShade 6.1 - Browse privately using an...
NetShade is an Internet security tool that conceals your IP address on the web. NetShade routes your Web connection through either a public anonymous proxy server, or one of NetShade's own dedicated... Read more
calibre 2.13 - Complete e-library manage...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more
Mellel 3.3.7 - Powerful word processor w...
Mellel is the leading word processor for OS X and has been widely considered the industry standard since its inception. Mellel focuses on writers and scholars for technical writing and multilingual... Read more
ScreenFlow 5.0.1 - Create screen recordi...
Save 10% with the exclusive MacUpdate coupon code: AFMacUpdate10 Buy now! ScreenFlow is powerful, easy-to-use screencasting software for the Mac. With ScreenFlow you can record the contents of your... Read more
Simon 4.0 - Monitor changes and crashes...
Simon monitors websites and alerts you of crashes and changes. Select pages to monitor, choose your alert options, and customize your settings. Simon does the rest. Keep a watchful eye on your... Read more
BBEdit 11.0.2 - Powerful text and HTML e...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
ExpanDrive 4.2.1 - Access cloud storage...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more
Adobe After Effects CC 2014 13.2 - Creat...
After Effects CC 2014 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous After Effects customer). After Effects CS6 is still available... Read more

Latest Forum Discussions

See All

Make your own Tribez Figures (and More)...
Make your own Tribez Figures (and More) with Toyze Posted by Jessica Fisher on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
So Many Holiday iOS Sales Oh My Goodness...
The holiday season is in full-swing, which means a whole lot of iOS apps and games are going on sale. A bunch already have, in fact. Naturally this means we’re putting together a hand-picked list of the best discounts and sales we can find in order... | Read more »
It’s Bird vs. Bird in the New PvP Mode f...
It’s Bird vs. Bird in the New PvP Mode for Angry Birds Epic Posted by Jessica Fisher on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Telltale Games and Mojang Announce Minec...
Telltale Games and Mojang Announce Minecraft: Story Mode – A Telltale Games Series Posted by Jessica Fisher on December 19th, 2014 [ permalink ] | Read more »
WarChest and Splash Damage Annouce Their...
WarChest and Splash Damage Annouce Their New Game: Tempo Posted by Jessica Fisher on December 19th, 2014 [ permalink ] WarChest Ltd and Splash Damage Ltd are teaming up again to work | Read more »
BulkyPix Celebrates its 6th Anniversary...
BulkyPix Celebrates its 6th Anniversary with a Bunch of Free Games Posted by Jessica Fisher on December 19th, 2014 [ permalink ] BulkyPix has | Read more »
Indulge in Japanese cuisine in Cooking F...
Indulge in Japanese cuisine in Cooking Fever’s new sushi-themed update Posted by Simon Reed on December 19th, 2014 [ permalink ] Lithuanian developer Nordcurrent has yet again updated its restaurant simulat | Read more »
Badland Daydream Level Pack Arrives to C...
Badland Daydream Level Pack Arrives to Celebrate 20 Million Downloads Posted by Ellis Spice on December 19th, 2014 [ permalink ] | Read more »
Far Cry 4, Assassin’s Creed Unity, Desti...
Far Cry 4, Assassin’s Creed Unity, Destiny, and Beyond – AppSpy Takes a Look at AAA Companion Apps Posted by Rob Rich on December 19th, 2014 [ permalink ] These day | Read more »
A Bunch of Halfbrick Games Are Going Fre...
A Bunch of Halfbrick Games Are Going Free for the Holidays Posted by Ellis Spice on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »

Price Scanner via MacPrices.net

The Apple Store offering free next-day shippi...
The Apple Store is now offering free next-day shipping on all in stock items if ordered before 12/23/14 at 10:00am PT. Local store pickup is also available within an hour of ordering for any in stock... Read more
It’s 1992 Again At Sony Pictures, Except For...
Techcrunch’s John Biggs interviewed a Sony Pictures Entertainment (SPE) employee, who quite understandably wished to remain anonymous, regarding post-hack conditions in SPE’s L.A office, explaining “... Read more
Holiday sales this weekend: MacBook Pros for...
 B&H Photo has new MacBook Pros on sale for up to $300 off MSRP as part of their Holiday pricing. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1699... Read more
Holiday sales this weekend: MacBook Airs for...
B&H Photo has 2014 MacBook Airs on sale for up to $120 off MSRP, for a limited time, for the Thanksgiving/Christmas Holiday shopping season. Shipping is free, and B&H charges NY sales tax... Read more
Holiday sales this weekend: iMacs for up to $...
B&H Photo has 21″ and 27″ iMacs on sale for up to $200 off MSRP including free shipping plus NY sales tax only. B&H will also include a free copy of Parallels Desktop software: - 21″ 1.4GHz... Read more
Holiday sales this weekend: Mac minis availab...
B&H Photo has new 2014 Mac minis on sale for up to $80 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 1.4GHz Mac mini: $459 $40 off MSRP - 2.6GHz Mac mini: $629 $70 off MSRP... Read more
Holiday sales this weekend: Mac Pros for up t...
B&H Photo has Mac Pros on sale for up to $500 off MSRP. Shipping is free, and B&H charges sales tax in NY only: - 3.7GHz 4-core Mac Pro: $2599, $400 off MSRP - 3.5GHz 6-core Mac Pro: $3499, $... Read more
Save up to $400 on MacBooks with Apple Certif...
The Apple Store has Apple Certified Refurbished 2014 MacBook Pros and MacBook Airs available for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and... Read more
Save up to $300 on Macs, $30 on iPads with Ap...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
iOS and Android OS Targeted by Man-in-the-Mid...
Cloud services security provider Akamai Technologies, Inc. has released, through the company’s Prolexic Security Engineering & Research Team (PLXsert), a new cybersecurity threat advisory. The... Read more

Jobs Board

*Apple* Store Leader Program (US) - Apple, I...
…Summary Learn and grow as you explore the art of leadership at the Apple Store. You'll master our retail business inside and out through training, hands-on experience, Read more
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.