TweetFollow Us on Twitter

Sprocket Menus 4
Volume Number:11
Issue Number:8
Column Tag:Getting Started

Sprocket Menus, Part 4

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 added code to our SprocketPicText project to implement the Style and most of the Size submenus that appear underneath the Text menu when a TTextWindow is the frontmost window. This month, we’re going to finish up the Size menu by implementing the Other... item. We’ll also add code to implement the Font submenu. Finally, we’ll add the code to the TPictureWindow to implement the two items in the Picture window that appears whenever a TPictureWindow is the frontmost window.


We’ll start off by adding a single DLOG resource and its associated DITL resource to SprocketStarter.rsrc. The two resources will implement a dialog that prompts the user to type in a new font size. The dialog will be brought up when the user selects Other... from the Size menu.

• Start by duplicating last month’s SprocketStarter folder (be sure you remove objects first if you care about disk space).

Don’t duplicate the Sprocket folder, since it hasn’t changed from last month. Last month’s Sprocket-Starter folder was named “SprocketPicText.04/25/95”. Name the new copy “SprocketPicText.05/31/95”.

Open up your new Sprocket-Starter folder and launch either the 68K or PowerMac SprocketStarter project. When your project window appears, double-click on the file named SprocketStarter.rsrc to launch your favorite resource editor.

• Create a new DLOG with a resource ID of 1000, a top of 71, left of 97, bottom of 146, and a right of 363. Be sure you select the modal dialog window type.

• Create a DITL with a resource ID of 1000.

• Create a pushbutton (item#1) with the text OK, a top of 42, left of 184, bottom of 62, and a right of 253.

• Create a pushbutton (item#2) with the text Cancel, a top of 42, left of 99, bottom of 62, and a right of 168.

• Create a static text item (item#3) with the text Font size:, a top of 13, left of 13, bottom of 29, and a right of 81.

• Create an editable text item (item#4) with no text, a top of 13, left of 91, bottom of 29, and a right of 250.

Figure 1 shows the finished dialog, as displayed by Resorcerer.

Figure 1. The DLOG and DITL resources, as displayed by Resorcerer.


Quit your resource editor, saving your changes, and return to CodeWarrior. Now open the file TextWindow.h and make these changes:

• Add these lines to the top of the file, just before the enum:

#include <Fonts.h>

const longkCancelButtonPressed = 0L;
const short iNumberEditTextField = 4;
const short kGetNumberDialogResID = 1000;

• Add these member function declarations to the TTextWindow class:

 virtual long    DoNumberDialog( void );
 virtual void    SetOtherMenuItemString( void );
 virtual void    PascalStringCat( Str255 dest, Str255 source );
 virtual void    AdjustFontMenu( void );
 virtual Boolean DoMenuSelection( short menu, short item );


Close TextWindow.h and open the file TextWindow.cp. Make these changes:

• Add to the file the member function


Here’s the source code:

TTextWindow::DoNumberDialog( void )
 BooleandialogDone = false;
 Str255 text;
 Handle itemHandle;
 short  itemHit, itemType;
 Rect   itemRect;
 long   returnValue;
 dialog = GetNewDialog( kGetNumberDialogResID, NULL, 
 (WindowPtr)-1L );
 if ( dialog == NULL )
 return kCancelButtonPressed;
 SetDialogDefaultItem( dialog, ok );
 SetDialogCancelItem( dialog, cancel );
 NumToString( (long)fCurrentFontSize, text );
 GetDialogItem( dialog, iNumberEditTextField, &itemType,
 &itemHandle, &itemRect );
 SetDialogItemText( itemHandle, text );
 SelectDialogItemText( dialog, iNumberEditTextField, 0, 32767 );
 ShowWindow( dialog );
 ModalDialog( NULL, &itemHit );
 if ( itemHit == ok )
 GetDialogItem( dialog, iNumberEditTextField, &itemType,
 &itemHandle, &itemRect );
 GetDialogItemText( itemHandle, text );
 StringToNum( text, &returnValue );
 if ( (returnValue < kMinimumFontSize) ||
 (returnValue > kMaximumFontSize) )
 SysBeep( 20 );
 SelectDialogItemText( dialog, iNumberEditTextField,
  0, 32767 );
 itemHit = iNumberEditTextField;
 dialogDone = true;
 else if ( itemHit == cancel )
 returnValue = kCancelButtonPressed;
 dialogDone = true;
 } while ( ! dialogDone );
 DisposeDialog( dialog );
 return returnValue;

This function implements the dialog box whose resources you created earlier. The dialog allows the reader to enter a new font size for the frontmost text window. The user must enter a size between kMinimumFontSize and kMaximumFontSize, otherwise we’ll beep and highlight the editable text field.

We’ll start off by converting the current text size, stored in the data member fCurrentFontSize, into a Str255 and we’ll place the Str255 version of the number in the dialog’s editable text field. We’ll then highlight the text field so if the user wants to type a new value, they don’t have to select the text first to replace it.

Inside the dialog loop, if the user presses the OK button, we’ll convert the text field to a long, then check to be sure it’s in range. If so, we’ll set dialogDone to true so we drop out of the loop.

If they hit the Cancel button, we’ll set the return value to kCancelButtonPressed, which has been pre-defined as 0L, which we know won’t be a legal font size.

Finally, once we drop out of the loop, we’ll dispose of the dialog and return returnValue.

• Add to the file the member function


Here’s the source code:

TTextWindow::PascalStringCat( Str255 dest, Str255 source )
 unsigned char i, destStringLength, sourceStringLength;
 destStringLength = dest[0];
 sourceStringLength = source[0];
 if ( sourceStringLength <= 0 )
 for ( i=1; i<=sourceStringLength; i++ )
 dest[i+destStringLength] = source[i];
 dest[0] += sourceStringLength;

Much like the function strcat(), this function appends the source pascal string on to the end of thepascal string already in dest. The length byte from source is deleted and the length byte of dest is incremented to reflect its new length.

This function is called by SetOtherMenuItemString() which we’ll add next.

• Add to the file the member function

TTextWindow::SetOtherMenuItemString() .

Here’s the source code:

TTextWindow::SetOtherMenuItemString( void )
 Str255 menuItemStr = "\pOther (";
 Str255 numberStr;
 NumToString( (long)fCurrentFontSize, numberStr );
 PascalStringCat( menuItemStr, numberStr );
 PascalStringCat( menuItemStr, "\p)..." );
 gMenuBar->SetItemString( cFontSizeOther, menuItemStr );

This function changes the Other... item in the Size menu to reflect the current text size. For example, if the current size is 37, the menu item should read Other (37).... Note that the Size menu we’ve implemented here is not my invention. It comes from the pages of Inside Macintosh and represents the standard you should use in your own applications.

SetOtherMenuItemString() starts off by defining a Str255 named menuItemStr with the text “Other (”. We’ll then convert the current size to a pascal string and append it to menuItemStr. Finally, we’ll append the pascal string “)...” to menuItemStr then call the TMenuBar member function SetItemString() to change the item associated with the command cFontSizeOther to menuItemStr.

• Add a call of SetOtherMenuItemString() to the end of the member function AdjustSizeMenu(). AdjustSizeMenu() gets called when a mousedown occurs in the menu bar.

• Add to the file the member function


Here’s the source code:

TTextWindow::DoMenuSelection( short menu, short item )
 Str255 itemString;
 short  fontNumber;
 if ( menu == mTextFont )
 GetMenuItemText( fgFontSubMenu, item, itemString );
 GetFNum( itemString, &fontNumber );
 SetPort( fWindow );
 TextFont( fontNumber );
 InvalRect( &fWindow->portRect );
 return true;
 return false;

DoMenuSelection() gets called before any of the command dispatching functions, giving you a chance to handle menus that contain unregistered items. Since there is no way to construct a CMNU resource for the Font menu (how would we assign command numbers when we don’t know how many or which fonts are installed?), we’ll handle selections from the Font menu in this function.

Before you read on, take a look at the function this function overrides, TWindow::DoMenuSelection(). Note that it simply returns false. If DoMenuSelection() returns false, Sprocket converts the menu selection to a command number and handles it that way. If DoMenuSelection() returns true, Sprocket assumes the menu selection has been processed and does nothing more.

DoMenuSelection() first checks to be sure the selection was from the Font menu. If so, it converts the selected item to a font number, then calls TextFont() to set the font for the associated fWindow, forces a redraw, and returns true.

Next, we’re going to make some changes to the function DoMenuCommand(), our menu command dispatcher that gets called if DoMenuSelection() returns false.

• Add a declaration of the variable newSize at the top of TTextWindow::DoMenuCommand():

 long newSize;

• Still in TTextWindow::DoMenuCommand(), edit the cFontSizeOther case in the switch statement to read:

 case cFontSizeOther:
 newSize = DoNumberDialog();
 if ( newSize != kCancelButtonPressed )
 SetNewTextSize( newSize );
 return true;

This case gets executed when Other (xx)... is selected from the Size menu. We’ll start by calling DoNumberDialog() to prompt the user for a new size. If a new size was entered, we’ll call SetNewTextSize() to set the new size.

Now we need to add the code that places the check mark next to the current font in the Font menu.

• Add a call of the function AdjustFontMenu() to the member function TTextWindow::AdjustMenusBeforeMenuSelection(). Here’s the new version of TTextWindow::AdjustMenusBeforeMenuSelection():

TTextWindow::AdjustMenusBeforeMenuSelection( void )

• Add the member function TTextWindow::AdjustFontMenu() to the file. Here’s the source code:

TTextWindow::AdjustFontMenu( void )
 short  fontNumber, numFonts, i;
 Str255 fontName, itemName;
 fontNumber = fWindow->txFont;
 GetFontName( fontNumber, fontName );
 numFonts = CountMItems( fgFontSubMenu );
 for ( i=1; i<=numFonts; i++ )
 GetMenuItemText( fgFontSubMenu, i, itemName );
 if ( EqualString( itemName, fontName, true, true ) )
 CheckItem( fgFontSubMenu, i, true);
 CheckItem( fgFontSubMenu, i, false);

AdjustFontMenu() turns the current font family id into its name. Next, CountMItems() is called to return the number of items in the Font menu. The for loop steps through each of the items, checking to see if the item is equal to the font name. If so, the item gets a check mark. If not, the item does not get a check mark.


Our final task is to add the code that implements the two items in the Picture menu, Centered and Upper Left. Centered causes the picture to be drawn centered in the picture window and Upper Left causes the picture to be pressed against the upper-left corner of the window.

• Close TextWindow.cp and open the file PictureWindow.h.

• Add the declaration of the data member fIsPictureCentered to the TPictureWindow class declaration:


• Add the declarations of the member functions DoMenuCommand() and AdjustMenusBeforeMenuSelection() to the TPictureWindow class declaration:

 virtual Boolean DoMenuCommand( unsigned long menuCommand );
 virtual void    AdjustMenusBeforeMenuSelection( void );


Close PictureWindow.h and open the file PictureWindow.cp.

• Add the code that initializes fIsPictureCentered to the TPictureWindow constructor:

 fIsPictureCentered = true;

• In the function TPictureWindow::Draw(), edit the last two lines of code so Draw() looks like this:

 Rect   r;
 r = fWindow->portRect;
 EraseRect( &r );
 if ( fDraggedPicHandle == nil )
 pic = this->LoadDefaultPicture();
 pic = fDraggedPicHandle;

 if ( fIsPictureCentered )
 this->CenterPict( pic, &r );
 r = (**pic).picFrame;
 OffsetRect( &r, - r.left, - );
 DrawPicture( pic, &r );

Basically, we’ve made Draw() depend on fIsPictureCentered.

• Add the member function TPictureWindow::DoMenuCommand() to the file. Here’s the source code:

TPictureWindow::DoMenuCommand( unsigned long menuCommand )
 switch ( menuCommand )
 case cCentered:
 fIsPictureCentered = true;
 SetPort( fWindow );
 InvalRect( &fWindow->portRect );
 return true;
 case cUpperLeft:
 fIsPictureCentered = false;
 SetPort( fWindow );
 InvalRect( &fWindow->portRect );
 return true;

 return false;

This code gets called in response to a selection from the Picture menu.

• Add the member function TPictureWindow::AdjustMenusBeforeMenuSelection() to the file. Here’s the source code:

TPictureWindow::AdjustMenusBeforeMenuSelection( void )
 if ( fIsPictureCentered )
 gMenuBar->EnableAndCheckCommand( cCentered, true, true );
 gMenuBar->EnableAndCheckCommand( cUpperLeft, true, false );
 gMenuBar->EnableAndCheckCommand( cCentered, true, false );
 gMenuBar->EnableAndCheckCommand( cUpperLeft, true, true );

Depending on the value of fIsPictureCentered, this code places a check mark next to the appropriate item in the Picture menu.


Several months ago, when we first started this program, we added code to the function HandleMenuCommand() in SprocketStarter.cp that beeped when either of the Picture items was selected. Since we now handle these two cases inside the file PictureWindow.cp (as it should be done), we need to delete the two commands from the case statement in HandleMenuCommand() inside SprocketStarter.cp.

• Close the file PictureWindow.cp and open the file SprocketStarter.cp.

• Find the function HandleMenuCommand(). Inside the switch statement, delete the cases (all the way down to the break) for cCentered and cUpperLeft.

Running SprocketStarter

Well, that’s about it. Now’s the time to test your new creation. Select Run from the Project menu. When it runs, SprocketStarter will create a new text window, and the Text menu will appear at the end of the menu bar. Click on the Text menu, then make a selection from the Font submenu (Figure 2). The font of the frontmost text window should change and, the next time you select from the Font submenu, the check mark should appear next to this new font.

Figure 2. The Font submenu, showing the checkmark by Geneva
with Chicago selected.

Next, select Other (18)... from the Size submenu (we set up18 as the default font size). The font size dialog will appear, with the number 18 in the editable text field. Type 0 and click the OK button. You’ll hear a beep and the 0 will be highlighted. Type 37 and click the OK button (Figure 3). This time, your new font size is accepted and the text in the text window is redrawn showing the new font size.

Figure 3. The font size dialog that appears when you select Other (xx)...
from the Size submenu.

Once again, pull down the Text menu and bring down the Size submenu. Notice that the last item now reads Other (37)... and that the check mark has moved to this item (Figure 4).

Figure 4. The Size submenu with the Other (37)... item selected and checked.

Finally, create a picture window, then select one of the two items from the Picture menu that appears. With each selection, the picture in the picture window should be redrawn to match the selection and the check mark should appear next to the last selected item.

Figure 5. The Picture menu.

About the only thing left to do with this code is to make the sizes in the Size menu appear in outline font if they are available on the current machine or in regular font if that size is not available. Take some time to add this code. A good place to add the code is in the function TTextWindow::SetUpStaticMenu(), after you set up the static member fgSizeSubMenu. You’ll need to use the functions SetItemStyle() and RealFont() for each of the 6 sizes in the menu.

What’s Next

I hope the last few columns have given you an appreciation for the complexity and coolness of a framework. One thing I’ve grown to appreciate is the incredible amount of work it must have been for Dave Falkenburg to build Sprocket. Way to go, Dave!

I’m not sure what topic we’ll be tackling next month. I’ve been thinking about building a small PowerPlant project, just to explore the differences between Sprocket and PowerPlant. On the other hand, I’ve really got a hankering to build a tool palette using Sprocket. And there’s this cool OpenDoc part I’ve been fiddling with. Any preferences? Send some email my way...

See you next month!


Community Search:
MacTech Search:

Software Updates via MacUpdate

Spotify - Stream music, crea...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
Gutenprint 5.2.12 - Quality drivers for...
Gutenprint is a suite of printer drivers that may be used with most common UNIX print spooling systems, including CUPS, lpr, LPRng, or others. Gutenprint currently supports over 2000 printer models.... Read more
Firefox 52.0.2 - Fast, safe Web browser.
Firefox offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals and casual... Read more
Google Chrome 57.0.2987.133 - 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
RapidWeaver 7.3.3 - Create template-base...
RapidWeaver is a next-generation Web design application to help you easily create professional-looking Web sites in minutes. No knowledge of complex code is required, RapidWeaver will take care of... Read more
Chromium 57.0.2987.133 - Fast and stable...
Chromium is an open-source browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web. Version 27.0.2987.133: Note: This update has no Flash... Read more
Lyn 1.8.8 - Lightweight image browser an...
Lyn is a fast, lightweight image browser and viewer designed for photographers, graphic artists, and Web designers. Featuring an extremely versatile and aesthetically pleasing interface, it delivers... Read more
Adobe Animate CC 2017 16.2.0 - Advanced...
Animate CC 2017 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous Flash Professional customer). Animate CC 2017 (was Flash CC) lets you... Read more
Tunnelblick 3.7.0 - GUI for OpenVPN.
Tunnelblick is a free, open source graphic user interface for OpenVPN on OS X. It provides easy control of OpenVPN client and/or server connections. It comes as a ready-to-use application with all... Read more
DEVONthink Pro 2.9.11 - Knowledge base,...
DEVONthink Pro is your essential assistant for today's world, where almost everything is digital. From shopping receipts to important research papers, your life often fills your hard drive in the... Read more

Dynasty Blades new update introduces a n...
Sharpen your weapons -- Dynasty Blades is back with new and improved hack n’ slash stylings. The Romance of the Three Kingdoms-inspired action MMORPG introduces a bunch of fun new features in its latest update. For the uninitiated, Dynasty Blades... | Read more »
Meganoid(2017) (Games)
Meganoid(2017) 1.0 Device: iOS Universal Category: Games Price: $3.99, Version: 1.0 (iTunes) Description: LAUNCH DISCOUNT 20% UNTIL APRIL 2nd! Support, tip and tricks: Subscribe to our newsletter... | Read more »
Telltale's Guardians of the Galaxy...
Telltale will be releasing their rendition of Guardians of the Galaxy later this month. The first episode, Tangled Up in Blue, features familiar faces including Star-Lord, Groot, Rocket, Gamora, and Drax. If the first episode's title is any... | Read more »
Royal Dungeon (Games)
Royal Dungeon 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: The king and his queen are trapped in their castle which suddenly turned out as a very dangerous place. The goal is to escape... | Read more »
Tom Clancy's ShadowBreak is a real-...
Ubisoft is treating Tom Clancy fans to the series' very first mobile-exclusive game in ShadowBreak, a real-time, multiplayer shooter in which players snipe at enemies in fast-paced tactics-driven combat. [Read more] | Read more »
Power Rangers: Legacy Wars beginner...
Rita Repulsa is back, but this time she's invading your mobile phone in Power Rangers: Legacy Wars. What looks to be a straightforward beat 'em up is actually a tough-as-nails multiplayer strategy game that requires some deft tactical maneuvering.... | Read more »
Hearthstone celebrates the upcoming Jour...
Hearthstone gets a new expansion, Journey to Un'Goro, in a little over a week, and they'll be welcoming the Year of the Mammoth, the next season, at the same time. There's a lot to be excited about, so Blizzard is celebrating in kind. Players will... | Read more »
4 smart and stylish puzzle games like Ty...
TypeShift launched a little over a week ago, offering some puzzling new challenges for word nerds equipped with an iOS device. Created by Zach Gage, the mind behind Spelltower, TypeShift boasts, like its predecessor, a sleak design and some very... | Read more »
The best deals on the App Store this wee...
Deals, deals, deals. We're all about a good bargain here on 148Apps, and luckily this was another fine week in App Store discounts. There's a big board game sale happening right now, and a few fine indies are still discounted through the weekend.... | Read more »
The best new games we played this week
It's been quite the week, but now that all of that business is out of the way, it's time to hunker down with some of the excellent games that were released over the past few days. There's a fair few to help you relax in your down time or if you're... | Read more »

Price Scanner via

1.4GHz Mac mini on sale for $399, $100 off MS...
B&H Photo has the 1.4GHz Mac mini on sale for $100 off MSRP including free shipping plus NY sales tax only: - 1.4GHz Mac mini: $399 $100 off MSRP Sale ends on March 31st. Read more
13-inch 128GB MacBook Air on sale for $849, s...
B&H Photo has lowered their price on the 13″ 1.6GHz/128GB MacBook Air to $849, or $150 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 13″ 1.6GHz/128GB MacBook Air (MMGF2LL/A... Read more
Is Apple Planning An iPhone Based Modular Doc...
Today’s more powerful and larger-screened smartphones and phablets are becoming the default anchor computing device for more and more users computing devices, but even a five or six inch panel is not... Read more
Razer Launches New Razer Blade Pro World’s Fi...
Razer, the gaming and high performance hardware specialists, have announced the new Razer Blade Pro laptop — the first laptop to be qualified for THX Mobile Certification, an accreditation reserved... Read more
Gro CRM’s Apple Small Business Mac And iOS CR...
Gro Software, developers of the Mac CRM software for small business and enterprise, are included in FinancesOnline 2017 CRM Rising Stars and Great User Experience lists by business software review... Read more
Deal alert! 15-inch and 13-inch MacBook Pros...
B&H Photo has the new 2016 15″ and 13″ Apple MacBook Pros in stock today and on sale for up to $200 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.7GHz Touch Bar... Read more
Save up to $420 on a new MacBook Pro with App...
Apple is offering Certified Refurbished 2016 15″ and 13″ MacBook Pros, including some Touch Bar models, for up to $420 off original MSRP. An Apple one-year warranty is included with each model, and... Read more
12-inch 1.2GHz Retina MacBooks on sale for $1...
B&H has 12″ 1.2GHz Retina MacBooks on sale for up to $200 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 12″ 1.2GHz Space Gray Retina MacBook: $1449 $150 off MSRP - 12″ 1.... Read more
Is A New 10.5-inch iPad Still Coming In April...
There was no sign or mention of a long-rumored and much anticipated 10.5-inch iPad Pro in Apple’s product announcements last week. The exciting iPad news was release of an upgraded iPad Air with a... Read more
T-Mobile’s Premium Device Protection Now Incl...
Good news for T-Mobile customers who love their iPhones and iPads. The “Un-carrier” has become the first national wireless company to give customers AppleCare Services at zero additional cost as part... Read more

Jobs Board

Fulltime aan de slag als shopmanager in een h...
Ben jij helemaal gek van Apple -producten en vind je het helemaal super om fulltime shopmanager te zijn in een jonge en hippe elektronicazaak? Wil jij werken in Read more
Fulltime aan de slag als shopmanager in een h...
Ben jij helemaal gek van Apple -producten en vind je het helemaal super om fulltime shopmanager te zijn in een jonge en hippe elektronicazaak? Wil jij werken in Read more
Desktop Analyst - *Apple* Products - Montef...
…technology to improve patient care. JOB RESPONSIBILITIES: Provide day-to-day support for Apple Hardware and Software in the environment based on the team's support Read more
*Apple* Mobile Master - Best Buy (United Sta...
**493168BR** **Job Title:** Apple Mobile Master **Location Number:** 000827-Denton-Store **Job Description:** **What does a Best Buy Apple Mobile Master do?** At Read more
Fulltime aan de slag als shopmanager in een h...
Ben jij helemaal gek van Apple -producten en vind je het helemaal super om fulltime shopmanager te zijn in een jonge en hippe elektronicazaak? Wil jij werken in Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.