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

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

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
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... 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.