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

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

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 up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
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

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.