TweetFollow Us on Twitter

PP Commanders
Volume Number:12
Issue Number:2
Column Tag:Getting Started

PowerPlant and Commanders

By Dave Mark, MacTech Magazine Regular Contributing Author

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

This month, we’re going to explore a brand new aspect of PowerPlant: the concept of commands, commanders, and the LCommander PowerPlant class. PowerPlant commands are similar to messages. You’ve already seen how messages are sent from a broadcaster (such as a button) to all listeners registered to listen to that broadcaster. The command model is slightly different.

Commands are associated with menus and keyDown events. To respond to menu selections and user keystrokes, you’ll need to create a class derived (at least in part) from the LCommander class. There are three key functions you’ll inherit and override from the LCommander base class.

• HandleKeyPress() - receives an EventRecord containing a character typed by the user.

• ObeyCommand() - receives a command number associated with a specific menu command. When we create this month’s project, you’ll see how to associate a command number with a specific menu item.

• FindCommandStatus() - gives your LCommander subclass a chance to update (i.e. enable, disable, check, uncheck, change item text) the status of the menu item associated with a specified command.

Basically, PowerPlant handles the administrative work of keeping track of which menu items need to be enabled, which pane should receive which event, etc. Every PowerPlant application has a chain of command. The chain (really a tree) starts with the LApplication object and flows downward through other objects that handle commands to the panes that will become the targets of the commands. Think of the current target as the application’s current focus. If a keystroke is entered, the corresponding keyDown event will be sent to the current target pane (perhaps a window, perhaps a textEdit pane within the window).

As you’ll see in this month’s program, you’ll have a little setup work to do, and then you’ll override the three LCommander functions described above. That’s pretty much it. Of course, as you get deeper into PowerPlant you’ll discover that there is much more you can do, but for now, concentrate on understanding the basics.

A Sneak Preview of BeepCommander

This month’s program is called BeepCommander. It features a single window type that responds to keyDowns by displaying the typed character in the window. Figure 1 shows a BeepCommander window.

Figure 1. A BeepCommander window.

BeepCommander also features a menu named Special with a single item named Beep. When you select Beep, your computer beeps (gasp!). The sneaky thing is, the Beep item is only enabled when the letter ‘x’ is typed. I know, I know, weird user interface. That’s fine. The point is to show the relationship between menus, keystrokes and the LPane and LCommander functions you’ll be overriding.

Let’s get started.

Create a New Project

The first thing you’ll need to do is create a new project, based on the PowerPlant stationery.

• Create a new folder called BeepCommander.

• Launch CodeWarrior and create a new project named BeepCommander.µ.

• In the project window, double-click on the file <PP Starter Resource>.rsrc. This will open the file in Constructor.

• In Constructor, do a Save As... and save the file in the BeepCommander folder as BeepCommander.rsrc.

(This last step tells Constructor to completely duplicate the file, and not just the resources it uses. This is definitely the right way to replace the stationery resource file.)

• Quit Constructor and return to CodeWarrior.

• Add the file BeepCommander.rsrc to the project.

• Delete the file <PP Starter Resource>.rsrc from the project.

• In the project window, double-click on the file <PP Starter Source>.cp.

• Select Save As... from the File menu and save the file as BeepCommander.cp.

Notice that the stationery file name changed from <PP Starter Resource>.rsrc to BeepCommander.cp in the project window. You might want to dog-ear this page and refer back to it the first few times you create your own PowerPlant projects. These first nine steps make a good starting point for all your new PowerPlant stationery-based projects.

Creating the Project Resources

Your next task is to add a new menu to the project and associate a command number with the menu’s item.

• Launch your favorite resource editor.

Be sure you install the appropriate resource editing templates for your resource editor. You’ll find the files PowerPlant Resorcerer TMPLs and PowerPlant ResEdit TMPLs buried in subfolders within the Metrowerks CodeWarrior folder. To install the Resorcerer templates, drag the file PowerPlant Resorcerer TMPLs into the folder Resorcerer® Templates. To install the ResEdit templates, duplicate ResEdit, then use ResEdit to edit the copy. Open the file PowerPlant ResEdit TMPLs and copy the 'TMPL' resources into your copy of ResEdit. Your copy now has the templates installed. As always, keep your original around in case things get screwed up.

• Select Open... from the File menu and open the file BeepCommander.rsrc.

• Create a new 'MENU' resource. Change its id to 131 (be sure it gets changed in both places if you are using ResEdit). Give the new menu a title of Special and create a single item called Beep. If you like, give Beep a command-key equivalent of AppleB.

• Create a 'Mcmd' resource, also with an id of 131. Add a single item with a command number of 1000.

The 'Mcmd' resource you just created associates a command number of 1000 with the Special menu’s Beep item.

Figure 2 shows the hex version of this resource in ResEdit in case you can’t get your 'Mcmd' resource template working or if you just want to check your handiwork.

Figure 2. The hex version of 'Mcmd' 131.

• Modify 'MBAR' 128, adding the new 'MENU' id (131) to the list of other 'MENU' ids already in the resource.

• Save your changes and quit your resource editor.

Constructor

Now we’ll use Constructor to create the views we’ll use in this program.

• Back in CodeWarrior, double-click on the file BeepCommander.rsrc to open the file in Constructor.

• In Constructor, delete the existing “<Replace Me>” view.

• Select New Resource from the Edit menu to create a new view.

• When the New Resource dialog appears, type Single Char Window in the textEdit field, be sure the popup menu is set to LWindow, then click OK.

• Close the new view window.

• Be sure the new view is highlighted in the master view list, then select Resource Info from the Edit menu.

• When the view info window appears, change the resource id to 1000.

• Close the view info window.

• Double-click on the view name in the master view list to reopen the view editing window.

This view represents our main window, the window that will be created when you select New from our application’s File menu. We’re now going to add a pane to the window that will be reflected in our source code by the class CSingleCharPane. Just as a heads up, CSingleCharPane will be partially derived from the LCommander class and will be the target for both menu selections from our new 'MENU' and for keystrokes. More on all this later.

• Drag an LPane from the palette into the center of the view editing window.

• Double-click on the LPane to open a pane info window.

• Set the Location coordinates according to those shown in Figure 3.

• Check all four of the Binding to Superview checkboxes, keeping the pane proportional to its enclosing window.

• Change the Pane ID to 2000.

• Change the Class ID to Cmdr.

This last step is extremely important. The Class ID is what ties this view resource to the CSingleCharPane class we’ll define when we get to the source code. By the way, just as Apple reserves all lower case resource types, Metrowerks reserves all lower case Class IDs (for example, 'abcd' is reserved, but 'Abcd' is just fine).

• Save your changes and quit Constructor.

Figure 3. The pane info window for our LPane.

Adding the Source Code

Your next step is to return to CodeWarrior and type in some new source code.

• Back in CodeWarrior, create a new source code file, save it under the name CSingleCharPane.cp.

• Type in the following source code:

#include <LPane.h>
#include <LCommander.h>
#include "CSingleCharPane.h"

CSingleCharPane *
CSingleCharPane::CreateSingleCharPaneStream(
 LStream *inStream )
{
 return( new CSingleCharPane( inStream ) );
}


CSingleCharPane::CSingleCharPane( LStream *inStream ) :
 LPane( inStream )
{
 mChar = 'x';
}
 

Boolean 
CSingleCharPane::HandleKeyPress(
 const EventRecord &inKeyEvent )
{
 mChar = inKeyEvent.message & charCodeMask;
 
 SetUpdateCommandStatus( true );
 Refresh();
 
 return true;
}


Boolean
CSingleCharPane::ObeyCommand( CommandT inCommand,
 void *ioParam )
{
 if ( inCommand == 1000 )
 {
 SysBeep( 20 );
 return true;
 }
 else
 return LCommander::ObeyCommand(inCommand, ioParam);
}


void
CSingleCharPane::FindCommandStatus( 
 CommandT inCommand,
 Boolean&outEnabled,
 Boolean&outUsesMark,
 Char16 &outMark,
 Str255 outName )
{
 if (inCommand == 1000)
 outEnabled = (mChar == 'x');
 else
 LCommander::FindCommandStatus(inCommand, outEnabled,
 outUsesMark, outMark, outName);
}


void
CSingleCharPane::DrawSelf()
{
 Rect   frameRect;
 short  x, y, frameWidth, frameHeight;
 const shortk  FontSize = 128;
 FontInfo myFontInfo;
 
 CalcLocalFrameRect( frameRect );
 
 frameWidth = frameRect.right - frameRect.left;
 frameHeight = frameRect.bottom - frameRect.top;
 
 TextSize( kFontSize );
 
 x = (frameWidth - CharWidth( mChar )) / 2
  + frameRect.left;
 
 GetFontInfo( &myFontInfo );
 y = frameRect.bottom - ((frameHeight - 
 myFontInfo.ascent + myFontInfo.descent) / 2);
 
 MoveTo( x, y );
 DrawChar( mChar );
}

Save your work, and add the file to the project.

Comments on SingleCharPane.cp

SingleCharPane.cp starts off with a creation function. We’ll pass that in when we register this new class by calling URegistrar::RegisterClass(). Notice that the creation routine actually creates the CSingleCharPane object. Get used to this way of doing things in PowerPlant.

Next comes the constructor. Notice that the constructor maps the input parameter to the LPane constructor. CSingleCharPane is derived from both LPane and LCommander. The data member mChar holds the last character typed. We initialize it to ‘x’, since that’s the magic character that enables the Beep item.

The function CSingleCharPane::HandleKeyPress() is inherited from the LCommander class and gets called in response to a keyDown event. The function returns true if the keystroke was handled correctly (in our case, we always return true). LCommander::SetUpdateCommandStatus(true) marks the menu bar as needing its status updated. LPane::Refresh() forces an update on the visible portion of the pane.

CSingleCharPane::ObeyCommand() is also inherited from LCommander and returns true if the command was obeyed. If we get command 1000 (that’s the command number of the Beep item), we’ll beep once and return true. Any other command causes a call to the inherited ObeyCommand(). This passes the command back up the chain to our commander. The LApplication class is the ultimate commander and has no supercommander. If the LApplication class can’t handle your command, you are out of luck!

CSingleCharPane::FindCommandStatus() is inherited from LCommander. It checks to see if the command sent to it is 1000 (the Beep item). If so, it sets the enable parameter depending on whether mChar is set to ‘x’. We could also have put a mark next to the Beep item or changed its name (try messing with these two: make the item name change to Beep followed by the current letter in the window, or add a checkmark next to the item when you type an ‘x’). If the command wasn’t a 1000, we’ll pass it back up the chain.

DrawSelf() is an LPane member function. DrawSelf() is paired with a member function named Draw(). Draw() gets called to set up the pane’s drawing environment in preparation for drawing (sort of like a call to SetPort()) and DrawSelf() is called to do the actual drawing. You might call an inherited Draw() method to prepare your derived pane for drawing, but you’ll override the DrawSelf() method to provide your own drawing method.

CSingleCharPane() calls CalcLocalFrameRect() to get our pane’s Rect. We’ll then set the font size to kFontSize, do some font calculations and draw the character in the window.

By the way, if you are trying to figure out the calling sequence for an overriding function, check out the function you are overriding. For example, when you are creating CSingleCharPane::ObeyCommand(), check out LCommander::ObeyCommand() or, even better, CPPStarterApp::ObeyCommand(). Also, get yourself a copy of Inside PowerPlant, which comes on your CodeWarrior CD and contains complete descriptions of all of these routines. You can also buy a printed copy of Inside PowerPlant directly from Metrowerks.

Adding the Include File CSingleCharPane.h

Next, we’ll create the include file CSingleCharPane.h that defines the CSingleCharPane class.

• Create a second source code file and save it as CSingleCharPane.h.

• Type in this source code:

#include <LPane.h>
#include <LCommander.h>


class CSingleCharPane : public LPane,
 public LCommander {
public:
 enum { class_ID = 'Cmdr' };
 
 static CSingleCharPane *CreateSingleCharPaneStream(
 LStream *inStream );
 
 CSingleCharPane( LStream *inStream );
 virtual Boolean HandleKeyPress(
 const EventRecord &inKeyEvent );
 virtual Boolean ObeyCommand( 
 CommandT inCommand, void *ioParam );
 virtual void    FindCommandStatus( 
 CommandT inCommand,
 Boolean&outEnabled,
 Boolean&outUsesMark,
 Char16 &outMark,
 Str255 outName );
 virtual void    DrawSelf();
 
protected:
 char   mChar;
};

• Save your typing and close the window.

The CSingleCharPane class is derived from both LPane and LCommander. The class definition starts off by creating the enumeration constant class_ID which has a value of 'Cmdr', the same value you typed into the LPane’s Class ID field in Constructor. Next comes all of the member function declarations and, finally, the declaration of the data member mChar.

Editing BeepCommander.cp

Your final bit of work is to add a few lines of code to BeepCommander.cp.

• Open the file BeepCommander.cp.

• Add these lines to ObeyCommand(), just after the call of LWindow::CreateWindow() and just before the call to theWindow->Show():

 CSingleCharPane *theCharPane =
 (CSingleCharPane *)theWindow->FindPaneByID( 2000 );
 theWindow->SetLatentSub( theCharPane );

• Add this line to top of the file at the end of the #include list:

#include "CSingleCharPane.h"

• Go to the top of the file and change the const window_Sample to have a value of 1000, like this:

const ResIDTwindow_Sample = 1000;  // EXAMPLE

• Finally, add this code to the constructor:

 URegistrar::RegisterClass( CSingleCharPane::class_ID,
 CSingleCharPane::CreateSingleCharPaneStream );

Till Next Month

Well, that’s about it for BeepCommander. Once all your code is in, run the darn thing. The window shown in Figure 1 will appear. Type some characters and watch the letters flash by. Notice that the Special menu is enabled only when you type the letter ‘x’. Why is the entire menu disabled and not just the Beep item? This is a feature, not a bug. PowerPlant disables a menu title when all of its items are disabled.

Next month, we’ll expand our horizons a bit more and explore yet another corner of PowerPlant. See you then...

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
Hopper Disassembler 5.14.1 - Binary disa...
Hopper Disassembler is a binary disassembler, decompiler, and debugger for 32- and 64-bit executables. It will let you disassemble any binary you want, and provide you all the information about its... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.