TweetFollow Us on Twitter

Sprocket Linked List 2
Volume Number:11
Issue Number:3
Column Tag:Getting Started

Adding Your Own Class to Sprocket, Part 2

Where to hook in with a linked list class...

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 created and tested a pair of classes that implemented a doubly linked list. This month we’ll look at the process of adding the linked list classes to a Sprocket project. Our goal is to create a linked list when the application starts up, then add a link to the list every time a new document is created. Each link in the list would contain a pointer to a TDocument object. When a document is closed, its corresponding link is removed from the list. When the application shuts down, the list is deleted.

Pre-Flighting Sprocket

Before you add new code to Sprocket, your first job is to make sure you have the latest version of Sprocket, and that you can get it to compile. As you no doubt have discovered for yourself, Macintosh development environments have an unsettling habit of changing with each new release, breaking your code in the process. The biggest reason for this is that Apple continuously updates their interface files, sending a constant stream of updates to the various compiler vendors. As of this writing, the latest version of Sprocket was built to run with a pre-release version of Code Warrior version CW5, which includes a slew of new headers. Though you can get the new version of Sprocket to compile using older versions of CodeWarrior, it will take a fair amount of work. Unfortunately, it would be impossible to continue to update Sprocket and to maintain compatibility with older versions of the various development environments. If you have any ideas about how we should be handling this problem, please send them along to our illustrious editor Scott (you can reach him at editorial@xplain.com).

As we go to press, Symantec had not yet released a version of Symantec C++ with the new Universal Headers, though by the time you read this, they likely will have. Since I can’t compile Sprocket using Symantec C++, all the figures in this month’s column are based on CodeWarrior. Hopefully, Symantec will make the new headers available in time for next month’s column.

When you go to any of the standard MacTech sites to download Sprocket
(see p. 2), there are two archives you’ll need. One should be called something like “Sprocket.12-15-94.sit” and the other something like “SprocketSample.12-15-94.sit”. The date in the middle is the date the archive was created, and should be about three months earlier than the date this article appears. The Sprocket archive contains the files that make up the Sprocket framework. The SprocketSample archive contains a few additional source code files, as well as a project file that brings the Sprocket and SprocketSample source together. The idea here is that Dave Falkenburg maintains Sprocket, while I maintain SprocketSample. Sprocket is a framework, while SprocketSample is an application that brings the framework to life. [You’ll be able to find the 12-15-94 versions, as well as any more recent releases at the online sites - ed stb]

Create a Sprocket folder on your hard drive, download and decompress the two archives, and copy each of the new folders into the Sprocket folder. Be sure each of the two folders has a date. This will distinguish the current Sprocket and SprocketSample folders from the versions you’ll download in following months. Figure 1 shows my master Sprocket folder. It contains one subfolder with the current version of Sprocket and another with two different versions of SprocketSample. The “before” folder contains all the SprocketSample code before I added in the list classes. The “after” folder contains the same program, this time with the list classes integrated in. We’ll start by getting the “before” version of SprocketSample to compile. Next, we’ll go through the process of converting the “before” version to the “after” version, then compile and run the “after” version.

Figure 1. My master Sprocket folder,
showing the folders for Sprocket and for SprocketSample.

Compiling the “Before” Version of SprocketSample

Each SprocketSample project is divided into two parts. The first part (the upper half of the project window) contains references to SprocketSample source code, while the second part (the lower half of the project window) contains references to Sprocket source code (Figure 2).

Figure 2. The 68K CodeWarrior version of the SprocketSample project.

To get the code in your SprocketSample project to compile, you’ve got to make sure the compiler can find all of the project’s files. If you are using CodeWarrior, launch either the PowerPC or 68K project, select Preferences... from the Edit menu, then scroll down to and click on the Access Paths icon (Figure 3). The rectangle labeled User: shows the paths that will be searched for source code files. The rectangle labeled System: shows the paths that will be searched for things like system include files. You want to make sure that the User: rectangle contains one additional path besides that leading to the project folder. The additional path is the folder containing the Sprocket source code. If this second path is there, but is wrong, click on it and press the Change button, then navigate into and select the folder containing the Sprocket source code. If the second path is there and looks good, just leave it alone. If there is no second path, click on the Add button and select the folder containing the Sprocket source code.

Figure 3. The CodeWarrior Access Paths preferences panel.

The point is, you want to make sure the compiler can find the Sprocket source code as well as the SprocketSample source. You know that the compiler will find the SprocketSample source code since it is in a subfolder inside the project folder. Once your new folder appears in the User: rectangle, click the OK button to save your preferences.

Next, you’ll need to make sure that your CodeWarrior project includes the proper precompiled header file. If you look at the project window shown in Figure 2, the very first file in the project is named SprocketSampleHeaders68K.pch++. This file is a source code file which will be precompiled, then used to compile all the other source files in the project. By precompiling all the #includes and #defines used by all your source code files, you can significantly reduce your compile times.

When CodeWarrior encounters a project file that ends in “.pch++”, it compiles the file into a precompiled header, saving the header in the same folder as its corresponding “.pch++” file. Select Preferences... from the Edit menu, then scroll down to the Language preferences. The Prefix File field tells the compiler which precompiled header to use when it compiles the project source code files (Figure 4). Make sure that the field contains either SprocketSampleHeaders68K or SprocketSampleHeadersPPC, making sure it matches the “.pch++” file in your project.

Figure 4. CodeWarrior’s Language preferences panel.

If you are using Symantec C++, you’ll have to address these same issues and get hold of the latest Universal Headers. That’s about it. You are now ready to take the “before” version of SprocketSample for a spin. Once you get everything to compile, you’ll see the familiar splash screen, menu bar, and empty tool palette window. Once you’ve had a chance to play with SprocketSample for a bit, quit and let’s add our list classes into the mix.

Adding the List Classes

Just as a reminder, here are the two linked list class definitions. TLinkedList is the linked list itself and TLink is a single link:

class    TLinkedList
{
  public:
                            TLinkedList();
    virtual                 ~TLinkedList();

    virtual    OSErr        CreateAndAddLink( void *objectPtr );
    virtual    OSErr        FindAndDeleteLink( void *objectPtr );
    virtual unsigned long   CountLinks();
    virtual void            *GetNthLinkObject( unsigned long 
                                                 linkIndex );

  protected:
    virtual void            DeleteAllLinks();
    TLink                   *FindLink( void *objectPtr );
    virtual OSErr           DeleteLink( TLink *linkPtr );
    
    TLink                   *fFirstLinkPtr;
    TLink                   *fLastLinkPtr;
};

class    TLink
{
  public:
                    TLink( void *objectPtr );
    virtual         ~TLink();
    virtual void    SetPrevLink( TLink *prevLinkPtr )
                        { fPrevLinkPtr = prevLinkPtr; }
    virtual void    SetNextLink( TLink *nextLinkPtr )
                        { fNextLinkPtr = nextLinkPtr; }
    virtual TLink   *GetPrevLink()
                        { return fPrevLinkPtr; }
    virtual TLink   *GetNextLink()
                        { return fNextLinkPtr; }
    virtual void    *GetObjectPtr()
                        { return fObjectPtr; }

  protected:
      TLink         *fPrevLinkPtr;
      TLink         *fNextLinkPtr;
      void          *fObjectPtr;
};

The first thing you’ll need to do is copy the four source code files that make up the TLinkedList and TLink classes into the same folder as the SprocketSample source code. In this case, you’ll copy the files LinkedList.cp, LinkedList.h, Link.cp, and Link.h into the SprocketSample folder located inside the folder named SprocketSample, Before. Be sure to add Link.cp and LinkedList.cp to the first half of the project window.

Next, you’ll need to modify SetUpApplication() to create a new TLinkedList object and QuitApplication() to step through the list and close all the documents stored in the list. You’ll also need to create a global variable containing a pointer to the TLinkedList object. To do that, create a file called SprocketSample.h and type in the following code:

#include "LinkedList.h"

extern  TLinkedList*gListPtr;

Save SprocketSample.h in the same folder as all the other SprocketSample source code.

Next, open the file SprocketSample.cp and add these two lines at the top:

#include "SprocketSample.h"

TLinkedList *gListPtr;

Now scroll down to the first routine in SprocketSample.cp, which should be SetupApplication(). Here’s where you’ll create a new TLinkedList object. Add this line at the beginning of SetupApplication():

gListPtr = new TLinkedList;

Scroll down about 4/5 of the way down in SprocketSample.cp and find the routine QuitApplication(). Change the routine so it reads like this:

Boolean QuitApplication(void)
{
 unsigned long numLinks, counter;
 TDocWindow *myDocPtr;
 OSErr  err;
 
 numLinks = gListPtr->CountLinks();
 for ( counter=1; counter<=numLinks; counter++ )
 {
 myDocPtr = (TDocWindow *)gListPtr->GetNthLinkObject( 1 );
// If the user cancels the close, return false to cancel the quit...
 if ( ! myDocPtr->Close() )
 return false;
 else
 delete myDocPtr;
 }
 
 return true;
}

The main purpose of QuitApplication() is to step through the list of documents, sending each document object a close message. If a document has changed since it was last saved, its close method will give the user a chance to cancel the close. If the close is canceled, we’ll exit the loop by returning false, thus canceling the quit. If the user doesn’t cancel a close, the TDocWindow object under consideration is deleted.

A few things worth noting here. Notice that we delete the TDocWindow but don’t remove it from the list first. That is done in the TDocWindow destructor. Deleting it from the list inside the TDocWindow destructor has two advantages. First, this keeps us from having to remember to delete the TLink every time we delete a TDocWindow. Secondly, this ties the deletion of the link as closely as possible to the actual deletion of the TDocWindow, keeping us from the nasty situation where we have a TDocWindow that isn’t in the list or where we have a TLink that points to a TDocWindow that’s already been deleted.

Take some time to look through the code that closes documents. Look in SprocketMain.cp at the code that handles clicks in a window’s close box and at the code that handles the Close and Quit menu items. Also check out the code that responds to the quit application Apple event. This code will probably change slightly in the future, but it won’t change by much. The most likely change is to merge all the above-mentioned code so that it all closes documents the exact same way.

Our final task is to modify the TDocWindow constructor and destructor. The constructor needs to embed a pointer to the new TDocWindow in a TLink, adding the TLink to the list pointed to by gListPtr. The destructor needs to find the TLink containing the TDocWindow about to be destroyed, and remove that link from the list.

Before you edit the constructor and destructor, you’ll need to add this line to the beginning of DocWindow.cp:

#include "SprocketSample.h"

This will give you access to the global gListPtr as well as to the TLinkedList class.

Now add these three lines to the end of the TDocWindow() constructor:

 err = gListPtr->CreateAndAddLink( this );
 if ( err != noErr )
 DebugStr((StringPtr) "\pAdd Doc to list failed");

The first line adds a pointer to the current object to the list, while the second two lines drop us into MacsBug if the add failed.

Add these three lines to the ~TDocWindow() destructor:

 err = gListPtr->FindAndDeleteLink( this );
 if (err != noErr)
 DebugStr((StringPtr) "\Delete doc from list failed");

The first line deletes the TDocWindow from the global linked list. The second two lines drop us into MacsBug if the delete fails.

Running the New, Improved SprocketSample

OK, now that all your changes are in, run your new version of SprocketSample (or, if you just can’t wait long enough to type in the changes, run the version of SprocketSample in the SprocketSample, After folder). Select New from the File menu and create 3 new documents. Next, click in the close box of the frontmost window. You’ll be prompted to save the changes in that window. Click the Save button.

Now select Quit from the File menu. Once again, you’ll be prompted to save changes in a document, but this time you’ll be prompted to save the changes in the first document in the global TLinkedList, which should be the document named “Untitled-1”. If you click the cancel button, the quit should be aborted and you should be left running as you were before you selected Quit.

Experiment with various cancel and saving combinations. Try sending a quit application Apple event to SprocketSample by launching this script from the Script Editor:

tell application "SprocketSample.68K"
 quit
end tell

Be sure to change the name of the application in the tell clause if you are not running with the 68K version of CodeWarrior. Use the debugger to follow the code. Though Sprocket might seem a little intimidating, it’s really not that hard to follow once you get into it, especially if you confine yourself to a specific functional area or thread.

Until Next Month

In next month’s column, we’ll look into Sprocket’s menu handling model and add our own menus to Sprocket’s menu bar. The current plan is to replace the existing menu-processing code with a new design that more closely approximates that used by OpenDoc. The idea is, if you learn how to handle menus in Sprocket, you’ll have a leg up when you start writing your first OpenDoc part.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.