|
Volume Number: | 12 | |
Issue Number: | 2 | |
Column Tag: | Object Pascal |
MacApp 2 for PowerPC in Object Pascal
“Object Pascal is not bad, it just smells funny.” - apologies to F.Z.
By Brian Arnold
Whither Native?
This is an article for developers who have Object Pascal MacApp 2 code and want to make that code native for PowerPC [or for anyone whose pulse was set racing by Brian’s and Guy MacCarthy’s preliminary report in the November 1995 issue - man]. Along the way, it will describe the MacApp2PPC developer’s cooperative as an example of how developers can help themselves when they need it the most. Although the MacApp framework itself has long since made the switch to the PowerPC, it has done so at the expense of Pascal Object support. The latest version of MacApp, 3.3, is written in C++, and has features to make you salivate - drag and drop, AppleScript, PowerTalk mailers, performance optimizations - and version 3.5 will have OpenDoc container support. You could convert your source code and upgrade today; many developers have done this. There are a number of excellent Object Pascal to C++ translators available on the market to help you in this conversion. But if you’re resource constrained, or C++ syntax causes a gag reflex, or you have some other Very Important Reason to stay with your Object Pascal MacApp 2 code, MacApp2PPC provides another alternative.
MacApp 2 for PowerPC
The Pascal version of the MacApp framework is hardly five years old now, and it’s already doomed to obsolescence. Or is it? Maybe once OpenDoc and SOM arrive in full force, we can seal the coffin on this version of the framework and look elsewhere for Object Pascal framework solutions. But until then, the lean and mean MacApp 2 still has some mileage left in the millions of lines of excellent Macintosh code written using it.
So what’s so difficult about porting MacApp 2 to PowerPC? To find out, I announced a developer’s cooperative at the Apple May 1994 WWDC. Immediately, twenty developers joined. We encountered several difficult obstacles, and by distributing the effort among the developers, we were able to make the necessary changes to MacApp 2 in just under 12 months.
Of course this would all be academic if there hadn’t been support from Apple and the compiler vendors. Language Systems (LS) licensed MPW Pascal from Apple and further developed a PowerPC back-end; LS is now developing it as a Symantec IDE plug-in compiler. They were instrumental in providing us with support when we were just getting started. Apple aided in the development of the project, particularly at the hack session that helped finalize the port. Metrowerks developed a compatible PowerPC Pascal compiler, and later added Pascal Object support and made it a plug-in compiler for the CodeWarrior (CW) IDE.
MacApp 2 for PowerPC has been designed to work with both the LS Pascal and CW Pascal compilers, and is provided by both Language Systems and Metrowerks for use with their native Object Pascal compilers.
MacApp 2 Conversion
Here’s the short list of elements in MacApp 2 that had to be changed for PowerPC.
• MacApp 2 makes extensive use of 68K assembly and in-line code that can’t run (easily) on PowerPC. This code had to be rewritten in Pascal, C, or PowerPC assembly.
• MacApp 2 relies on AppFile Toolbox calls and has no support for required Apple events. The PowerPC runtime architecture does not support AppFile calls for opening documents at application startup, and expects you to support the required Apple events (open application, open document, print document, quit application).
• MacApp 2 uses 68K-specific methods for trap patching. On PowerPC, patching a Macintosh Toolbox trap is a lot less trivial and more costly, so it needs to be done differently and less often.
• MacApp 2 makes extensive use of ProcPtrs for Mac Toolbox callbacks. Since the PowerPC Toolbox is designed to operate with both PowerPC and 68K applications, all callback ProcPtrs need to identify whether they are compiled for 68K or PowerPC. A toolbox glue routine for each ProcPtr fills in this information, plus some other housework, and returns a UniversalProcPtr that you use instead of the ProcPtr.
• MacApp 2 uses old and obsolete Toolbox names extensively. The PowerPC runtime architecture uses shared libraries (code fragments) that implement newer, more consistent names for Toolbox calls. Because Toolbox calls are resolved by name, the new Toolbox names must be used. In addition, the Pascal QuickDraw globals thePort, gray, etc., now reference the qd global (e.g., qd.thePort), as it is in C.
• Developers have relied on unsupported extensions that also needed to be ported. These extensions include Model Far, floating windows, tear-off menus, and synchronized scrolling.
• Finally, adding support for PowerPC Object Pascal compilers and IDEs was a prerequisite. The build process needed to be revamped to support the latest development environments and tools, and the documentation had to be revised.
This sounds a bit daunting. Frankly, when I announced the MacApp2PPC developer’s cooperative, I didn’t have the foggiest idea whether or how we were going to succeed. However, I did know a little bit about what needed to get done and I called upon members of the MacApp 2 developer community for their interest in helping themselves. I did not expect this inquiry to generate a lot of interest, but we developed into a 100-member Internet mailing list. I also did not expect to witness much enthusiasm, but it was there in spades.
Essential Ingredients for Making It Happen
We were so successful with the MacApp 2 PowerPC port that I am compelled to muse on why this was so. It isn’t so hard to identify the elements, because we promoted them from the start.
• Nobody else is going to do this for you, so you had better do it yourself.
• Only do what is necessary, and do no more.
• Don’t change anything that doesn’t need to be changed.
• Trust your instincts.
When you take personal responsibility for managing a task, the details become much clearer to you, and you are more productive. Secondly, when you focus on only what is necessary, the right thing to do comes out of the woodwork and other gunk tends to stay out of the way. Finally, when you don’t change things that would seriously affect the user of the framework, something mysterious and wonderful happens: their code gets ported faster. The extra ingredient, “trust your instincts,” is the reason why I persisted with MacApp2PPC for the past year and a half. It didn’t hurt that the Internet (and AppleLink) helped people across continents share ideas and code to make this happen.
For the first eight months, Masahiro Abe, Per Bergland, and Dave Johnston laid the foundation for the port by switching MacApp to the new Toolbox names, rewriting assembly code in C, Pascal and PowerPC assembly, and developing conversion scripts for our own code, while the remainder of the cooperative provided feedback.
In March 1995, when it looked like we had completed all the difficult porting tasks, we held a three-day hack session at Lumina, where a dozen developers and Language Systems and Apple engineers converged to identify the remaining porting issues. Lumina’s Brendan Del Favero set up the ethernet, and John Corbett made the logo. LS’s Steven Hopkins and Steve Lavagnino were in the compiler hot seat. Apple’s MPW entomologist Greg Branche helped out with MPW-related issues. Dave Johnston practically lived inside the PowerPC debugger all weekend. Cheryl Lins and I went wild on adding floating windows support to MacApp 2. Larry Tesler, Apple’s chief scientist and the one to blame for MacApp 1.0, stayed up late hacking code with Colleen Barton, and contributed a change to his USynchScroller unit. Andrew Peterson and Larry Hamel came to port their MacApp 1.0 application. Eric Jackson, Mr. MacWireFrame, didn’t use MacApp 2, but provided a lot of feedback on PPC Pascal code generation. Masahiro Abe, Per Bergland, David Shillitto, and Ingo Ciechowski provided remote input and feedback. As you would expect for such an event, Prograph guru and MacApp afficionado Kurt Schmucker visited and handed out C++ barf bags. I highly recommend throwing a hack session; nothing helps better to identify the critical tasks while having a lot of fun.
A few weeks after the session, Metrowerks added their support with the help of CW Pascal architect Marcel Achim and developers Roger Brown, Peter Baum, Donald McCormick, Farhad Anklesaria, and Scott Vorthmann, all of whom contributed one change or another. By the May 1995 Apple WWDC in San Jose, CA, we were able to claim that “Nothing works!”, “Failure fails!”, and “Windows float!” In case you’re not familiar with MacApp, Nothing is the name of the 4-line “Hello World” example application, UFailure is the name of the seminal framework failure handling mechanism, and windows never used to float in MacApp 2 (that part we borrowed from MacApp 3). These were our milestones. Most of us were amazed that we succeeded in one short year.
Porting Your Source Code
Along the way to developing MacApp2PPC, we tried to come up with tools and hints for making the leap to PowerPC with your own code. The result is a set of MPW scripts that you can execute to do most of the conversion work for you. However, because MacApp2PPC was constructed to minimize the damage to your own code, you may be surprised at how little time it would take you to port even without the MPW scripts.
Running the scripts is easy, provided you can already tolerate MPW.
1. Install MacApp2PPC and a minimal MPW according to the instructions provided on your compiler vendor’s CD. It is best to use a fresh MPW setup, not one that you’re already using.
2. Start up MPW. Confirm that MacApp2PPC installed correctly (its menu is added to the menu bar).
3. Set the current directory to one containing your Pascal source code, and select Convert Directory from the MacApp2PPC menu. Several dictionary files are run against your code using the MPW Canon tool. This performs the majority of the Toolbox renaming changes.
4. You can run a script called CreateUPPChecker to find out where all of your ProcPtrs live, because you will have to change them to create UniversalProcPtrs. Because this script takes a long time to run, it’s best to start it at night and return to it the next day (or the next, depending on how large your application is).
By this point, most developers cut to the chase, try to build, and wade through the remaining compiler and linker errors. We’ll cover a few of them here.
Changing those Pesky ProcPtrs
One common hang-up in the migration to PowerPC is the need to replace ProcPtrs with UniversalProcPtrs for Toolbox callbacks. We’ll take a moment to describe how to change a ProcPtr through an example in MacApp 2 itself.
The process goes like this: you have identified a ProcPtr that must be changed. You need to create a UniversalProcPtr for that procedure pointer, and use that UPP in its place. The UPP is a record that includes your procedure pointer, information about whether it’s compiled for 68K, and other housework. If you use that UPP repeatedly or in a modeless manner (for example, a TextEdit clickLoop callback), you might hang on to it; otherwise, you will usually dispose of the storage used by the UPP right after making your Toolbox call.
For example, in MacApp 2 for PowerPC, when Finder printing, we use the Apple event Toolbox call AEInteractWithUser to make sure we get the user’s attention before putting up the print dialog box. This call has a callback to our own code, so that we can idle while the Apple event manager is off waving its hand in front of the user. Here is the interface to the idle function.
FUNCTION IdleFunction ( VAR event: EventRecord; VAR sleepTime: Longint; VAR mouseRgn: RgnHandle): BOOLEAN;
Before porting to PowerPC, the address of this function would be passed directly to the Toolbox:
FailOSErr(AEInteractWithUser( kAEDefaultTimeout, NIL, @IdleFunction))
For PowerPC, to create the UPP automatically, we go searching for the Toolbox file that contains the definition for the relevant function, in the hope of finding a definition for its UPP and an automatic conversion function. In this example, the Toolbox file is AppleEvents.p; lo and behold, there is an AEIdleUPP type and NewAEIdleProc conversion function provided for us. Because we no longer need the UPP when we are through, we will dispose of it when finished. So, in order to call AEInteractWithUser, we add a local variable and change the AEInteractWithUser code.
VAR idleUPP: AEIdleUPP; idleUPP := NewAEIdleProc(@idleFunction); FailNIL(idleUPP); FailOSErr(AEInteractWithUser(kAEDefaultTimeout, NIL, idleUPP)); idleUPP := DisposeIfRoutineDescriptor(idleUPP);
When building for 68K, this changed code still works, that’s why it’s called Universal. In fact on 68K it does the same thing as before: NewAEIdleProc simply returns the @, and DisposeIfRoutineDescriptor does nothing. We are doing this extra work for PowerPC builds.
Working with fp and fenv
Another area of difficulty in porting your own code to PowerPC is likely to be the use of SANE or the 68881 (math coprocessor), if you do a lot of floating point math in your application. The good news is that the MPW porting scripts provided with MacApp2PPC make a lot of the changes for you to use the PowerPC MathLib through fp.p and fenv.p. Still, there are a few gaps.
For example, the Num2Str and Str2Num functions aren’t provided by MathLib. This bothered key developers porting MacApp2PPC, so these are now provided in UMacAppUtilities. If you already include UMacAppUtilities or UMacApp, you can continue using Num2Str and Str2Num as is. Note that the string parameter was changed from DecStr to Str255.
MacApp 2 API Changes
Aside from new interfaces and methods, the only major API change is in TApplication:GetActiveWindow, which now requires a Boolean parameter similar to MacApp 3. kFloatersOK and kFloatersNotOK are defined for you. If you use this function, the returned window can be a floating window or a regular window. When in doubt about how you need it to behave, use kFloatersNotOK.
Other important API changes include accepting UniversalProcPtrs instead of regular ProcPtrs (consult the previous description of converting to UPPs for help in changing your ProcPtrs).
Finally, UPatch’s mechanism for patching traps has changed to conform to the MacApp 3.1 mechanism, which is friendlier for PowerPC trap patching. If you use UPatch directly, you will have to change the way you patch traps. Consult UPatch and MacApp 3.1 documentation for details.
What’s More
We wouldn’t be able to call ourselves good hackers if there wasn’t a surprise or two in the converted MacApp 2. One surprise is integrated support for floating windows. There is an unsupported trap-patched floating windows unit used by a lot of MacApp 2 developers, but nobody wanted to wade through the gunk in porting that code, which is buggy anyway. So, Cheryl Lins and I looked at MacApp 3.1’s support for floating windows, and we back-ported those changes into MacApp 2. It was easier than it sounds. The result is cleaner, integrated floating window support in the framework, and no trap patching. Finally, code for Balloon Help was mixed in with the code that supports Apple events (which Anil Bajaj originally wrote as a patch to MacApp 2 using Keith Rollin’s excellent PatchMaker).
Apple events in MacApp 2
Several API functions are added for Apple event support. Default support for the required Apple events 'oapp', 'odoc', 'pdoc', and 'quit' are implemented in TApplication.
You can support Apple events very easily with MacApp2PPC. You first create a new 'aedt' resource in your <app>.r file specifying the event class, event message, and a CmdNumber (for an example look at the 'aedt' resource in the MacApp.r file). The next and only other thing you have to do is override the TEvtHandler method DoAECommand and handle the appropriate CmdNumber (just like you would in DoMenuCommand, etc.).
DoAECommand interface { If the handler can perform the apple event command it } { does so by either performing the command directly or } { by posting a TCommand. NOTE: Both UNIV Ptr’s are } { actually a Ptr to an Apple event record } FUNCTION TEvtHandler.DoAECommand ( aCmdNumber:CmdNumber; message: UNIV Ptr; reply: UNIV Ptr): TCommand;
In addition, there are two utility routines (in UMacAppUtilities):
• MissedRequiredAEParameters checks the passed-in Apple event for any required parameters that we may have missed (called if handling Apple events, which should not have any parameter like the open application and quit events.)
• ProcessAEDocList extracts the list of documents from the Apple event’s direct parameter and converts each document’s FSSpec record to an AppFile record; then calls the passed-in routine (used to handle the open document and print document events).
Note: Your 'size' resource must have its isHighLevelEvents flag set in order for your application to receive Apple events. All of the MacApp2PPC example applications have this set already.
Floating windows
Floating window support was integrated into TApplication and TWindow. If you wish to add floating windows to your application, all you need to do is call InitUFloatWindow to ensure that the TFloatWindow subclass isn’t dead-stripped.
To make a window floating, make your window resource class name a TFloatWindow instead of TWindow, and add the following to your .r file:
#include "FloatWindow.r"
This adds the System 7.5 floating window WDEF to your application, so that you have floating windows on older Macintosh systems. If you’ve been reading this article and you’re skeptical of the value of object-oriented frameworks, notice the number of lines of source code the developer must write to use floating windows (answer: one line, and that’s just to trick the linker!).
New Building Blocks
Actually, none of these building blocks are new, but they’ve moved from the MacApp examples into the main part of the MacApp library. If you are already using them, you will be mildly relieved to know they have been ported to PowerPC. You can remove them from your application source code, as well as from your MAMake file (if you’re using MPW).
These building blocks include:
UBetterFeedbackCmd VBL-synchronized feedback
UFloatWindow Floating window support
UGrabberTracker That MacPaint hand-grabber thingy
UMenu TView descendants that can appear in menus
USynchScroller Scrolling multiple views simultaneously
UTearOffMenu What it says
UVUAssist Virtual User support (OK, I lied, this is
68K only)
Compiler-Specific Details
It’s worth mentioning one compiler-specific detail for each Object Pascal compiler.
Language Systems Pascal 1.0 works under MPW; that means it uses the MABuild tool to build MacApp applications. MABuild has been modified to accept additional options, including -[No]PPC to indicate 68K vs. PowerPC code generation. That’s all there is to it! When a future version is provided as a plug-in for the Symantec IDE, the build process will use the features in the IDE more directly.
Metrowerks CodeWarrior Pascal works within the CodeWarrior IDE so the IDE is used for building applications, but MacApp 2 still requires compiling resources under MPW. Although there is a Rez plug-in for the CW IDE, MacApp 2 still relies on a custom MPW tool called PostRez. To make life easier for the CW Pascal user, the revised MABuild tool also accepts a -[No]OnlyResources option, to specify that you wish to compile (and PostRez) only resources for your application. This step is still annoying enough that Per Bergland and Roger Brown are seeking ways to remove or simplify the PostRez step, by developing a plug-in tool. Their dedication captures the spirit of what is MacApp2PPC.
And Finally
Well over a dozen applications have been ported to PowerPC using MacApp2PPC, and many more are currently being ported. Meanwhile, the world of software frameworks is constantly shifting. Component technology is moving rapidly to your neighborhood. MacApp2PPC is currently serving the needs of Macintosh Object Pascal MacApp 2 developers wishing to have native applications on PowerPC. Where it goes depends on the developers who use and nurture this version of the framework. There is no commitment except the one each developer gives to it. Some developers are sufficiently motivated to continue evolving MacApp 2 in manners consistent with the drive towards MacApp 3.3 as its flagship, and in moving developers toward OpenDoc as the future.
Developers in the cooperative are considering adding drag and drop support as an initial step toward OpenDoc container support, removing the working directories dependency, and removing the PostRez step mentioned earlier. If you want to make a difference and help out in making these changes, you can join the “MacApp2PPC-List” Internet mailing list by sending e-mail to macjordomo@afar.med.cornell.edu with “subscribe MacApp2PPC-List Your_Name” in the body of the message; send e-mail to arnold@lumina.com if you need help. Macjordomo (http://leuca.med.cornell.edu/Macjordomo) is a listserver that Michele Fuortes ported to PowerPC using MacApp2PPC in about 5 evenings. You are also highly encouraged to subscribe to the comp.lang.pascal.mac newsgroup on the Internet to stay in tune with the latest goings-on in Pascal for the Macintosh.
Also, check out the cooperative’s Internet world wide web pages at: http://www.lumina.com/arnold/MacApp2PPC.html
You’ll find some interesting things for MacApp 2 at this site, including the latest version of MacApp 2 for PowerPC, plus WASTE text engine support, QuickDraw GX printing support, and more.
What this cooperative brings Object Pascal MacApp 2 developers in the future is yet unseen. Stay tuned.
- SPREAD THE WORD:
- Slashdot
- Digg
- Del.icio.us
- Newsvine