TweetFollow Us on Twitter

Cursor Control 1
Volume Number:6
Issue Number:6
Column Tag:abC

Related Info: TextEdit Quickdraw

Cursor Control

By Bob Gordon, Minneapolis, MN

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

Managing Cursors

I know how to curse

Shakespeare, The Tempest (Act 1, Scene 2)

If you remember from last time, I had introduced the idea of adding some additional data structures at the end of the window record to aid in keeping track of the data that hangs around with a window. At the end of that article I said we would illustrate the use of the added data in managing the cursor. We will cover that, but first I would like to comment on a nice piece of work by John Nairn in the April issue.

John has presented a full-blown Scrolling Manager to handle all the issues involved with creating and maintaining scrolling windows. While there are a number of differences between what he has done and what I am describing in this column, a couple common points are worth mentioning. First, the approach is to isolate the user interface control from the actual application. That is, as much as possible, develop generic code to handle the basic operation of the windows (or menus or dialogs, for that matter). Second, this generic code will probably require some place to keep the information it uses; develop a data structure to hold this, and attach it in some way to the window (or menu or dialog). There is actually a bit more commonality (I have the advantage of being able to see the parts I have written but not yet published), and we will explore one of those in this article.

One point of difference. John uses the window’s refCon to hold his additional data structure. His new data structure includes its own refCon for the window’s contents. I added the data on to the end of the window’s structure itself. I feel this simplifies things somewhat, and at least for now it does not seem to violate any rules. If you liked John’s article as I did, you certainly have my permission to use the technique I’ve outlined in implementing it. While I haven’t met John, I’m reasonably sure he won’t mind.

Cursors

The cursor attached to the mouse changes its shape as you move the mouse around the screen. In addition, the user can often affect its shape directly by selecting a tool from a toolbox (usually found in graphics or page layout applications). The problem we deal with this month is how to manage the cursor so it is handled as automatically as possible.

The first issue is getting cursors. There are five built in to the Mac: arrow, crosshairs, plus, clock, i-beam. You can also make your own with ResEdit or some other resource tool. Once we have decided the cursors to use (and made their resources), we need to control the appearance on the screen. What I will describe this month is one way to manage the change of cursor shape as the user moves the mouse around the screen. I am not covering the setting of the cursor’s via tool box or menus.

In June I suggested the use of window margins. The window margin is that area between the window’s frame, which is handled by the Macintosh toolbox routines, and the window’s actual contents, which is what your application is about. The objects that might be in a window margin include scroll bars, rulers, and tool boxes. These are such common components of windows that they can be handled by generic code apart from your application. The other property of the window margin is that the cursor typically changes into the arrow as it is moved into the scroll bar, ruler, etc.

Cursorhelp

Cursorhelp consists of three functions and an include file to aid in the setting and automatic changing of cursors. These functions assume the window structure described in June. The window margins (mtop,mbottom, mright, mleft) are stored with the window. More importantly, the rectangle that surrounds the actual window contents (cursrt) is also stored (I assume rectangular windows). This rectangle is the area in which the cursor is the shape the user selected (i beam, cross, etc.). I put it in the window structure simply to avoid having to calculate it each time. The final piece is the cursor itself (mouser). That is, the cursor’s shape as selected by the user is a property of the window. With a multi-window application the user can have one window editing text, another editing a graphic, and a third editing a spreadsheet (I am not suggesting anyone actually write something like this), and the appropriate cursor will be displayed automatically as the user selects each window. The main loop need know nothing of the cursors.

The main loop does need to set the cursor. There are two places where this can occur: the users specifies a cursor in some way or, the application displays the watch (or other indicator) to indicate the passage of time. The program calls CursorToUse passing the window and the number of the desired cursor.

The program also needs to set the cursor rectangle. This must be done every time the window’s size is changed or the window margins are changed (for example, choosing to show rulers or not).A call to CursorRect() does that. Note that the window margins must have been previously set.

To actually control the cursor, the program calls CursorMaintain() as it runs through the event loop.

Include Files
/*windowhelp.h */
#include “TextEdit.h”
 
#ifndef WINDOWHELP_H
#define WINDOWHELP_H
#include“abc.h”    /* window add-on structure */

#define WindowStruct struct w_struct
WindowStruct
 {
 WindowRecord  wr;  /* the original window record */
 uchar  mtop;    /* margin indents */
 uchar  mleft;
 uchar  mbottom;
 uchar  mright;
 Rect   cursrt;    /* used for cursor control */
 char   mouser;  /* mouse pointer id  */
 char   changed; /* if contents were changed */
 long   ckind;   /* kind of contents */
 short  fileref; /* associated file, if any */
 TEHandle curtext; /* handle to current text */
 };
 
WindowStruct*WindowNew();

#define Woffset  18
#define SBarWidth 15

/* these definitions allow easy generation of the four square cornered 
titled windows. The basic (simplest) window is the WDOC (NoGrowDocProc). 
To this optionally add WGROW to add a grow box and/or WZOOM to add a 
zoom box.
 */
#define WDOC4
#define WGROW    -4
#define WZOOM    8
#define WVBAR    16
#define WHBAR    32

/* Value placed in windowKind field of WindowRecord by WindowNew if the 
window has a grow box. This is used by routines that redraw the window 
to decide whether to draw the grow box or not 
 */
#define HASGROW  9

#endif

/* cursorhelp.h
 * header file for cursorhelp
 */
 
 #defineARROW  0
 #defineIBEAM  1
 #defineCROSS  2
 #definePLUS3
 #defineWATCH  4
CursorHelp Functions
#include“abc.h”
#include“Quickdraw.h”
#include“windowMgr.h”
#include“windowhelp.h”
#include“cursorhelp.h”

/* CursorMaintain
 * Adjusts the cursor according to the value
 * set in the window and the rectangle currect.
 * If the mouse is in the rectangle, the cursor 
 * set to the current cursor, otherwise it is
 * set to the arrow.
 * The if statement checks to see if there is a 
 * valid window and if the window belongs to the
 * application. If it does not belong to the application
 * it is a DA. If the DA is controlling the cursor, there
 * will be a conflict as both programs attempt to control
 * it.
 */
CursorMaintain(ws)
 WindowStruct  *ws;
{
 Point  pt;
 CursHandle curs;
 short  curcursor; /* current cursor */
 
 if (ws && (((WindowRecord *)ws)->windowKind > 7) )
 {
 GetMouse(&pt);
 curcursor = ws->mouser;  /* cursor kind is stored in the window struct 
*/
 if ((PtInRect(pt, &(ws->cursrt))) && (curcursor))
 {
 curs = (Cursor **)GetCursor(curcursor);     
 SetCursor(*curs); 
 }
 else if (curcursor != WATCH)
 {
 InitCursor();
 }
 }
 if (ws == NIL)
 InitCursor();
}

/* CursorRect
 * Uses the portRect of the window passed in
 * to set the current rectangle.  Adjusts the size
 * of the rectangle to account for window margins.
 * By keeping the rectangle around, we eliminate doing
 * this each time through the event loop.
 */
 
CursorRect(ws)
 WindowStruct    *ws;
{
 ws->cursrt = ((GrafPort *)ws)->portRect;
 AdjustRect(&(ws->cursrt),ws->mtop,ws->mleft,ws->mbottom,ws->mright);
}

/* CursorToUse
 * Sets the cursor to be displayed in the
 * rectangle of the current window.
 * Either pass a pointer to the window struct
 * or a NULL pointer. If a NULL pointer is passed,
 * CursorToUse() will use the front window. 
 * Note: At least one window must exist for this
 * to work, but if no windows exist, it
 * will not hurt.
 */
CursorToUse(ws,c)
 WindowStruct  *ws;/* window struct to set cursor for */
 short  c;/* cursor code to use */
{
 if (!ws)
 ws = (WindowStruct *)FrontWindow();
 if (ws)
 ws->mouser = c;
}

Using CursorMaintain()

The following fragment shows the call to CursorMaintain() in the main event loop.

EventLoop()
{
 EventRecordtheEvent;
 char   c;
 short  windowcode;
 WindowPtrwp;
 WindowStruct  *ws;
 
 while(True)
 {
 wp = FrontWindow();
 SystemTask();
 CursorMaintain(wp); 
 if (wp)
 {
 AppTask(wp);
 } 
 if (GetNextEvent(everyEvent,&theEvent))
 switch(theEvent.what)

Other Comments

Check John Nairn’s article for other things to do to automate cursor control. You will note he checks for certain keys being pressed to change the cursor to allow window scrolling (e.g. with a hand).

Last Time

I have a minor error in June’s column. I included some space in the window structure to handle window zooming. These are not needed as zooming is fully supported by the Mac Toolbox. I hadn’t used them for anything yet.

Next Time

Next time I am going to show a quick and very dirty way to help deal with menus.

P.S. Comments are welcome. Send your notes to MacTutor, and please include a phone number.

 
AAPL
$98.77
Apple Inc.
-0.26
MSFT
$44.00
Microsoft Corpora
+0.03
GOOG
$589.11
Google Inc.
-1.49

MacTech Search:
Community Search:

Software Updates via MacUpdate

OS X Yosemite Wallpaper 1.0 - Desktop im...
OS X Yosemite Wallpaper is the gorgeous new background image for Apple's upcoming OS X 10.10 Yosemite. This wallpaper is available for all screen resolutions with a source file that measures 5,418... Read more
Acorn 4.4 - Bitmap image editor. (Demo)
Acorn is a new image editor built with one goal in mind - simplicity. Fast, easy, and fluid, Acorn provides the options you'll need without any overhead. Acorn feels right, and won't drain your bank... Read more
Bartender 1.2.20 - Organize your menu ba...
Bartender lets you organize your menu bar apps. Features: Lets you tidy your menu bar apps how you want. See your menu bar apps when you want. Hide the apps you need to run, but do not need to... Read more
TotalFinder 1.6.2 - Adds tabs, hotkeys,...
TotalFinder is a universally acclaimed navigational companion for your Mac. Enhance your Mac's Finder with features so smart and convenient, you won't believe you ever lived without them. Tab-based... Read more
Vienna 3.0.0 RC 2 :be5265e: - RSS and At...
Vienna is a freeware and Open-Source RSS/Atom newsreader with article storage and management via a SQLite database, written in Objective-C and Cocoa, for the OS X operating system. It provides... Read more
VLC Media Player 2.1.5 - Popular multime...
VLC Media Player is a highly portable multimedia player for various audio and video formats (MPEG-1, MPEG-2, MPEG-4, DivX, MP3, OGG, ...) as well as DVDs, VCDs, and various streaming protocols. It... Read more
Default Folder X 4.6.7 - Enhances Open a...
Default Folder X attaches a toolbar to the right side of the Open and Save dialogs in any OS X-native application. The toolbar gives you fast access to various folders and commands. You just click... Read more
TinkerTool 5.3 - Expanded preference set...
TinkerTool is an application that gives you access to additional preference settings Apple has built into Mac OS X. This allows to activate hidden features in the operating system and in some of the... Read more
Audio Hijack Pro 2.11.0 - Record and enh...
Audio Hijack Pro drastically changes the way you use audio on your computer, giving you the freedom to listen to audio when you want and how you want. Record and enhance any audio with Audio Hijack... Read more
Intermission 1.1.1 - Pause and rewind li...
Intermission allows you to pause and rewind live audio from any application on your Mac. Intermission will buffer up to 3 hours of audio, allowing users to skip through any assortment of audio... Read more

Latest Forum Discussions

See All

To The End Review
To The End Review By Lee Hamlet on July 29th, 2014 Our Rating: :: A VICIOUS CYCLEUniversal App - Designed for iPhone and iPad To The End will test players’ patience, timing, and dedication as they try to navigate all 13 levels in... | Read more »
Traps n’ Gemstones Review
Traps n’ Gemstones Review By Campbell Bird on July 28th, 2014 Our Rating: :: CASTLEVANIA JONESUniversal App - Designed for iPhone and iPad Fight mummies, dig tunnels, and ride a runaway minecart to discover ancient secrets in this... | Read more »
The Phantom PI Mission Apparition Review
The Phantom PI Mission Apparition Review By Jordan Minor on July 28th, 2014 Our Rating: :: GHOSTS BUSTEDUniversal App - Designed for iPhone and iPad The Phantom PI is an exceedingly clever and well-crafted adventure game.   | Read more »
More Stubies Are Coming Your Way in a Ne...
More Stubies Are Coming Your Way in a New Update Posted by Jessica Fisher on July 28th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
The Great Prank War Review
The Great Prank War Review By Nadia Oxford on July 28th, 2014 Our Rating: :: PRANKING IS SERIOUS BUSINESSUniversal App - Designed for iPhone and iPad Though short, The Great Prank War offers an interesting and fun mix of action and... | Read more »
Marvel Contest of Champions Announced at...
Marvel Contest of Champions Announced at Comic-Con Posted by Jennifer Allen on July 28th, 2014 [ permalink ] Announced over the weekend at San Diego Comic-Con was the fairly exciting looking Marvel Contest of Champions. | Read more »
Teenage Mutant Ninja Turtles Review
Teenage Mutant Ninja Turtles Review By Jennifer Allen on July 28th, 2014 Our Rating: :: DULL SWIPINGUniversal App - Designed for iPhone and iPad The pizza power is weak when it comes to this Teenage Mutant Ninja Turtles game.   | Read more »
Exploration Focused Puzzle Game Beatbudd...
Exploration Focused Puzzle Game Beatbuddy Set to Make Transition from PC to iOS this September Posted by Jennifer Allen on July 28th, 2014 [ permalink ] | Read more »
PlanetHD
PlanetHD By Nadia Oxford on July 28th, 2014 Our Rating: :: SPACE MADNESSUniversal App - Designed for iPhone and iPad PlanetHD will keep players busy for a while, though its unpredictable physics are a handful to deal with.   | Read more »
This Week at 148Apps: July 21-25, 2014
Another Week of Expert App Reviews   At 148Apps, we help you sort through the great ocean of apps to find the ones we think you’ll like and the ones you’ll need. Our top picks become Editor’s Choice, our stamp of approval for apps with that little... | Read more »

Price Scanner via MacPrices.net

Apple updates MacBook Pros with slightly fast...
Apple updated 13″ and 15″ Retina MacBook Pros today with slightly faster Haswell processors. 13″ models now ship with 8GB of RAM standard, while 15″ MacBook Pros ship with 16GB across the board. Most... Read more
Apple drops price on 13″ 2.5GHz MacBook Pro b...
The Apple Store has dropped their price for the 13″ 2.5GHz MacBook Pro by $100 to $1099 including free shipping. Read more
Apple drops prices on refurbished 2013 MacBoo...
The Apple Store has dropped prices on Apple Certified Refurbished 13″ and 15″ 2013 MacBook Pros, with model now available starting at $929. Apple’s one-year warranty is standard, and shipping is free... Read more
iOS 8 and OS X 10.10 To Support DuckDuckGo As...
Writing for Quartz, Dan Frommer reports that Apple’s forthcoming iOS 8 and OS X 10.10 operating systems version updates will allow users to select DuckDuckGo as their default search engine. He notes... Read more
U.K. Hospital Using iPods and iPads To Record...
British news journal GazetteLive’s. Ian McNeal notes that the old “an apple a day keeps the doctor away” proverb is being turned on its head at http://southtees.nhs.uk/hospitals/james-cook/ James... Read more
13-inch 2.5GHz MacBook Pro on sale for $1099,...
Best Buy has the 13″ 2.5GHz MacBook Pro available for $1099.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $100 off MSRP. Price is... Read more
Roundup of Apple refurbished MacBook Pros, th...
The Apple Store has Apple Certified Refurbished 13″ and 15″ MacBook Pros available for up to $400 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. Their prices... Read more
Record Mac Shipments In Q2/14 Confound Analys...
A Seeking Alpha Trefis commentary notes that Apple’s fiscal Q3 2014 results released July 22, beat market predictions on earnings, although revenues were slightly lower than anticipated. Apple’s Mac’... Read more
Intel To Launch Core M Silicon For Use In Not...
Digitimes’ Monica Chen and Joseph Tsai, report that Intel will launch 14nm-based Core M series processors specifically for use in fanless notebook/tablet 2-in-1 models in Q4 2014, with many models to... Read more
Apple’s 2014 Back to School promotion: $100 g...
 Apple’s 2014 Back to School promotion includes a free $100 App Store Gift Card with the purchase of any new Mac (Mac mini excluded), or a $50 Gift Card with the purchase of an iPad or iPhone,... Read more

Jobs Board

Sr Software Lead Engineer, *Apple* Online S...
Sr Software Lead Engineer, Apple Online Store Publishing Systems Keywords: Company: Apple Job Code: E3PCAK8MgYYkw Location (City or ZIP): Santa Clara Status: Full Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Sr. Product Leader, *Apple* Store Apps - Ap...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.