TweetFollow Us on Twitter

Cursor Control 2
Volume Number:6
Issue Number:9
Column Tag:C Workshop

Related Info: Quickdraw

Cursor Control

By Robert S. T. Gibson, Ontario, Canada

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

[Robert S. T. Gibson is a Senior Software Engineer at Atryx Software Design in Canada]

Although it is not suggested by anyone who follows the Macintosh user interface, it is occasionally necessary for a program to change or restrict the cursor position. Some programs move the cursor to lock it into a grid, some restrict the cursor to a specific region, and others (usually games) allow it to wrap around the screen. Games sometimes read the cursor position, compare it to the middle of the screen, and then move the cursor to the screen’s center to keep it from reaching the edge.

Cursor tracking is maintained by many system globals. The three we are interested in, however, are MTemp, RawMouse, Mouse, and CrsrNew (see Figure 1).

It is often dangerous to change the System’s low-memory globals if you don’t know their exact effects on your system.

As always, there is a right way and a wrong way to do this. I’ll skip the wrong way and get right to what I believe to be the correct way. The C techniques used here can easily be adapted into other programming languages.

It is a relatively simple task to set the mouse position, but it requires a bit of insight into how the System keeps control.

Figure 1. Mouse Globals

System Control

Operation of the mouse depends on two routines that are called during interrupts. The first routine simply sets the global variable CrsrNew to true if the mouse position has changed. The second routine is a vertical retrace (VBL) task, which checks the value of CrsrNew and draws the cursor in the new position if the value is true.

Providing CrsrNew is set, each time the VBL task is executed, it draws the cursor and copies the value of MTemp, the new location of the mouse, into the variable RawMouse, the saved (old) location. This allows the next execution to examine the two variables. If MTemp is a valid position, RawMouse is set to the new position and the cycle continues. The mouse location is copied in to the global variable Mouse for use by routines such as GetMouse().

Program Control

Only a few simple steps are required to set the mouse position properly and safely:

Step:

1: set MTemp to the new position

2: set RawMouse to new position

3: set CrsrNew to true

First, we should define our variables:

int             *MTemp;
char            *CrsrNew;

MTemp   = (int *)  0x828;
CrsrNew = (char *) 0x8CE;

Notice that MTemp was declared as an integer, and RawMouse and Mouse were not declared at all. Since the three points are in a row, it is much easier to simply declare the first variable as an integer and increment the pointer to each position to be set. NewPos is passed to our routine, containing the point to which the mouse should be moved in the following code excerpt. Remember that points are stored internally as (v,h) or (row,column), instead of (h,v).

!c

odeexamplestart/* 1 */

for (i=0;i<3;i++) {
 *(MTemp+2*i) = newPos.v;
 *(MTemp+2*i+1) = newPos.h;
}


Once the three points are set, the only task which remains to be done is the setting of the CrsrNew variable. To tell the System that the mouse has moved, the boolean must be set with a non-zero (true) value. Since it is set to -1 by the System, it will be so set here. Any true value should work, however.

/* 2 */

*CrsrNew = -1;

The System routine will realize that the global CrsrNew has been changed, will find the new position in MTemp and RawMouse and will draw the cursor in the new position.

Curse Control

It’s unwise to have your program confuse the user by moving the cursor too dramatically from where he would expect it to appear. If you are in a programming situation which is leading you to move the cursor to where you want it, rather than where the user expects it, you should think twice -- and then think again.

Listing:  Control.c

/*******
 * HandleMouse()
 * Checks the cursor position and calls MousePos if necessary
 *******/
HandleMouse(boundsRect)
Rect  *boundsRect;
{
Point   mousePoint;
Point   newPoint;

 GetMouse(&mousePoint);
 LocalToGlobal(&mousePoint);
 newPoint.h = newPoint.v = -1;
 
 if (mousePoint.h <= boundsRect->left)
 newPoint.h = boundsRect->right - 2;
 else
 if (mousePoint.h >= boundsRect->right - 1)
 newPoint.h = boundsRect->left + 1;
 if (mousePoint.v <= boundsRect->top)
 newPoint.v = boundsRect->bottom - 2;
 else
 if (mousePoint.v >= boundsRect->bottom - 1)
 newPoint.v = boundsRect->top + 1;
 
 if ( (newPoint.h + 1) || (newPoint.v + 1) )
 {
 newPoint.h = (newPoint.h != -1) ? newPoint.h : mousePoint.h;
 newPoint.v = (newPoint.v != -1) ? newPoint.v : mousePoint.v;
 MousePos(newPoint);
 }
}
Listing:  ControlMain.C

/* CursorControl */ /* by Rob Gibson */ /* August 22, 1989. */
/* MacHeaders Included */
/*********  Project file: Control.c  ControlMain.c             Functions.c 
 MacTraps MousePos.c
 Type: APPL Creator: CCTL **********/

#define ControlDialogID 1000
#define nil 0L
/* important dialog items */
enum{   quitItem = 1,   setItem,   topPosItem,     leftPosItem, 
 bottomPosItem,  rightPosItem,   boxItem     };

  /* Our global variables */
DialogPtr ControlDialog;
Rect    boundsRect;

/**InitMacintosh()  Initialize all the managers & memory ***/
InitMacintosh()
{  MaxApplZone();
 InitGraf(&thePort);
 InitFonts();
 FlushEvents(everyEvent, 0);
 InitWindows();
 InitMenus();
 TEInit();
 InitDialogs(0L);
 InitCursor();
} /* end InitMacintosh */

/**GetBounds()  *  * Get the rect specified in dialog  ***/
GetBounds(theDialog)
DialogPtr theDialog;
{  Str255 str;   longdummy;

 boundsRect.top = GetETNum(theDialog, topPosItem);
 boundsRect.left = GetETNum(theDialog, leftPosItem);
 boundsRect.bottom = GetETNum(theDialog, bottomPosItem);
 boundsRect.right = GetETNum(theDialog, rightPosItem);
} /* end GetBounds */

/*TrackRect() Frame old, new bound rects in current GrafPort**/
TrackRect(oldRect, r)
Rect  *oldRect;
Rect  *r;
{  FrameRect(oldRect);
 FrameRect(r);
} /* end TrackRect */

/**DisplayBounds() Display a rect in the dialog*/
DisplayBounds(theRect, theDialog) 
Rect    *theRect;
DialogPtr theDialog;
{  SetETNum(theDialog, topPosItem, (long)theRect->top);
 SetETNum(theDialog, leftPosItem, (long)theRect->left);
 SetETNum(theDialog, bottomPosItem, (long)theRect->bottom);
 SetETNum(theDialog, rightPosItem, (long)theRect->right);
 SelIText(theDialog, topPosItem, 0, 32767);
} /* end DisplayBounds */

/**SetBoundsLoop() User drags to specify new rect**/
SetBoundsLoop(theDialog)
DialogPtr theDialog;
{  Rect oldRect;
 Rect   newRect;
 GrafPtrsavePort;
 GrafPtrdeskPort;
 Point  firstPoint;
 Point  secondPoint;
 Point  lastSecondPoint;

 GetPort(&savePort);
 OpenPort(deskPort = (GrafPtr)NewPtr(sizeof(GrafPort)));
 InitPort(deskPort);
 SetPort(deskPort);
 PenPat(gray);
 PenMode(notPatXor);
 PenSize(2, 2);
 while(!Button());
 GetMouse(&firstPoint);
 newRect.top = lastSecondPoint.v = firstPoint.v;
 newRect.left = lastSecondPoint.h = firstPoint.h;
 newRect.bottom = newRect.right = 0;
 while(Button()) {
 oldRect = newRect;
 GetMouse(&secondPoint);
 /* If the mouse location has changed then track mouse */
 if (secondPoint.v != lastSecondPoint.v || secondPoint.h != lastSecondPoint.h) 
 {
 /* Create a new Rect making sure it is not an empty Rect */
 if (secondPoint.v > firstPoint.v) {
 newRect.top = firstPoint.v;
 newRect.bottom = secondPoint.v;
 }
 else {
 newRect.top = secondPoint.v;
 newRect.bottom = firstPoint.v;
 }
 if (secondPoint.h > firstPoint.h) {
 newRect.left = firstPoint.h;
 newRect.right = secondPoint.h;
 }
 else {
 newRect.left = secondPoint.h;
 newRect.right = firstPoint.h;
 }
 lastSecondPoint = secondPoint;

 TrackRect(&oldRect, &newRect);
 DisplayBounds(&newRect, theDialog);
 }
 }
 FrameRect(&newRect);
 ClosePort(deskPort);
 DisposPtr((Ptr)deskPort);
 PenNormal();
 SetPort(savePort);
 boundsRect = newRect;
 } /* end SetBoundsLoop */

/*HandleControlDialog()  Main event loop  *  ****/
HandleControlDialog(theDialog)
DialogPtr theDialog;
{  EventRecord   event; /*  Filled by GetNextEvent */
 Booleanfinished = false; /*  Are we done? */
 int    chosen;
 char   theChar;

 while (!finished) /*  do this until we selected quit */
 { /* continue with the normal get next event stuff... */
 if (GetNextEvent(everyEvent, &event))
 /*  if there was an event... then  */
 {
 if (event.what == keyDown || event.what == autoKey)
 { 
 theChar = (char) (event.message & charCodeMask);
 switch(theChar) { 
 case ‘Q’:
 case ‘q’:
 case ‘.’:
 chosen = quitItem;
 event.what = 0; /* remove event */
 finished = true;
 ClickButton(theDialog, quitItem, 2);
   break;
   case ‘\t’:
 case ‘\b’: 
 break;
   case ‘\r’:
 case ‘\003’:
 case ‘S’:
 case ‘s’:
 chosen = setItem;
 event.what = 0; /* remove event */
 ClickButton(theDialog, setItem, true);
 SetBoundsLoop(theDialog);
 ClickButton(theDialog, setItem, false);
 break;
 default:
 if (theChar < ‘0’ || theChar > ‘9’)
 event.what = 0;
 break;
 }
 } else if (event.what == updateEvt)
 {
 SetPort(theDialog);
 BeginUpdate(theDialog);
 FrameItem(theDialog, boxItem);
 DrawDialog(theDialog);
 DrawDefaultBtn (theDialog, setItem);
 EndUpdate(theDialog);
 }
   }

 if (!finished) {
 if   (IsDialogEvent(&event))
 if (DialogSelect(&event, &theDialog, &chosen)) {
 GetBounds(theDialog);
 switch (chosen) {
 case 1:
 finished = true;
 break;
 case 2:
 ClickButton(theDialog, setItem, true);
 SetBoundsLoop(theDialog);
 ClickButton(theDialog, setItem, false);
 break;
 default:
 break;
 } /*  end of if switch  */
 } 
 HandleMouse(&boundsRect);
 } /*  end of if (!finished) */
 } /*  of event loop  */

 DisposDialog(theDialog);
} /* end HandleControlDialog */

/*****  * SetUpDialog()  *  * Set up dialog stuff  *  *****/
SetUpDialog() {
 int    itemType;
 Handle Hdl;

 ControlDialog = GetNewDialog(ControlDialogID, nil, -1L);
 CenterWindow(ControlDialog, &screenBits.bounds);
 DisplayBounds(&screenBits.bounds, ControlDialog);
 ShowWindow(ControlDialog);
 boundsRect = screenBits.bounds;
 HandleControlDialog(ControlDialog);
} /* end SetUpDialog */

/*****  * main()  *  * Call the main procedures  *  *****/
main()

{  InitMacintosh();
 SetUpDialog();
} /* end main */
Listings:  Functions.C

/****
 * GetEText()
 * Get text of an ETItem
 ****/
GetEText (theDialog, theItem, s)
DialogPtr theDialog;
inttheItem;
char    *s;
{
 int     theType;
 Handle Hdl;
 Rect box;

 GetDItem (theDialog, theItem, &theType, &Hdl, &box);
 GetIText (Hdl, s);
} /* end GetEText */

/****
 * GetETNum()
 * Get number from an ETItem
 ****/
GetETNum(theDialog, theItem)
DialogPtr theDialog;
inttheItem;
{
 Str255 s;
 long theNum;
 
 GetEText(theDialog, theItem, &s);
 StringToNum(s, &theNum);
 return(theNum);
} /* end GetETNum */

/****
 * SetEText()
 * Set text of an ETItem
 ****/
SetEText (theDialog, theItem, s)
DialogPtr theDialog;
inttheItem;
Str255  s;
{
 int     theType;
 Handle Hdl;
 Rect box;

 GetDItem (theDialog, theItem, &theType, &Hdl, &box);
 SetIText (Hdl, s);
} /* end SetEText */

/****
 * SetETNum()
 * Set number in an ETItem
 ****/
SetETNum(theDialog, theItem, theNum)
DialogPtr theDialog;
inttheItem;
long    theNum;
{
 Str255 s;
 
 NumToString(theNum, s);
 SetEText(theDialog, theItem, &s);
} /* end GetETNum */

/***** LToGRect()  Convert a local rect to global *****/
LToGRect(r)
Rect  *r;
{
 Point  pt1,
 pt2;

 pt1 = topLeft(*r);
 pt2 = botRight(*r);
 LocalToGlobal(&pt1);
 LocalToGlobal(&pt2);
 Pt2Rect(pt1, pt2, r);
} /* end LToGRect */

/*****
 * CenterWindowPoint()
 * Calculates the topleft co-ords of a window,
 * taking screen size into account
 *****/
Point CenterWindowPoint (theRect)
Rect  *theRect;
{
 int    theInd = (screenBits.bounds.bottom<350) ? 3:4;
 Point  thePt;
 int    int1, int2;

 int1=((screenBits.bounds.right-screenBits.bounds.left-theRect->right+theRect->left) 
/ 2);
 int2=((screenBits.bounds.bottom-screenBits.bounds.top-theRect->bottom+theRect->top+20) 
/ theInd);
 SetPt(&thePt, int1, int2);
 return(thePt);
} /* end CenterWindowPoint */

/*****
 * CenterWindow()
 * Centers a dialog or window
 *****/
void CenterWindow(theDialog)
DialogPtr theDialog;
/* Center window - center slightly higher for large screens */
{
 Point  thePt;
 Rect newBounds;

 newBounds = *&theDialog->portRect;
 LToGRect(&newBounds);
 thePt = CenterWindowPoint(&newBounds);
 MoveWindow(theDialog, thePt.h, thePt.v, 0);
} /* end CenterWindow */

/****ClickButton() Simulate a click in a button ****/
ClickButton(theDialog, ID, method) 
/* 0 is off, 1 is on, 2 simulates a click */
DialogPtr theDialog;
intID;
intmethod;
{
 int    itemType;
 Handle item;
 Rect box;
 long ticks;

 GetDItem(theDialog, ID, &itemType, &item, &box);
 HiliteControl((ControlHandle) item, (method >= 1));
 if (method >= 2)
 {
 Delay(8L, &ticks);
 HiliteControl((ControlHandle) item, 0);
 }
} /* end ClickButton */

/****
 * FrameItem()
 * Frame a dialog item in current pen modes
 ****/
void FrameItem (theDialog, item)
DialogPtr theDialog;
intitem;
{
 int    optType;
 Handle btnHdl;
 Rect   optBox;

 SetPort(theDialog);
 GetDItem(theDialog, item, &optType, &btnHdl, &optBox);
 FrameRect(&optBox);
} /* end FrameItem */

/**** DrawDefaultBtn() Outline the default button ****/
void DrawDefaultBtn (theDialog, item)
DialogPtr theDialog;
intitem;
{
 int    optType;
 Handle btnHdl;
 Rect   optBox;

 SetPort(theDialog);
 GetDItem(theDialog, item, &optType, &btnHdl, &optBox);
 PenSize(3, 3);
 InsetRect(&optBox, -4, -4);
 FrameRoundRect(&optBox, 16, 16);
} /* end DrawDefaultBtn */
Listing:  MousePos.C

/********
* MousePos()
* Set the mouse position, August 22, 1989
* by Robert S. T. Gibson for MacTutor
********/
void MousePos(newPos)
Point newPos;
{
 int    *MTemp;
 char *CrsrNew;
 int    i;

 MTemp = (int *)  0x828;  /* Set up our globals... */
 CrsrNew = (char *) 0x8CE;

/* Points are stored as (row, column) or (v, h) in memory...*/
 /* Set our globals... */
 for (i=0;i<3;i++) {
 *(MTemp+2*i) = newPos.v;
 *(MTemp+2*i+1) = newPos.h;
 }
 *CrsrNew = -1;  /* There’s a new position */
}
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

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 »
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 »

Price Scanner via MacPrices.net

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
May 2024 Apple Education discounts on MacBook...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $300 off the purchase of a new MacBook... Read more
Clearance 16-inch M2 Pro MacBook Pros in stoc...
Apple has clearance 16″ M2 Pro MacBook Pros available in their Certified Refurbished store starting at $2049 and ranging up to $450 off original MSRP. Each model features a new outer case, shipping... Read more
Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... 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.