TweetFollow Us on Twitter

Template Application
Volume Number:1
Issue Number:2
Column Tag: C Workshop

“Template” Application

By Robert B. Denny

This month’s C Workshop presents a “template” application. Most Macintosh programs share a common overall structure, dictated by the operating system environment. The purpose of the template program is to give you a framework for developing your own applications. It will also be used as the basis for topics discussed in future C Workshops. The functions that do the actual work of the program have been “stubbed”.

Since “a program is worth a thousand words”, most of this month’s column is the program itself, sprinkled liberally with comments. Please take the time to study the program. But first, a few introductory words.

Some C Basics for the Macintosh

Many data structures that you’ll be working with are stored in the “heap”, dynamic memory. Most of these struc- tures are accessed by a “handle” rather than a pointer. A handle is a pointer to a pointer. Why this extra level of indirection?

The heap is used for almost everything. Code goes there. Resources go there (code is really a resource). Data structures allocated at run time go there. Nothing is preallocated. The memory manager is rather dumb about allocating and deallocating blocks of space in the heap.

As a result, the heap can (and does) get chopped up into small pieces. When someone makes a request for a block of space that exceeds the size of the largest free block, the memory manager compacts the heap. It moves blocks of data around in an effort to collect enough contiguous space to satisfy the request. Blocks that are eligible to be moved are called relocatable. Most Mac data structures fall into this class. You can control whether or not your own data structures are relocatable. The tradeoff should be obvious.

Relocatable data structures are accessed via handles so that your references remain valid if the structure is moved. The handle points to a master pointer which in turn points to the relocatable structure. If the structure is moved, the memory manager updates the master pointer and your handle reference remains valid. Obviously, the area containing the master pointers is not relocatable.

Accessing data structures defined by struct statements via handles isn’t too difficult. The example is shown in figure 1 below:

The expression assigns the value contained in the relocatable structure via its handle to “intval”. The only safe way to access relocatable structures is to use the double-indirect access shown above at all times. Do not attempt to cache the pointer (*foo_handle) at any time. To do so is to defeat the purpose of handle access.

Template Application

Now to the template application. It is written for the Consulair Mac C system and Toolkit. Changes to the details of the program will probably be necessary for other languages since there is little consistency in the toolbox interface.

/*
 * *************
 * *  TEMPL.H  *
 * *************
 *
 * Common stuff for template program
 *  (C) 1984, MacTech  by Robert B. Denny
 *
 * NOTE:Dependent on the menu                 
 *   structure defined in the resources.
 */

// Toolbox traps must start with ‘#’ now.
#Options -N

//
// Include Macintosh data structure 
// definitions.  These files are included 
// with the Mac C Toolkit, or from the 
// Stanford University Macintosh C 
//  Programming system (SuMacC).
//

#include  <MacDefs.H>
#include<QuickDraw.H>
#include<Control.H>
#include<Events.H>
#include<Menu.H>
#include<TextEdit.H>

#define MAX_WINDOWS8
#define MAX_MENUS8

#define TRUE1
#define FALSE    0
#define NULL0

/*
*  Each window requires a window                
*  control block to define it’s structure. 
*  Note which things are handles and           
*  which are pointers.
*
* wcb = Window Control Block
 */
struct wcb
 {
 WindowPtrwp;  // Pointer to window rec in heap
 Rect drag_rect; // Dragging limits
 Rect grow_rect; // Window size limits
 TEHandle te_handle; // Handle to textEdit rec in heap
 Point  te_origin; // Text origin
 ControlHandle vs_handle; // Vert scroller’s handle
 ControlHandle hs_handle; // Horiz scroller’s handle
 };

//
// Supress extern declarations in module 
// containing the real declarations.
//
#ifndef GLOB_DATA
extern struct wcb dw[MAX_WINDOWS];
extern struct wcb *dwp;   // --> Current doc-window
extern unsigned n_windows;// No. of open windows
extern EventRecord Event; // Our event record (duh)
extern short EvType; // Event result type
extern WindowPtr EvWindow;// Event window
/*
 * Array of menu handles 
 */
extern MenuHandle menus[];// Our menu contexts
#define APPLE    1
#define FILE2
#define EDIT3
#define OPTIONS  4
#endif

/*
 * Resource ID’s of menus in rsrc file.
 */
#define APPLE_ID 1
#define FILE_ID  256 
#define EDIT_ID  257
#define OPTIONS_ID 258 //Add more menu resource ID’s here

/*
 * File menu item numbers
 */

#define FM_EXIT  // This should reflect file menu rsrc

/*
 * Edit menu item numbers
 *
 * Note that SystemEdit expects the Edit    
 *  menu items as follows:
 *
 * 0: undo (** YES, zero-based **)
 * 1: --------
 * 2: cut 
 * 3:  copy
 * 4: paste
 *
 * The rest of the items may be chosen 
 *    at will by the application.
 */

#define EM_UNDO  1
#define EM_CUT 3
#define EM_COPY  4
#define EM_PASTE 5
#define EM_CLEAR 6

/*
 * Options menu assignments
 */
#define MM_EDIT_WINDOW  1
#define MM_SCRAWL_WINDOW  2
#define MM_MUSIC  4

/*
 *   Other resource ID’s
 */
#define ABOUT_ID 256
#define WINDOW_ID256

/*
 * Macro to hack the Point struct,               
 * composed of 2 short (16-bit) ints
 * into a long, which can be passed by         
 * value to toolbox routines.
 * Takes address of a Point and turns it      
 * into a scalar long.  NOTE
 * this generates NO runtime code.
 */
#define PtLong(ptr) *((long *)ptr)

MAIN PROGRAM

A Template Application in C

Template program for the C Workshop. Has hooks for multiple dynamically allocated windows (to be added in future columns), supports desk accessories, has a menu bar with 4 menus and an “about” dialog in the Apple menu. The program will eventually support multiple dynamically allocated text edit and drawing windows. The text edit windows will have scroll bar controls and resizing (“grow”) capability. Also, an interface to the sound system will be added. The components of this program are:

TMAIN.C This module, the main program & global data.

TMENU.C Menu handling functions, fig. 6.

TEMPL.H Common “include” file of definitions, fig. 4.

TEMPL.R RMAKER source for program resources, fig. 5.

TEMPL.LINK Linker command file, fig. 3.

TEMPL.JOB Exec command procedure to build template, fig. 2.

Additional modules will be added in future C Workshop columns. This program was written for the MAC C system by Consulair Corp. Changes will be needed for other C systems. Also, prerelease versions of MAC C and RMAKER may not work with this program. [Note: one or two obscure Mac C statements may have been changed in the current Mac C so that a change may be needed to fully compile this program using present Mac C systems. This program was written with an early version of Mac C. Any offending lines should be obvious at compile time. -Ed.]

/*
 * TMAIN.C - Template application
 * (c) 1984 MacTech by Robert B. Denny
 */
 *     GLOBALS DEFINITIONS
#define GLOB_DATA
#include <Templ.H>
/*
 Define window control block for window   management. See Templ.H file.
 */
struct wcb dw[MAX_WINDOWS];  // our windows
struct wcb *dwp = NULL; // --> Current window
unsigned n_windows = 0; // Number of open windows
EventRecord Event; // Our event record
short EvType;    // Event result type
WindowPtr EvWindow;// Event window
MenuHandle menus[MAX_MENUS]; // Our menus
 
/*
 *   MAIN PROGRAM  
 *
 * Link with MacCLib, which does 
 * Quickdraw and Window initialization.
 *
 */
main()
 {
 register WindowPtr wp; // Try to save space/time
 int i;
 #InitFonts();   // Not done in MacCLib ...
 #InitDialogs(0);// No restart function
 #OpenResFile(“\011TemplRsrc”);// Open resfile (Pstring)
 setup_menu();   // Set up our menus
 #TEInit(); // Initialize TextEdit
 #FlushEvents(-1,0); // Flush all events
 #InitCursor();  // Make arrow cursor
 for(i=0; i<MAX_WINDOWS; i++) // Mark all WCB’s free
 dw[i].wp = NULL;
 dwp = NULL;// No windows
 n_windows = 0;

 //   -- EVENT LOOP --
 // This is the “outer loop” of a typical    // application.  All event 
types
 // are dequeued, most are processed.  // Those not processed are ignored.
 // 
 while(TRUE)// Loop here forever
 {
 #SystemTask();  // Handle desk accessories
 // dwp always points to the WCB   //for the active (front) window.
 // If dwp = NULL, than it’s not   //”our” window.
 // (Is this possible??)

dwp = (struct wcb *)find_wcb(#FrontWindow());
if(dwp != NULL && dwp->te_handle != 0) // If active wind & text
#TEIdle(dwp->te_handle);  // Flash the insertion mark
if(!#GetNextEvent(-1, &Event)) // Process only our events
continue;
 switch(Event.what)// Dispatch on event type
 {
 case mouseDown: // Mouse click
 do_mouse();// Dispatch on mouse location
 break;
 case keyDown: // Keypress
 case autoKey:  // Repeat-key generator
 do_key();
 break;
 case updateEvt: // window needs refresh
EvWindow = (WindowPtr)Event.message; // Which window?
 upd_wind(EvWindow); // Do the update
 break;
 case activateEvt: // Activate/deactivate
EvWindow = (WindowPtr)Event.message; // Which window?
 if(Event.modifiers & 1) // If Activate
 act_wind(EvWindow); // Activate window
 else // If Deactivate
 deact_wind(EvWindow); // Deactivate window
 
// Additional cases for other event types 
 default: // Do nothing for other events
 }
 }
 //
 // -- END OF EVENT LOOP --
 //
 }

/*
 * *  LOCAL FUNCTIONS  *
 *     Handle mouse-down events
 */
do_mouse()
 {
 short window_part;// FindWindow result code //
 // Following fills in EvWindow with //--> window in which the click
 // occurred (or NULL if none).
 //
 window_part = #FindWindow(PtLong(&Event.where), &EvWindow);
 
 switch(window_part) // Dispatch on where clicked
 {
 case inMenuBar: do_menu(#MenuSelect(PtLong(&Event.where))); 
 break;
 case inSysWindow:
 #SystemClick(&Event, EvWindow);
 break;
 case inContent: // Click in content of a window
 #SelectWindow(EvWindow); // Activate window
 #SetPort(EvWindow); // Hook QuickDraw up
 break;
 case inDrag:
 #SelectWindow(EvWindow); // Activate 
 #SetPort(EvWindow); // Hook QuickDraw up 
 break;
 case inGoAway:  // Go-away handling
 break;
 case inGrow:  // Grow handling
 break;
// Add dispatches for other area types
 default:
 }
 }

/*
 *  - Handle keypress and command keys
 *     Handles edit command keys 
 */
do_key()
 {
 unsigned short ch;
 ch = (unsigned short)Event.message; // Isolate key codes
 if(Event.modifiers & cmdKey) // If command character
 do_menu(#MenuKey(ch)); // Try menu shortcut cmd
 }
// Stub functions
upd_wind(wp)
WindowPtr wp;
 {
 return(0);
 }
act_wind(wp)
WindowPtr wp;
 {
 return(0);
 }
deact_wind(wp)
WindowPtr wp;
 {
 return(0);
 }
find_wcb(wp)// Never one of our windows
WindowPtr wp;
 {
 return(0);
 }

MENU SUB-PROGRAM IN C

/*
 * TMenu.C - Handle menu selections for 
 * template program
 *
 *  (c) 1984, MacTutor  by Bob Denny
 */
#include<Templ.H>
/*
 * SETUP_MENU() - Initialize menu system 
 *
 * Fills in an array of menu handles.  Not     
*  used in this version of the program. 
 */
setup_menu()
 {
 #InitMenus();
 #InsertMenu(menus[APPLE] = (MenuHandle)#GetMenu(APPLE_ID), 0);
 #AddResMenu(menus[APPLE], ‘DRVR’);
 #InsertMenu(menus[FILE] = (MenuHandle)#GetMenu(FILE_ID), 0);
 #InsertMenu(menus[EDIT] = (MenuHandle)#GetMenu(EDIT_ID), 0);
 #InsertMenu(menus[OPTIONS] = (MenuHandle)#GetMenu(OPTIONS_ID), 0);
 #DrawMenuBar();
 }
 
/*
 * DO_MENU() - Handle menu selection
 *
 * Input:
 * Result longword from MenuSelect       
 *        or MenuKey
 */
do_menu(result)
unsigned result;
 {
 unsigned short menu_id; // Resource ID of selected menu
 unsigned short item_no; // Item number selected
 char item_name[64]; // Item name (for desk acc.)
 Ptr dp;// Dialog pointer for “about ...”
 unsigned short item_hit; // Dialog item that was hit 
 if(result == 0) // Just for safety with MenuKey
 return;// Ignore zero results
 menu_id = (short)#HiWord(result); // Use toolbox 
 item_no = (short)#LoWord(result);
 
 switch(menu_id)
 {
 case APPLE_ID: // “Apple” menu
 if(item_no > 1) // If desk accessory
 {
 #GetItem(menus[APPLE], item_no, item_name);
 #OpenDeskAcc(item_name);
 }
 else  // Our About ... dialog
 {
 dp = #GetNewDialog(ABOUT_ID, 0, -1); 
 // Bring in dialog to front
 #SetPort(dp); // Hook QuickDraw up to dialog
 #ModalDialog(0, &item_hit); // dialog item hit
 #DisposeDialog(dp); // Close & free heap 
 }
 break;

 case FILE_ID: // File menu
 if(item_no == FM_EXIT)
 #ExitToShell(); // Ugly exit
 break;
 
 case EDIT_ID:
 //
 // First we must hand off any   // desk-accessory edit commands.
 // Note the comments in Demo.H 
 // regarding implicit assumptions
 // in numbering items in Edit menu.
 //
 if(#SystemEdit(item_no - 1)) // Relies on item no.!!
 break;
 //
 // Do the requested edit function only      // if this is an editing 
window and there // is a window open.  For now, we have  // no windows, 
so we just return.
 //
 break;
 
 case OPTIONS_ID: // Options menu.
 switch(item_no)
 {
 case MM_MUSIC:
 play_tune();
 break;
 case MM_EDIT_WINDOW:
 edit_window();
 break;
 case MM_SCRAWL_WINDOW:
 scrawl_window();
 break;
 
 default:
 }
 break;
 
 default:
 }
 #HiliteMenu(0); // Turn off highlighted title
 }
// Stub functions
play_tune() // Make crude music -- demo driver 
 {
 return(0);
 }
edit_window()  // Create a new editing window
 {
 return(0);
 }
scrawl_window()  // Create a new “scrawling” window
 {
 return(0);
 }

Resource File

This is the RMAKER source for the Mac C template application. The dialog box will not come out right with the version of the RMAKER that I have. The \0D entries in the staticText item are supposed to be “hard” carriage returns in the text. Instead, they come out as “D”. To fix this, use the AlertDialog Editor on the file after building it to put the 2 carriage returns in and remove the “D”s. Perhaps RMAKER (or it’s successor) will work some day ...

The menu items for things that aren’t in the template (yet) have been dimmed. As things are filled in, you’ll have to edit this file to un-dim & thus activate the corresponding menu items. Note that the Edit menu is enabled to support SystemEdit editing in desk accessories.

* Templ.R  --  Resources for the 
*                     template program
*
*  (C) 1984, MacTech by R. B. Denny 

TemplRsrc
RSRCXXXX

TYPE WIND
  ,256
Please Wait ...
50 50 250 250
Visible GoAway
0
0

TYPE MENU
  ,1
\14
About Template ...
(-

  ,256
File
Quit

  ,257
Edit
(Can’t Undo
(-
Cut/X
Copy/C
Paste/V
Clear/D

  ,258
Options
(New Edit Window
(New Scrawl Window
(-
(Play a tune

TYPE DLOG
  ,256

54 145 203 376
Visible NoGoAway
1
0
256


TYPE DITL
  ,256
2

button
116 58 142 174
RESUME DEMO

staticText Disabled
9 9 105 228
This program was written as an example of native Macintosh ++ 
application programming in the C language, using Mac C. 
\0D \0D ++ 
Bob Denny            October, 1984

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
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 »

Price Scanner via MacPrices.net

Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
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
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more
New promo at Visible: Buy a new iPhone, get $...
Switch to Visible, and buy a new iPhone, and Visible will take $10 off their monthly Visible+ service for 24 months. Visible+ is normally $45 per month. With this promotion, the cost of Visible+ is... Read more
B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for $100 off Apple’s new MSRP, only $899. Free 1-2 day delivery is available to most US addresses. Their... Read more
Take advantage of Apple’s steep discounts on...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel 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
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
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.