TweetFollow Us on Twitter

MACINTOSH C

Demonstration Program

Go to Contents
// ××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××
// SysMemRes.c
// ××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××
//
// This program:
//
// „  Initialises the system software managers.
//
// „  Creates a nonrelocatable block of memory for a window structure.
//
// „  Loads a window template ('WIND') resource and creates a window.
//
// „  Loads a purgeable 'PICT' resource and a non-purgeable 'STR ' resource and draws
//    them in the window.
//
// „  Checks if any error codes were generated as a result of calls to to Memory Manager 
//    and Resource Manager functions.
//
// „  Terminates when the mouse button is clicked.
//
// ××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

// ............................................................................. includes

#include <MacMemory.h>
#include <Resources.h>
#include <Sound.h>
#include <TextUtils.h>

// .............................................................................. defines

#define rWindowResourceID    128
#define rStringResourceID    128
#define rPictureResourceID   128

// .................................................................. function prototypes

void  main                 (void);
void  doInitManagers       (void);
void  doNewWindow          (void);
void  doDrawPictAndString  (void);

// ××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××× main

void  main(void)
{  
  doInitManagers();
  doNewWindow();
  doDrawPictAndString();
  while(!Button()) ;
}

// ××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××× initManagers

void  doInitManagers(void)
{
  MaxApplZone();
  MoreMasters();

  InitGraf(&qd.thePort);
  InitFonts();
  InitWindows();
  InitMenus();
  TEInit();
  InitDialogs(NULL);

  InitCursor();
}

// ×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××× doNewWindow

void  doNewWindow(void)
{
  WindowPtr  windowPtr;
  Ptr        windowRecPtr;

  windowRecPtr = NewPtr(sizeof(WindowRecord));
  if(windowRecPtr == NULL)
  {
    SysBeep(10);
    ExitToShell();
  }

  windowPtr = GetNewCWindow(rWindowResourceID,windowRecPtr,(WindowPtr) -1);
  if(windowPtr == NULL)
  {
    SysBeep(10);
    ExitToShell();
  }

  SetPort(windowPtr);
  TextFont(systemFont);
  
}

// ×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××× doDrawPictAndString

void  doDrawPictAndString(void)
{
  PicHandle      pictureHdl;
  StringHandle   stringHdl;
  Rect           pictureRect;
  SInt16         resourceError;
  OSErr          memoryError;      

  pictureHdl = GetPicture(rPictureResourceID);
  if(pictureHdl == NULL)
  {
    SysBeep(10);
    ExitToShell();
  }

  SetRect(&pictureRect,148,25,353,170);

  HNoPurge((Handle) pictureHdl);
  DrawPicture(pictureHdl,&pictureRect);
  HPurge((Handle) pictureHdl);

  stringHdl = GetString(rStringResourceID);
  if(stringHdl == NULL)
  {
    SysBeep(10);
    ExitToShell();
  }

  MoveTo(105,210);
  DrawString(*stringHdl);

  ReleaseResource((Handle) pictureHdl);
  ReleaseResource((Handle) stringHdl);

  resourceError = ResError();
  if(resourceError == noErr)
  {
    MoveTo(162,240);
    DrawString("\pNo Resource Manager errors");
  }  

  memoryError = MemError();
  if(memoryError == noErr)
  {
    MoveTo(165,255);
    DrawString("\pNo Memory Manager errors");
  }  
}

// ××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

Demonstration Program Comments

#include

The following explains the inclusion of each of the specified header files:

MacMemory.h Prototypes: MaxApplZone  NewPtr  HNoPurge  HPurge  MemError

Resources.h Prototypes: ReleaseResource  ResError

Sound.h     Prototypes: SysBeep

            Sound.h itself includes Dialogs.h, which contains:
            Prototypes: InitDialogs

            Dialogs.h also includes TextEdit.h, which contains
            Prototypes: TEInit

            Dialogs.h also includes MacWindows.h, which contains:
            Prototypes: InitWindows  GetNewCWindow
            Data Types: WindowRecord

            MacWindows.h itself includes Events.h, which contains:
            Prototypes: Button

            Dialogs.h also includes Controls.h, which includes Menus.h, which contains:
            Prototypes: InitMenus

            Menus.h itself includes MacTypes.h, which contains:
            DataTypes:  SInt16, Ptr  StringHandle  Rect  OSErr  Handle
            Constants:  noErr

            Menus.h also includes Fonts.h, which contains:
            Prototypes: InitFonts
            Constants:  systemFont

            Menus.h also includes Quickdraw.h, which contains:
            Prototypes: InitGraf  InitCursor  SetPort  SetRect  DrawPicture
                          MoveTo  GetPicture
            Data Types: WindowPtr  PicHandle
            QuickDraw Global Variable:  thePort

            Quickdraw.h itself includes QuickdrawText.h, which contains:
            Prototypes: TextFont  DrawString

            Menus.h also includes Processes.h, which contains:
            Prototypes: ExitToShell

TextUtils.h Prototypes: GetString

#define

Constants are established for the resource IDs of the 'WIND', 'PICT' and 'STR '
resources.

main

The main function calls the application-defined functions which initialise the
system software managers, create a window, and draw a picture and text in the window.  It
then waits for a button click before terminating the program.

doInitManagers

doInitManagers grows the application heap, creates a block of master pointers,
initialises the system software managers, and sets the cursor to the standard arrow
shape.

Note that the function name is somewhat of a misnomer in that it does more than
initialise the system software managers.  However, since growing the heap, creating
additional master pointer blocks, and setting the standard arrow cursor shape are
invariably part of an application's setting up process, it is convenient to attend to
those matters within the doInitManagers function.  This practice will continue in all
other demonstration programs.

The call to MaxApplZone is really not required for this simple program.  However, it
should be the first call in any serious application.  The call grows the heap immediately
to the maximum permissible size, assisting in the prevention of heap fragmentation,
reducing the number of blocks which the Memory Manager has to purge when satisfying a
memory request and speeding up memory allocation operations.

The call to MoreMasters to allocate a block of master pointers is really not required in
this simple program because the Operating System automatically allocates one block of
master pointers at application launch.  However, in larger applications where more than
64 master pointers are required, the call, or calls, to MoreMasters should be made here
so that all master pointer (nonrelocatable) blocks are located at the bottom of the heap. 
This will assist in preventing heap fragmentation.

The next six lines initialise certain system software managers.  Not all of the data
structures and variables inititialised by these calls will be used by this simple
program; however, any serious application will require the full initialisation shown.  It
is also relevant that some managers require the use of information in other managers, so
those other managers need to be initialised at least for that purpose.  Some explanatory
notes on the various calls are as follows:

*  InitGraf initialises the QuickDraw global variables.  The first element in the
   QuickDraw global data area is a pointer (thePort) to the current graphics port.
   Because it is the first QuickDraw global, passing its address to InitGraf tells 
   QuickDraw where all the other QuickDraw globals are located.  Other QuickDraw globals
   initialised by InitGraf are:

*  The pattern variables qd.white, qd.black, qd.gray, qd.ltGray, qd.dkGray.

*  qd.arrow, which contains the standard cursor arrow shape and which can be passed as an
   argument to QuickDraw's cursor functions.

*  qd.screenBits, a data structure which describes the main screen.  The field 
   screenBits.bounds contains a rectangle which encloses the main screen.

*  qd.randSeed, which is used to seed the random number generator.

Note:  The header file Quickdraw.h defines the following data type:

     struct QDGlobals
     {
       char      privates[76];
       long      randSeed;
       BitMap    screenBits;
       Cursor    arrow;
       Pattern   dkGray;
       Pattern   ltGray;
       Pattern   gray;
       Pattern   black;
       Pattern   white;
       GrafPtr   thePort;
     };
     typedef struct QDGlobals QDGlobals;
     extern QDGlobals qd;

In the 680x0 environment, the runtime libraries define the QuickDraw global variable qd. 
There is no need for your application to do this.

*  InitFont initialises the Font Manager and loads the system font into memory.  Since
   the Window Manager uses the Font Manager to draw the window's title, etc., InitFonts
   must be called before InitWindows. Also, it must be called after InitGraf.

*  InitWindows initialises the Window Manager port.  It must be called after InitGraf and
   InitFonts.  It draws the familiar rounded rectangle desktop with an empty menu bar at
   the top.  The fill pattern used is the resource whose resource ID is represented by 
   the constant deskPatID.  (If a different fill pattern is required, it can be specified
   in the application's resource file.)  The call establishes a nonrelocatable block (the
   Window Manager port) in the application heap.

*  InitMenus allocates heap storage for the menu list and draws an empty menu bar.  (For
   some unknown reason, InitWindows and InitMenus both draw the menu bar.)  InitMenus 
   must be called after InitGraf, InitFonts and InitWindows.

*  TEInit initialises TextEdit, the Text editing manager, by allocating an internal 
   handle for the TextEdit scrap (not the same as the "desk scrap" maintained by the Desk
   Manager).  It should be called even if the application does not explicitly use 
   TextEdit functions, since it ensures that dialog boxes and alert boxes work correctly.

*  InitDialogs initialises the Dialog Manager and optionally installs a function to get 
   control after a fatal system error.  It installs the standard sound procedure (for
   alerts) and sets all text replacement parameters to empty strings (see the function
   ParamText).

InitCursor sets the cursor shape to the standard arrow cursor and sets the cursor level
to 0, making it visible.  (The 68-byte Cursor structure for the standard arrow cursor can
be found in the QuickDraw data area.)

doNewWindow

doNewWindow creates a window.

NewPtr is used to allocate a nonrelocatable block of memory for the window structure.  If
the call is not successful, the system alert sound is played and the program is
terminated by a call to ExitToShell, which releases the heap and hands control to the
Finder.  (Note that error handling here, and in the rest of the program, is thus somewhat
rudimentary.  Note also that SysBeep's parameter is nowadays ignored, but must be
included for historical reasons.)

The call to GetNewCWindow creates a window using the 'WIND' template resource  specified
in the first parameter, and using the pointer to the nonrelocatable block already
allocated for the window structure as the second parameter.  (The third parameter tells
the Window Manager to open the window in front of all other windows.)  The type, size,
location, appearance, title and visibility of the window are all established by the
'WIND' resource.

Recall that, as soon as the data from the 'WIND' template resource is copied to the
window structure during the creation of the window, the nonrelocatable block occupied by
the template will automatically be marked as purgeable.

The call to SetPort makes the new window's graphics port the current port for drawing
operations.  The call to TextFont at sets the font for that port to the standard system
default font (Chicago or Charcoal, depending on the setting in the Appearance control
panel).

doDrawPictAndString

doDrawPictAndString draws a picture and some text strings in the window.

GetPicture reads in the 'PICT' resource corresponding to the ID specified in the
GetPicture call.  If the call is not successful, the system alert sound is played and the
program terminates.

The SetRect call assigns values to the left, top, right and bottom fields of a Rect
variable.  This Rect is required for a later call to DrawPicture.

The basic rules applying to the use of purgeable resources are to load it, immediately
make it unpurgeable, use it immediately, and immediately make it purgeable.  Accordingly,
the HNoPurge call makes the relocatable block occupied by the resource unpurgeable, the
DrawPicture call draws the picture in the window's graphics port, and the HPurge call
makes the relocatable block purgeable again.

Note that, because HNoPurge and HPurge expect a parameter of type Handle, pictureHdl (a
variable of type PicHandle) must be cast to a variable of type Handle.

GetString then reads in the specified 'STR ' resource.  Once again, if the call is not
successful, the system alert sound is played and the program terminates.  MoveTo moves
the graphics "pen" to an appropriate position before DrawString draws the string in the
window's graphics port.  (Since the 'STR ' resource, unlike the 'PICT' resource, does not
have the purgeable bit set, there is no requirement to take the precaution of a call to
HNoPurge in this case.)

Note the parameter in the call to DrawString.  stringHdl, like any handle, is a pointer
to a pointer.  It contains the address of a master pointer which, in turn, contains the
address of the data.  Dereferencing the handle once, therefore, get the required
parameter for DrawString, which is a pointer to a string.

The calls to ReleaseResource release the 'PICT' and 'STR ' resources.  These calls
release the memory occupied by the resources and set the associated handles in the
resource map in memory to NULL.

The ResError call returns the error code of the most recent resource-related operation. 
If the call returns noErr (indicating that no error occurred as a result of the most
recent call by a Resource Manager function), some advisory text is drawn in the graphics
port.

The next six lines examine the result of the most recent call to a memory manager
function and draw some advisory text if no error occurred as a result of that call.

Note that the last two calls to DrawString utilise "hard-coded" strings.  This sort of
thing is discouraged in the Macintosh programming environment.  Such strings should
ordinarily be stored in a 'STR#' (string list) resource rather than hard-coded into the
source code.  The \p token causes the compiler to compile these strings as Pascal
strings.

PASCAL STRINGS
As stated in the Preface, when it comes to the system software, the 
ghost of the Pascal language forever haunts the C programmer.  For example, a 
great many system software functions take Pascal strings as a required 
parameter, and some functions return Pascal strings.

Pascal and C strings differ in their formats.  A C string comprises the 
characters followed by a terminating 0 (or NULL byte):

+---+---+---+---+---+---+---+---+---+---+
| M | Y |   | S | T | R | I | N | G | 0 |
+---+---+---+---+---+---+---+---+---+---+

In a Pascal string, the first byte contains the length of the string, and the 
characters
follow that byte:

+---+---+---+---+---+---+---+---+---+---+
| 9 | M | Y |   | S | T | R | I | N | G |
+---+---+---+---+---+---+---+---+---+---+

Not surprisingly, then, Pascal strings are often referred to as 
"length-prefixed" strings.

In Chapter 3, you will encounter the data type Str255.  Str255 is the C name 
for a Pascal-style string capable of holding up to 255 characters.  As you 
would expect, the first byte of a Str255 holds the length of the string and 
the following bytes hold the characters of the string.

Utilizing 256 bytes for a string will simply waste memory in many cases.  
Accordingly, the header file Types.h defines the additional types Str63, 
Str32, Str31, Str27, and Str15, as well as the Str255 type:-

    typedef unsigned char Str255[256];
    typedef unsigned char Str63[64];
    typedef unsigned char Str32[33];
    typedef unsigned char Str31[32];
    typedef unsigned char Str27[28];
    typedef unsigned char Str15[16];
    
Note, then, that a variable of type Str255 holds the address of an array of 
256 elements, each element being one byte long.

As an aside, in some cases you may want to use C strings, and use standard C 
library functions such as strlen, strcpy, etc., to manipulate them.  
Accordingly, be aware that functions exist (C2PStr, P2CStr) to convert a 
string from one format to the other.

You may wish to make a "working" copy of the SysMemRes demonstration program 
file package and, using the working copy of the source code file SysMemRes.c, 
replace the function doDrawPictAndString with the following, compile-link-run, 
and note the way the second and third strings appear in the window.

    void  doDrawPictAndString(void)
    {
      Str255  string1 = "\pIs this a Pascal string I see before me?";
      Str255  string2 = "Is this a Pascal string I see before me?";
      Str255  string3 = "%s this a Pascal string I see before me?";
      Str255  string4;
      SInt16  a;

      // Draw string1    

      MoveTo(30,100);
      DrawString(string1);

      // Change the length byte of string1 and redraw

      string1[0] = (char) 23;
      MoveTo(30,120);
      DrawString(string1);

      // Leave the \p token out at your peril
      // I (ASCII code 73) is now interpreted as the length byte

      MoveTo(30,140);
      DrawString(string2);

      // More peril:-  % (ASCII code 37) is now the length byte

      MoveTo(30,160);
      DrawString(string3);

      // A hand-built Pascal string

      for(a=1;a<27;a++)
        string4[a] = (char) a + 64;

      string4[0] = (char) 26;

      MoveTo(30,180);
      DrawString(string4);

      // But is there a Mac OS function to draw the C strings correctly?

      MoveTo(30,200);
      DrawText(string2,0,40);  // Look it up in your on-line reference
    }
    

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasnā€™t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, donā€™t remind me I could currently buy him this month Iā€™m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly ā€œborrowedā€ many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13ā€³ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. Thatā€™s $110 off MSRP, and itā€™s the lowest price weā€™ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13ā€³ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Appleā€™s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Appleā€™s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
Weā€™ve updated our iPhone Price Tracker with the latest carrier deals on Appleā€™s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobileā€™s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobileā€™s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13ā€³ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Appleā€™s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16ā€³ and 14ā€³ MacBook Pros along with 13ā€³ and 15ā€³ MacBook... Read more
Every model of Appleā€™s 13-inch M3 MacBook Air...
Best Buy has Apple 13ā€³ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13ā€³ M3 MacBook Airs among... Read more

Jobs Board

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
DMR Technician - *Apple* /iOS Systems - Haml...
ā€¦relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, 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
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.