TweetFollow Us on Twitter

MACINTOSH C CARBON

Demonstration Program LowEvents

Goto Contents

// *******************************************************************************************
// LowEvents.c                                                             CLASSIC EVENT MODEL
// *******************************************************************************************
// 
// This program contains a main event loop function, together with subsidiary functions which 
// perform nominal handling only of low-level and Operating System events.  It opens a window 
// in which the types of all received low-level and Operating System events are displayed.  It 
// terminates when the user clicks the window's close box.
//
// Event handling is only nominal in this program because its main purpose is to demonstrate
// the basics of an application's main event loop.  Programs in later chapters demonstrate
// the full gamut of individual event handling. 
//
// The program utilises the following resources:
//
// o  A 'plst' resource.
//
// o  A 'WIND' resource (purgeable).
//
// o  A 'SIZE' resource with the acceptSuspendResumeEvents, canBackground,
//    doesActivateOnFGSwitch, and isHighLevelEventAware flags set.
//  
// *******************************************************************************************

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

#include <Carbon.h>

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

#define rWindowResource  128

#define topLeft(r)  (((Point *) &(r))[0])
#define botRight(r) (((Point *) &(r))[1])

// .......................................................................... global variables

Boolean   gDone;
RgnHandle gCursorRegionHdl;

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

void  main            (void);
void  doPreliminaries (void);
void  doNewWindow     (void);
void  eventLoop       (void);
void  doEvents        (EventRecord *);
void  doMouseDown     (EventRecord *);
void  doUpdate        (EventRecord *);
void  doOSEvent       (EventRecord *);
void  drawEventString (Str255);
void  doAdjustCursor  (WindowRef);

// ************************************************************************************** main

void  main(void)
{
  doPreliminaries();
  doNewWindow();
  eventLoop();
}

// *************************************************************************** doPreliminaries

void  doPreliminaries(void)
{
  MoreMasterPointers(48);

  InitCursor();
  FlushEvents(everyEvent,0);
}

// ******************************************************************************* doNewWindow

void  doNewWindow(void)
{
  WindowRef windowRef;

  if(!(windowRef = GetNewCWindow(rWindowResource,NULL,(WindowRef) -1)))
  {
    SysBeep(10);
    ExitToShell();
  }

  SetPortWindowPort(windowRef);
  TextSize(10);
}

// ********************************************************************************* eventLoop

void  eventLoop(void)
{
  EventRecord eventStructure;
  Boolean     gotEvent;
  
  gDone = false;
  gCursorRegionHdl = NewRgn();
  doAdjustCursor(FrontWindow());
  
  while(!gDone)
  {
    gotEvent = WaitNextEvent(everyEvent,&eventStructure,180,gCursorRegionHdl);
    if(gotEvent)
      doEvents(&eventStructure);
    else
    {
      if(eventStructure.what == nullEvent)
        drawEventString("\p   o nullEvent");
    }
  }
}

// ********************************************************************************** doEvents

void  doEvents(EventRecord *eventStrucPtr)
{
  switch(eventStrucPtr->what)
  {
    case mouseDown:
      drawEventString("\p   o mouseDown");
      doMouseDown(eventStrucPtr);
      break;

    case mouseUp:
      drawEventString("\p   o mouseUp");
      break;

    case keyDown:
      drawEventString("\p   o keyDown");
      break;

    case autoKey:
      drawEventString("\p   o autoKey");
      break;

    case updateEvt:
      drawEventString("\p   o updateEvt");
      doUpdate(eventStrucPtr);
      break;

    case activateEvt:
      drawEventString("\p   o activateEvt");
      break;

    case osEvt:
      drawEventString("\p   o osEvt - ");
      doOSEvent(eventStrucPtr);
      break;
  }
}
  
// ******************************************************************************* doMouseDown

void  doMouseDown(EventRecord *eventStrucPtr)
{
  WindowPartCode partCode;
  WindowRef      windowRef;
  
  partCode = FindWindow(eventStrucPtr->where,&windowRef);
  
  switch(partCode)
  {
    case inContent:
      if(windowRef != FrontWindow())
        SelectWindow(windowRef);
      break;

    case inDrag:
      DragWindow(windowRef,eventStrucPtr->where,NULL);
      doAdjustCursor(windowRef);
      break;

    case inGoAway:
      if(TrackGoAway(windowRef,eventStrucPtr->where))
        gDone = true;
      break;
  }
}

// ********************************************************************************** doUpdate

void  doUpdate(EventRecord *eventStrucPtr)
{
  BeginUpdate((WindowRef) eventStrucPtr->message);
  EndUpdate((WindowRef) eventStrucPtr->message);
}

// ********************************************************************************* doOSEvent

void  doOSEvent(EventRecord *eventStrucPtr)
{
  Cursor arrow;

  switch((eventStrucPtr->message >> 24) & 0x000000FF)
  {
    case suspendResumeMessage:
      if((eventStrucPtr->message & resumeFlag) == 1)
      {
        SetCursor(GetQDGlobalsArrow(&arrow));
        DrawString("\pResume");
      }
      else
        DrawString("\pSuspend");
      break;

    case mouseMovedMessage:
      doAdjustCursor(FrontWindow());
      DrawString("\pMouse-moved");
      break;
  }
}

// *************************************************************************** drawEventString

void  drawEventString(Str255 eventString)
{
  WindowRef windowRef;
  RgnHandle tempRegion;
  Rect      portRect;

  windowRef = FrontWindow();
  tempRegion = NewRgn();

  GetWindowPortBounds(windowRef,&portRect);
  ScrollRect(&portRect,0,-15,tempRegion);
  DisposeRgn(tempRegion);

  MoveTo(8,340);
  DrawString(eventString);
}

// **************************************************************************** doAdjustCursor

void  doAdjustCursor(WindowRef windowRef)
{
  RgnHandle myArrowRegion;
  RgnHandle myIBeamRegion;
  Rect      cursorRect;
  Point     mousePt;
  Cursor    arrow;
  
  myArrowRegion = NewRgn();
  myIBeamRegion = NewRgn();
  SetRectRgn(myArrowRegion,-32768,-32768,32767,32767);
  
  GetWindowPortBounds(windowRef,&cursorRect);
  SetPortWindowPort(windowRef);
  LocalToGlobal(&topLeft(cursorRect));
  LocalToGlobal(&botRight(cursorRect));  

  RectRgn(myIBeamRegion,&cursorRect);
  DiffRgn(myArrowRegion,myIBeamRegion,myArrowRegion);
  
  GetGlobalMouse(&mousePt);
  if(PtInRgn(mousePt,myIBeamRegion))
  {
    SetCursor(*(GetCursor(iBeamCursor)));
    CopyRgn(myIBeamRegion,gCursorRegionHdl);
  }
  else
  {
    SetCursor(GetQDGlobalsArrow(&arrow));
    CopyRgn(myArrowRegion,gCursorRegionHdl);
  }
  
  DisposeRgn(myArrowRegion);
  DisposeRgn(myIBeamRegion);
}

// *******************************************************************************************

Demonstration Program LowEvents Comments

When the program is run, the user should move the mouse cursor inside and outside the window,
click the mouse inside and outside the window, drag the window, and press and release keyboard
keys, noting the types of events generated by these actions as printed on the scrolling display
inside the window.

The user should also note:

o The basic window deactivation and activation that occurs when the mouse is clicked outside,
  and then inside the window.

o That when another window is positioned over part of the program's window and then dragged to
  expose more of the program's window, an update event is received on Mac OS 8/9 but not on 
  Mac OS X.

The program may be terminated by a click in the window's close box.

The general "flow" of the program is illustrated in the flow chart at Fig 4.

defines

rWindowResource establishes a constant for the ID of the 'WIND' resource.

The remaining two lines define two common macros.  The first converts the top and left fields
of a Rect to a Point.  The second converts the bottom and right field of a Rect to a Point.

Global Variables

The global variable gDone controls the termination of the main event loop and thus of the
program.  gCursorRegionHdl will be assigned the handle to a region to be passed in the mouseRgn
parameter of the WaitNextEvent function.

main

The main function calls the functions for performing certain preliminary actions common to most
applications and for creating the window.  It then calls the function containing the main event
loop.

doPreliminaries

doPreliminaries is the standard "do prelimaries" function which will be used in all subsequent
Classic event model demonstration programs.

FlushEvents empties the Operating System event queue of any low-level events left unprocessed
by another application, for example, any mouse-down or keyboard events that the user may have
entered while this program was being launched.

doNewWindow

The function doNewWindow opens the window in which the types of low-level and Operating System
events will be printed as they occur.  The 'WIND' resource passed as the first parameter
specifies that the window has a close box and a drag (title) bar.  The window's graphics port
is set as the current port for drawing and the text size is set to 10 points.

eventLoop

eventLoop is the main event loop.

The global variable gDone is set to false before the event loop is entered.  This variable will
be set to true when the user clicks on the window's close box.  The event loop (the while
loop) terminates when gDone is set to true.

The calls to NewRgn and doAdjustCursor have to do with the generation of mouse-moved events. 
The NewRgn call allocates storage for a Region object and initialises the contents of the
region to make it an empty region.  As will be seen, this first call to doAdjustCursor defines
two regions (one for the arrow cursor and one for the I-Beam cursor) and copies the handle to
one of them (depending on the current position of the mouse cursor) to the global variable
gCursorRegionHandle.

In the call to WaitNextEvent:

o The event mask everyEvent ensures that all types of low-level and Operating System events
  will be returned to the application (except keyUp events, which are masked out by the system
  event mask).

o eventStructure is the EventRecord structure which, when WaitNextEvent returns, will contain
  information about the event.

o 180 represents the number of ticks for which the application agrees to relinquish the
  processor if no events are pending for it.  180 ticks equates to about three seconds.

o If the cursor is now not within the region passed in the cursorRegion parameter, a
  mouse-moved event will be generated immediately.

WaitNextEvent returns 1 if an event was pending, otherwise it returns 0.  If an event was
pending, the program branches to doEvent to determine the type of event and handle the event
according to its type.  If 0 is returned, and if the what field of the event structure contains
nullEvent, "nullEvent" is printed in the window.  This will occur every three seconds in the
absence of other events.

doEvents

doEvents handles some events to finality and performs initial handling of others.

On return from WaitNextEvent, the what field of the event structure contains an unsigned short
integer which indicates the type of event received.  The doEvent function isolates the type of
event and switches according to that type.

In this demonstration, the action taken in every case is to print the type of event in the
window.  In addition, and in the case of mouse-down, update, and Operating System events only,
calls to individual event handling functions are made.

Note that, in the case of an Operating System event, doEvent will only print "osEvt - " in the
window.  At this stage, the program has not yet established whether the event is a suspend,
resume or mouse-moved event.

Note also that the inclusion of the key-up event handling would be pointless, since key-up
events are masked out by the Operating System.

doMouseDown

The function doMouseDown handles mouse-down events to completion.

FindWindow is called to get a reference to the window in which the event occurred and a part
code which indicates the part of that window in which the mouse-down occurred.  The function
then switches according to that part code.

The inContent case deals with a mouse-down in a window's content region.  FrontWindow returns a
reference to the frontmost window.  If this is not the same as the reference in the event
structure's message field, SelectWindow is called to generate activate events and to perform
basic window activation and deactivation.  (Actually, SelectWindow will never be called in this
demonstration because the program only opens one window, which is always the front window.)

The inDrag case deals with a mouse-down in the window's title bar (Mac OS 8/9) or title bar
(Mac OS X).  In this case, control is handed over to DragWindow, which tracks the mouse and
drags the window according to mouse movement until the mouse button is released.  A bounding
rectangle limiting the area in which the window can be dragged may be passed in DragWindow's
third parameter. In Carbon, NULL may also be passed in this parameter.  This has the effect of
setting the third parameter to the bounding box of the "desktop region" (also known as the
"gray region").  The desktop region is the region below the menu bar, including all screen real
estate in a system equipped with multiple monitors.

The regions controlling the generation of mouse-moved events are defined in global coordinates. 
The region for the I-Beam cursor is based on the window's graphics port's bounding rectangle. 
Accordingly, when the window is moved, the new location of the port rectangle, in global
coordinates, must be re-calculated so that the arrow cursor and I-Beam cursor regions may be
re-defined.  The call to doAdjustCursor re-defines these regions for the new window location
and copies the handle to one of them, depending on the current location of the mouse cursor, to
the global variable gCursorRegionHandle.  (Note that this call to doAdjustCursor will also be
required, for the same reason, when a window is re-sized or zoomed.)

The inGoAway case deals with the case of a mouse-down in the close box (Mac OS 8/9) or close
button (Mac OS X).  In this case, control is handed over to TrackGoAway, which tracks the mouse
while the mouse button remains down.  When the button is released, TrackGoAway returns true if
the cursor is still inside the close box, in which case the global variable gDone is set to
true, terminating the event loop and the program.

doUpdate

The function doUpdate handles update events to completion.

Although no window updating is performed by this program, it is nonetheless necessary to call
BeginUpdate because, amongst other things, BeginUpdate clears the update region, thus
preventing the generation of an unending stream of update events.  The call to EndUpdate always
concludes a call to BeginUpdate, undoing the results of the visible/update region manipulations
of the latter.

doOSEvent

doOSEvent first determines whether the Operating System event passed to it is a suspend/resume
event or a mouse-moved event by examining bits 24-31 of the message field.  It then switches
according to that determination.

In the case of a suspend/resume event, a further examination of the message field establishes
whether the event was a suspend event or a resume event.  In the case of a resume event, the
call to SetCursor ensures that the cursor will be set to the arrow cursor shape when the
application comes to the foreground.  (With regard to the call to GetQDGlobalsArrow, see
QuickDraw Globals and Accessor Functions, below.)

In the case of a mouse-moved event (which occurs when the mouse cursor has moved outside the
region whose handle is currently being passed in WaitNextEvent's mouseRgn parameter),
doAdjustCursor is called to change the handle passed in the mouseRgn parameter according to the
current location of the mouse.

drawEventString

drawEventString is incidental to the demonstration.  It simply prints text in the window
indicating when the various types of events are received.  ScrollRect scrolls the contents of
the current graphics port within the rectangle specified in the first parameter.  The second
parameter specifies the number of pixels to be scrolled to the right and the third parameter
specifies the number of pixels to scroll vertically, in this case 15 up.

doAdjustCursor

doAdjustCursor's primary purpose in this particular demonstration is to force the generation of
mouse-moved events.  The fact that it also changes the cursor shape simply reflects the fact
that changing the cursor shape is usually the sole reason for generating mouse-moved events in
the first place.

Basically, the function establishes two regions (the calls to NewRgn), one describing the
content area of the window (in global coordinates) and the other everything outside that.  The
location of the cursor, in global coordinates, is then ascertained by the call to
GetGlobalMouse.  If the cursor is in the content area of the window (the I-Beam region), the
cursor is set to the I-Beam shape and the handle to the I-Beam region is copied to the global
variable passed in the mouseRgn parameter in the WaitNextEvent call in the eventLoop function. 
If the cursor is in the other region (the arrow region), the cursor is set to the normal arrow
shape and the arrow region is copied to the global variable passed in the mouseRgn parameter.

GetCursor reads in the system 'CURS' resource specified by the constant iBeamCursor and returns
a handle to the 68-byte Cursor structure created by the call.  The parameter for a SetCursor
call is required to be the address of a Cursor structure.  Dereferencing the handle once
provides that address.

WaitNextEvent, of course, returns a mouse-moved event only when the cursor moves outside the
"current" region, the handle to which is passed in the mouseRgn parameter of the WaitNextEvent
call.  Only one mouse-moved event, rather than a stream of mouse-moved events, will be
generated when the cursor is moved outside the "current" region because: 

o The mouse-moved event will cause doAdjustCursor to be called.

o doAdjustCursor will thus reset the "current" region to the region in which the cursor is now
  located.

The cursor and cursor adjustment aspects, as opposed to the region-swapping aspects, of the
doAdjustCursor function are incidental to the demonstration.  These aspects are addressed in
more detail at Chapter 13.

QUICKDRAW GLOBALS AND ACCESSOR FUNCTIONS

An accessor function pertaining to application QuickDraw global variables
(GetQDGlobalsArrow) is used in this demonstration.

QuickDraw global variables are stored as part of your application's global variables.
In Carbon, accessor functions are provided, and must be used, to access the data in 
these globals.
 
The accessor functions are as follows:

CGrafPtr  GetQDGlobalsThePort(void);             // Gets pointer to current graphics port.
Cursor*   GetQDGlobalsArrow(Cursor *arrow);      // Gets standard cursor arrow shape.
void      SetQDGlobalsArrow(const Cursor *arrow);  // Sets standard cursor arrow shape.
Pattern*  GetQDGlobalsDarkGray(Pattern *dkGray);   // Gets pre-defined dark gray pattern.
Pattern*  GetQDGlobalsLightGray(Pattern *ltGray);  // Gets pre-defined light gray pattern.
Pattern*  GetQDGlobalsGray(Pattern *gray);         // Gets pre-defined gray pattern.
Pattern*  GetQDGlobalsBlack(Pattern *black);       // Gets pre-defined black pattern.
Pattern*  GetQDGlobalsWhite(Pattern *white);       // Gets pre-defined e white pattern.
long      GetQDGlobalsRandomSeed(void);            // Get random number generator seed.
void      SetQDGlobalsRandomSeed(long randomSeed); // Set random number generator seed.
BitMap*   GetQDGlobalsScreenBits(BitMap *screenBits); // screenBits.bounds contains
                                                      // rectangle enclosing main screen.
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Seven Knights Idle Adventure drafts in a...
Seven Knights Idle Adventure is opening up more stages, passing the 15k mark, and players may find themselves in need of more help to clear these higher stages. Well, the cavalry has arrived with the introduction of the Legendary Hero Iris, as... | Read more »
AFK Arena celebrates five years of 100 m...
Lilith Games is quite the behemoth when it comes to mobile games, with Rise of Kingdom and Dislyte firmly planting them as a bit name. Also up there is AFK Arena, which is celebrating a double whammy of its 5th anniversary, as well as blazing past... | Read more »
Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
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 »

Price Scanner via MacPrices.net

Apple introduces the new M4-powered 11-inch a...
Today, Apple revealed the new 2024 M4 iPad Pro series, boasting a surprisingly thin and light design that pushes the boundaries of portability and performance. Offered in silver and space black... Read more
Apple introduces the new 2024 11-inch and 13-...
Apple has unveiled the revamped 11-inch and brand-new 13-inch iPad Air models, upgraded with the M2 chip. Marking the first time it’s offered in two sizes, the 11-inch iPad Air retains its super-... Read more
Apple discontinues 9th-gen iPad, drops prices...
With today’s introduction of the new 2024 iPad Airs and iPad Pros, Apple has (finally) discontinued the older 9th-generation iPad with a home button. In response, they also dropped prices on 10th-... Read more
Apple AirPods on sale for record-low prices t...
Best Buy has Apple AirPods on sale for record-low prices today starting at only $79. Buy online and choose free shipping or free local store pickup (if available). Sale price for online orders only,... Read more
13-inch M3 MacBook Airs on sale for $100 off...
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, along with Amazon’s, are the lowest currently available for new 13″... Read more
Amazon is offering a $100 discount on every 1...
Amazon has every configuration and color of Apple’s 13″ M3 MacBook Air on sale for $100 off MSRP, now starting at $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD): $999 $100 off... Read more
Sunday Sale: Take $150 off every 15-inch M3 M...
Amazon is now offering a $150 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1149 for models with 8GB of RAM and 256GB of storage: – 15″ M3 MacBook... Read more
Apple’s 24-inch M3 iMacs are on sale for $150...
Amazon is offering a $150 discount on Apple’s new M3-powered 24″ iMacs. Prices start at $1149 for models with 8GB of RAM and 256GB of storage: – 24″ M3 iMac/8-core GPU/8GB/256GB: $1149.99, $150 off... Read more
Verizon has Apple AirPods on sale this weeken...
Verizon has Apple AirPods on sale for up to 31% off MSRP on their online store this weekend. Their prices are the lowest price available for AirPods from any Apple retailer. Verizon service is not... Read more
Apple has 15-inch M2 MacBook Airs available s...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more

Jobs Board

Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL 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.