TweetFollow Us on Twitter

PP Documents
Volume Number:12
Issue Number:4
Column Tag:Getting Started

PowerPlant and Documents

By Dave Mark, MacTech Magazine Regular Contributing Author

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

Last month, we implemented a window containing a scrolling TextEdit view. Though you could type text in a window, there was no way of saving the text out as a file or of loading a text file into a text editing window. What’s missing here is the concept of a document. PowerPlant features a sophisticated set of document-handling classes that allow you to quickly tie a file to a window. Each file/window pairing is known as a document. Although PowerPlant does support a more complex model (multiple windows tied to a single file, for example), the most common document approach ties a single file to a single window, all controlled by the LSingleDoc class.

This month, we’re going to examine a sample application that ships with CodeWarrior. The application is called DocDemo, and it implements a simple TextEdit window that supports most standard document behaviour. That is, you can Save a document, Save As... under a new name, Open an existing document, and Print a document. DocDemo supports Apple events and is recordable. You can find DocDemo on the CodeWarrior CD. On CodeWarrior 8, it is in a folder called Document Demo.

My original goal for this month’s column was to add the LSingleDoc class to last month’s program, allowing you to save your text window as a file and open an existing file in a text window. But when I saw DocDemo, I changed my mind. DocDemo does everything I wanted to do, but also adds printing and great Apple event support. This is definitely a great learning program. Cool!

Getting Started with DocDemo

Before you go any further, you might want to find a copy of DocDemo on your CodeWarrior disk (or download it from whatever site you go to to pick up the Getting Started source code each month [such as - man]). Figure 1 shows the project window for the PowerPC version of DocDemo. Take a look at the files grouped under the name Application. The file CDocDemoApp.cp contains main() and the member functions that make up our main application class. CDocDemoApp is derived from LDocApplication, which is derived from LApplication. If you plan on building an application that supports multiple documents, CDocDemoApp.cp makes a great starting point.

(Remember, a class that starts with “L” belongs to PowerPlant. All the classes that you add to your PowerPlant programs will start with “C”.)

Figure 1. The DocDemoPPC.µ project window

Where CDocDemoApp.cp implements the application, the file CTextDoc.cp implements a single text-based document. CTextDoc is derived from LSingleDoc, which is derived from LDocument.

CDirtyText.cp implements the actual text stream, the text stored in memory that appears in one of the DocDemo windows. The word “dirty” refers to the state of a text stream, either changed since the last save (dirty) or not.

Later in the column we’ll step through each of these three source code files, pointing out the highlights. The remaining three files in the Application group are resource files. Notice that the Constructor resources are stored separately from the rest of the resources. As mentioned in a previous column, this is a good idea. When you double-click on the file DocDemo.rsrc, your favorite resource editor is launched (in this case, the creator code of DocDemo.rsrc is set to launch Resorcerer - feel free to change it to use ResEdit if that’s your preference). When you double-click on the file DocDemo.PPob, Constructor is launched.

Figure 2. The main window for DocDemo.PPob

Take some time to look through the resource files, especially the Constructor file. If you haven’t seen it yet, this would be an excellent time to check out Constructor 2.1, the version that shipped on CW8. It has a cool new look and a great new menu editor. Yup, Constructor now does menus! Figure 2 shows the main Constructor window for DocDemo.PPob. Very nice...

The main view of interest here is the one named “Text Window”. If you double-click on it, you’ll see something very similar to the scrolling text pane we created last month, with an LScroller enclosing an LTextEdit pane. Figure 3 shows the pane info window for the LTextEdit pane. Notice that the Pane ID is set to the four byte value 'Text' and that the Text ID checkbox is checked. When the Text ID checkbox is checked, the value in the Pane ID field is represented as a sequence of 4 characters (like a resource type) instead of as a long integer.

Notice also that the Class ID is set to the four byte value 'Dtxt'. This value will come into play when we register our classes in the source code. We’ll pass this value as a parameter to URegistrar::RegisterClass() in the CDocDemoApp constructor. You’ll see this in a bit, when we explore the project source code.

Figure 3. The LTextEdit pane info window for the pane

Running DocDemo

Take some time to put DocDemo through its paces. The important things to test are the ability to save and reopen text files. If you have AppleScript installed on your machine (and you should), run the Script Editor, click the Record button, then run DocDemo. While recording, create a new window, type some text, then save the document to disk. Go back to the Script Editor and click the Stop button. Figure 4 shows the results when I did this on my Mac. The line saying “make new document” was a result of selecting New from the File menu. The line following it was a result of doing a Save. Notice that the action of typing my text was not recorded. Once you’ve been through the code, see if you can figure out why this action wasn’t captured and how to make this happen.

Figure 4. A script recorded using Script Editor
while running DocDemoPPC

Here’s another interesting thing to try. You may experience an unrecoverable crash with this one, so be sure you save any open docs first! In DocDemo, open a new window, type some text, then save the document on your hard drive. Without closing the window, select Open from the File menu. Select the file you just saved (it’s already open, right?) from the SFGetFile list, then sit back and watch some exception handling kick in. Remember that option-Apple-escape forces a quit; you might end up using it. You might want to repeat this experiment with the debugger turned on.

OK, enough play. Let’s check out the source code.


You’ll notice a strong similarity between CDocDemoApp and last month’s PPTextEdit.cp file. While PPTextEdit’s application class, CPPStarterApp, was derived from LApplication, CDocDemoApp is derived from LDocApplication (LDocApplication is derived from LApplication). Here are some important things to look at as you go through the source in CDocDemoApp.cp:

• CDocDemoApp overrides OpenDocument(), MakeNewDocument(), ChooseDocument(), ObeyCommand(), and FindCommandStatus(). ObeyCommand() and FindCommandStatus() should be familiar to you from previous columns. In DocDemo, they don’t do much, since we haven’t added any commands specific to DocDemo.

• OpenDocument() gets called on an 'odoc' Apple event and opens the file specified in the incoming FSSpec. In a truly recordable application, OpenDocument() should never be called directly. When you want to do an open, you should post an 'odoc' event, which will cause OpenDocument() to get called. Remember, Apple events are what get recorded. Without the Apple event, the process of opening a document won’t be recorded. To post an 'odoc' Apple event, call LDocApplication::SendAEOpenDoc().

• MakeNewDocument() gets called in response to a kAECreateElement Apple event. When you select New fom the File menu, PowerPlant sends itself a kAECreateElement Apple event. Again, this is vital if you want your app to be recordable. To see this in action, take a look in CDocDemoApp::ObeyCommand(). Notice that cmd_New is not handled and that this causes a call of LDocApplication::ObeyCommand(). LDocApplication::ObeyCommand() sends the kAECreateElement Apple event in response to cmd_New. MakeNewDocument() uses new to create a new CTextDoc.

• Take a look at the ChooseDocument() source code:

 StandardFileReply macFileReply;
 SFTypeList typeList;
 typeList[0] = 'TEXT';
 ::StandardGetFile(nil, 1, typeList, &macFileReply);
 if (macFileReply.sfGood) {

There are a couple of interesting points here. First, notice that ChooseDocument() calls OpenDocument() directly. This action will now not be recordable (try it). Instead, ChooseDocument should pass macFileReply.sfFile to LDocApplication::SendAEOpenDoc().

UDesktop::Deactivate() calls Deactivate() for every window object in your app. This is needed since StandardGetFile() eats all the events as soon as it is called and your application windows never get a chance to get deactivated. If you don’t call UDesktop::Deactivate(), then when the StandardGetFile() dialog appears, your previously frontmost window will still appear in its active state (the title bar will still have stripes, for example). This is purely for aesthetics.

UDesktop::Activate() calls FrontWindow() and calls that window’s Activate(), returning things to the way they were before the call to UDesktop::Deactivate().

Note: If you have floating windows in your application, replace the file UDesktop.cp in your project window with UFloatingDesktop.cp. UFloatingDesktop.cp uses a slightly different mechanism for activate/deactivate that takes floating windows into account. This file is a little bigger and causes your built app to be a little larger, so don’t make the switch unless you use floating windows.

Take a look at the call of ::StandardGetFile() in ChooseDocument(). The two colons before the function name tell the compiler that the function is a global function. By convention, we always put two colons in front of a direct Toolbox call; this helps us discriminate between Toolbox and member function calls.

• ObeyCommand() and FindCommandStatus() don’t do much here. You’ll want to add stuff to these functions as you add commands and menus to your own applications.

• Take a look at the other member functions in LDocApplication (the ones we didn’t override). They are mostly there to handle Apple events and printing, and are definitely worth reviewing, especially if you are trying to learn how to work with Apple events.


CTextDoc is derived from LSingleDoc which is derived from LDocument. CTextDoc implements a single DocDemo document. Here are the highlights from the source code file:

• CTextDoc overrides IsModified(), DoAESave(), DoSave(), DoRevert(), and DoPrint().

• Take a look at the function CDocDemoApp::Open-Document():

 FSSpec *inMacFSSpec)
 CTextDoc *theDoc = new CTextDoc(this, inMacFSSpec);

Notice that this code causes the CTextDoc constructor to be called. The CTextDoc constructor calls CreateWindow() to create a new window, passing it the 'PPob' resource ID 200 as a parameter. Here’s the constructor:

 LCommander *inSuper,
 FSSpec *inFileSpec)
 : LSingleDoc(inSuper)
 // Create window for our document
 mWindow = LWindow::CreateWindow(WIND_TextDoc, this);
 // Specify that the text view should
 // be the Target when the Window
 // is activated
 mTextView = (CDirtyText*) mWindow->FindPaneByID('Text');
 if (inFileSpec == nil) {
 NameNewDoc();   // Set name of untitled window
 } else {
 OpenFile(*inFileSpec);   // Display contents of file in window

The call to FindPaneByID() returns a pointer to the LTextEdit pane object. The call to SetLatentSub() tells PowerPlant that the LTextEdit pane should be the target when the window is activated. Without this call, the text edit field would not become active when the window was activated, and the text insertion cursor would not flash (or even appear) until you clicked on the text edit pane. If you go back to last month’s example, you’ll see that that is exactly what happened. Take a few minutes, open up last month’s program, and see if you can add the code that makes the text cursor blink as soon as a new window is created.

• NameNewDoc() makes use of a pair of strings to name the new document “Untitled” or “Untitled x”. If there is no window named “Untitled”, NameNewDoc() makes that the new window name. If there already is a window named “Untitled”, NameNewDoc() looks for a window named “Untitled 1”, then “Untitled 2”, etc. As soon as it finds an open slot, that becomes the name of the new window.

Here’s the code:

 // Start with the default name (“untitled”)
 Str255 name;
 ::GetIndString(name, STRx_Untitled, 1);
 long num = 0;
 while (UWindows::FindNamedWindow(name) != nil) {
 // An existing window has the current name
 // Increment counter and try again

 ::GetIndString(name, STRx_Untitled, 2);
 Str15  numStr;
 ::NumToString(num, numStr);
 LString::AppendPStr(name, numStr);

The first call to ::GetIndString() returns the string “Untitled”. The second call returns the string “Untitled ” (note the space at the end of the string).

The call to mWindow->SetDescriptor() sets the window’s title. Don’t be fooled. SetDescriptor() has nothing to do with Apple event descriptors. Greg used the function name SetDescriptor() any time you were setting the title of an object to a value.

• Here’s the code to CTextDoc::OpenFile():

 FSSpec &inFileSpec)
 Try_ {
 mFile = new LFile(inFileSpec);
 Handle textH = mFile->ReadDataFork();
 mIsSpecified = true;
 Catch_(inErr) {
 delete this;
 } EndCatch_

Try_ is a macro Greg wrote to simulate exception handling before CodeWarrior supported exception handling. Now that exception handling is supported, Try_ is just defined as try and Catch_ is just defined as catch.

You will definitely want to spend some time curled up with a good book or paper on exception handling. Basically, here’s how this works. The try keyword tells the compiler to execute the block of code that follows the try. If the function throw() is called anywhere within that block (assuming there are no nested trys within the block), control is immediately transferred to the try’s matching catch block. The idea is, you can be way down in some code, encounter an error, and you jump out to the catch block attached to the code you are trying. The call to throw() is called, throwing an exception, and the catch block catches the exception. If the try code all runs without throwing an exception, the catch block is never entered.

By the way, the data member mIsSpecified indicates whether an existing file is tied to this document. If it isn‘t, and we do a Save, we need to do a StandardPutFile() to create a new file.

• IsModified() tells you whether the document is dirty (if you’ve made any changes to it since the last save):

 mIsModified = mTextView->IsDirty();
 return mIsModified;

mIsModified indicates whether the document is dirty. Note that in this case, whenever the pane is dirty, the document will be dirty. But what if we had two text panes, both stored in the same document? mIsModified would be based on either of the panes being dirty.

• DoAESave() gets called in response to a kAESave Apple event:

 FSSpec &inFileSpec,
 OSType inFileType)
 delete mFile;   // Kill existing file
 mFile = new LFile(inFileSpec);  // Make new file object
 OSType fileType = 'TEXT';// Find proper file type
 if (inFileType != fileType_Default) {
 fileType = inFileType;
    // Make new file on disk
 mFile->CreateNewDataFile(Creator_DemoDoc, fileType, 0);
 DoSave();// Write out data
    // Change window name
 mIsSpecified = true;// Document now has a specified file

DoAESave() uses a pretty simple file-saving strategy. It deletes the existing file, then creates a brand new file and writes the text out to it. This strategy isn’t very good if your computer happens to crash between deleting the file and writing out the new contents. In that case, you lose everything. A better strategy is to create the new file first, then delete the old one. There is a tech note somewhere that tells you the exactly right (i.e., official thought police) way to do this.

• DoSave() is a utility routine that actually copies the text out to an existing file.

 // Get text and write to file
 Handle textH = mTextView->GetTextHandle();
 StHandleLocker  theLock(textH);
 mFile->WriteDataFork(*textH, GetHandleSize(textH));
 mTextView->SetDirty(false);// Saving makes doc un-dirty

• DoRevert() reloads the text from the file into the text pane and refreshes mTextView:

 Handle textH = mFile->ReadDataFork();

• DoPrint() does printing. We’ll talk about that in a future column:

 LPrintout*thePrintout =
 LPlaceHolder  *textPlace = (LPlaceHolder*)
 textPlace->InstallOccupant(mTextView, atNone);
 delete thePrintout;


CDirtyText is derived from LTextEdit which is derived from LView. It is basically a version of LTextEdit that keeps track of whether it is dirty or not.

• CDirtyText overrides SetTextPtr() and UserChangedText().

• CDirtyText::CDirtyText() sets its dirty flag to false.

• CreateDirtyTextStream() is passed as a parameter to URegistrar::RegisterClass() (in the CDocDemoApp constructor) and is what allows us to create a CDirtyText object from a 'PPob':

 return (new CDirtyText(inStream));

• SetTextPtr() takes a pointer to a block of text and a length parameter and connects that block of text to this LTextEdit object:

 Ptr    inTextP,
 Int32  inTextLen)
 LTextEdit::SetTextPtr(inTextP, inTextLen);
 mIsDirty = false;

• UserChangedText() gets called whenever an action takes place on the LTextEdit view. If something has happened, if the pane is not already dirty, we have to change the menus to reflect the dirty status and flip the dirty flag. If the view is already dirty, we can’t make it any dirtier:

 if (!mIsDirty) {
 mIsDirty = true;

• IsDirty() just returns the status of the dirty flag.

• SetDirty() sets the dirty flag.

Till Next Month...

DocDemo is one of the most interesting PowerPlant examples I’ve seen. It is incredibly rich without being too difficult to understand. There are a bunch of ways you can extend this app, so take some time and start playing. Try adding a few menus to the DocDemo. Use Constructor to change the word-wrapping of the LTextEdit field. Try to change the font, style, and color of the text displayed in each document. I’ll see you next month...


Community Search:
MacTech Search:

Software Updates via MacUpdate

Apple Safari 10.0.1 - Apple's Web b...
Note: The direct download link is currently unavailable. It is available in the OS X 10.11.6 release, as well as in the Apple Security Updates. Apple Safari is Apple's web browser that comes with OS... Read more
Apple macOS Sierra 10.12.1 - The latest...
With Apple macOS Sierra, Siri makes its debut on Mac, with new features designed just for the desktop. Your Mac works with iCloud and your Apple devices in smart new ways, and intelligent... Read more
Apple iOS 10.1 - The latest version of A...
iOS 10 is the biggest release of iOS ever. A massive update to Messages brings the power of the App Store to your conversations and makes messaging more personal than ever. Find your route with... Read more
Hazel 4.0.7 - Create rules for organizin...
Hazel is your personal housekeeper, organizing and cleaning folders based on rules you define. Hazel can also manage your trash and uninstall your applications. Organize your files using a familiar... Read more
Opera 40.0.2308.90 - High-performance We...
Opera is a fast and secure browser trusted by millions of users. With the intuitive interface, Speed Dial and visual bookmarks for organizing favorite sites, news feature with fresh, relevant content... Read more
BetterTouchTool 1.93 - Customize Multi-T...
BetterTouchTool adds many new, fully customizable gestures to the Magic Mouse, Multi-Touch MacBook trackpad, and Magic Trackpad. These gestures are customizable: Magic Mouse: Pinch in / out (zoom... Read more
Backblaze - Online backup serv...
Backblaze is an online backup service designed from the ground-up for the Mac. With unlimited storage available for $5 per month, as well as a free 15-day trial, peace of mind is within reach with... Read more
Postbox 5.0.5 - Powerful and flexible em...
Postbox is a new email application that helps you organize your work life and get stuff done. It has all the elegance and simplicity of Apple Mail, but with more power and flexibility to manage even... Read more
Coda 2.5.19 - One-window Web development...
Coda is a powerful Web editor that puts everything in one place. An editor. Terminal. CSS. Files. With Coda 2, we went beyond expectations. With loads of new, much-requested features, a few surprises... Read more
Toast Titanium 15.1 - $99.99
Roxio Toast 15 Titanium, the leading DVD burner for Mac, makes burning even better, adding Roxio Secure Burn to protect your files on disc and USB in Mac- or Windows-compatible formats. Get more... Read more

Latest Forum Discussions

See All

WitchSpring2 (Games)
WitchSpring2 1.27 Device: iOS Universal Category: Games Price: $3.99, Version: 1.27 (iTunes) Description: This is the story of Luna, the Moonlight Witch as she sets out into the world. This is a sequel to Witch Spring. Witch Spring 2... | Read more »
Best Fiends Forever Guide: How to collec...
The fiendship in Seriously's hit Best Fiends has been upgraded this time around in Best Fiends Forever. It’s a fast-paced clicker with lots of color and style--kind of reminiscent of a ‘90s animal mascot game like Crash Bandicoot. The game... | Read more »
5 apps for the budding mixologist
Creating your own cocktails is something of an art form, requiring a knack for unique tastes and devising interesting combinations. It's easy to get started right in your own kitchen, though, even if you're a complete beginner. Try using one of... | Read more »
5 mobile strategy games to try when you...
Strategy enthusiasts everywhere are celebrating the release of Civilization VI this week, and so far everyone seems pretty satisfied with the first full release in the series since 2010. The series has always been about ultra-addictive gameplay... | Read more »
Popclaire talk to us about why The Virus...
Humanity has succumbed to a virus that’s spread throughout the world. Now the dead have risen with a hunger for human flesh, and all that remain are a few survivors. One of those survivors has just called you for help. That’s the plot in POPCLAIRE’... | Read more »
Oceans & Empires preview build sets...
Hugely ambitious sea battler Oceans & Empires is available to play in preview form now on Google Play - but download it quickly, as it’s setting sail away in just a few days. [Read more] | Read more »
Rusty Lake: Roots (Games)
Rusty Lake: Roots 1.1.4 Device: iOS Universal Category: Games Price: $2.99, Version: 1.1.4 (iTunes) Description: James Vanderboom's life drastically changes when he plants a special seed in the garden of the house he has inherited.... | Read more »
Flippy Bottle Extreme! and 3 other physi...
Flippy Bottle Extreme! takes on the bottle flipping craze with a bunch of increasingly tricky physics platforming puzzles. It's difficult and highly frustrating, but also addictive. When you begin to master the game, the sense of achievement is... | Read more »
Plants vs. Zombies Heroes guide: How to...
Plants vs. Zombies Heroes surprised us all, presenting a deep deck building experience. It's a great CCG that stands up well to the competition. There are a lot of CCGs vying for players' attention at the moment, but PvZ Heroes is definitely one... | Read more »
Arcane Online takes Online RPG’s to anot...
If you think that you need a desktop to enjoy high quality MMO gaming then Arcane Online hopes to prove you emphatically wrong. An epic fantasy Online RPG set in the land of Eldine, Arcane Online offers an abundance of features and content that... | Read more »

Price Scanner via

Apple’s Thursday “Hello Again” Event A Largel...
KGI Securities analyst Ming-Chi Kuo, who has a strong record of Apple hardware prediction accuracy, forecasts in a new note to investors released late last week that a long-overdue redo of the... Read more
12-inch Retina MacBooks on sale for $100 off...
Amazon has 2016 12″ Apple Retina MacBooks on sale for $100 off MSRP. Shipping is free: - 12″ 1.1GHz Silver Retina MacBook: $1199.99 $100 off MSRP - 12″ 1.1GHz Gold Retina MacBook: $1199.99 $100 off... Read more
Save up to $600 with Apple refurbished Mac Pr...
Apple has Certified Refurbished Mac Pros available for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The following... Read more
PixelStyle Inexpensive Photo Editor For Mac W...
PixelStyle is an all-in-one Mac Photo Editor with a huge range of high-end filters including lighting, blurs, distortions, tilt-shift, shadows, glows and so forth. PixelStyle Photo Editor for Mac... Read more
13-inch MacBook Airs on sale for $100-$140 of...
B&H has 13″ MacBook Airs on sale for $100-$140 off MSRP for a limited time. Shipping is free, and B&H charges NY sales tax only: - 13″ 1.6GHz/128GB MacBook Air (sku MMGF2LL/A): $899 $100 off... Read more
2.8GHz Mac mini available for $988, includes...
Adorama has the 2.8GHz Mac mini available for $988, $11 off MSRP, including a free copy of Apple’s 3-Year AppleCare Protection Plan. Shipping is free, and Adorama charges sales tax in NY & NJ... Read more
21-inch 3.1GHz 4K on sale for $1379, $120 off...
Adorama has the 21″ 3.1GHz 4K iMac on sale $1379.99. Shipping is free, and Adorama charges NY & NJ sales tax only. Their price is $120 off MSRP. To purchase an iMac at this price, you must first... Read more
Check Apple prices on any device with the iTr...
MacPrices is proud to offer readers a free iOS app (iPhones, iPads, & iPod touch) and Android app (Google Play and Amazon App Store) called iTracx, which allows you to glance at today’s lowest... Read more
Apple, Samsung, Lead J.D. Power Smartphone Sa...
Customer satisfaction is much higher among smartphone owners currently subscribing to full-service wireless carriers, compared with those purchasing service through a non-contract carrier, according... Read more
Select 9-inch Apple WiFi iPad Pros on sale fo...
B&H Photo has select 9.7″ Apple WiFi iPad Pros on sale for up to $50 off MSRP, each including free shipping. B&H charges sales tax in NY only: - 9″ Space Gray 256GB WiFi iPad Pro: $799 $0 off... Read more

Jobs Board

*Apple* Retail - Multiple Positions- Nashua,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Retail - Multiple Positions- Napervi...
Job Description:SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Security Data Analyst - *Apple* Information...
…data sources need to be collected to allow Information Security to better protect Apple employees and customers from a wide range of threats.Act as the subject Read more
*Apple* Retail - Multiple Positions (Multi-L...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Retail - Multiple Positions- New Yor...
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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.