TweetFollow Us on Twitter

Fat Bits
Volume Number:2
Issue Number:6
Column Tag:C Workshop

Mouse DA shows off Fat Bits

By Rick Flott, FlottWare, Chandler, AZ

Mouse Position Desk Accessory


Setting up screen graphics on the Mac can be a very tedious and time consuming job. Previously I have used "Mouse Position" desk accessories (DA's) to show the position of the mouse, but none of them had the features I wanted. So as a true programmer I wrote one myself. I borrowed some ideas from others and added a few new ones of my own.

First, I must give credit where it is due. I used an old DA called Magnifying Glass to get a "Fat Bits" view of the screen. I really thought the "Fat Bits" was neat, but wanted other information. This Mouse Position DA also has this feature, but uses it in a little different way.

Using the Mouse Position DA

The window created by the Mouse Position DA looks like this -

The top line gives the name of the window the cursor is currently over. The next two lines (labeled 'L' and 'G') give the local and global coordinates of the mouse (both horizontal and vertical portions are given). The bottom graphics give a "Fat Bits" view of the mouse position. There are a few differences between these "Fat Bits" and others you may have seen.

First, the actual position of the cursor is in the center of the screen (not in the top left corner). Second, the gray lines symbolize the real point (as you all know from reading Inside Macintosh - points do not occupy space, they are at the intersection of infinitely thin horizontal and vertical grid lines). The "hot spot" of the cursor is the point immediately below and to the right of the gray "crosshairs" (the tip of the paintbrush of the MacPaint Icon shown in the window). The "crosshairs" do not cover up any pixels, they just split the rectangle surrounding the cursor into four planes.

There are also a few other features in this DA -

• when the mouse is over the desktop, the window name is set to "DeskTop" and no local coordinates are shown (since they don't exist).

• the window name, local, and global coordinates can be "Cut" or "Copied" to the clipboard and "Pasted" into your program.

• when the CapsLock key is down and the coordinates are Cut or Copied, they are appended to the clipboard. This is very handy when setting up rectangles or other complex graphics that require multiple points. Just press CapsLock and start Copying!

• remember - in most applications Cut and Copy only work on the topmost window, hence the Mouse Position window must be in front for these commands to work.

Code Description

As in any desk accessory, 5 routines must be present -

• open (initializes the DA)

• close (stops the DA)

• control (receives commands from system)

• prime

• status

The latter two routines do not need to perform any functions, but they must be present.

The open routine in the Mouse Position DA is the "main()" of this C program. It allocates the DA window from the heap, sets up the font for this window, and draws the "static" portion of the window. It also stores the reference number of the DA in the windowKind field of the window. This is very important since this the only way the Mac knows that this is a "system" window and to pass the proper events to it and not to the running application. In addition to this, the pointer to the window is kept in the device control entry for retrieval later on. Remember, a desk accessory is viewed as 5 separate routines called by the system (unlike an application).

The Close routine does the opposite of the open. It releases the memory used by the window and resets the proper fields in the device control entry record.

The Control routine does all the work. It takes commands from the system (passed to it when the application calls SystemTask, SystemEdit, or SystemClick) and processes them. In this DA, only two commands are processed - accRun (periodic command telling the DA to run) and accEvent (command telling the DA to handle an event). As you will see later on, this DA is set up to run as often as possible so that the mouse position coordinates appear to be updated continuously in the window.

This routine starts off by obtaining the window pointer from the device control entry and parsing the command (CSCode) sent to it. If it is a run command (accRun) then the new mouse position is displayed (by calling the routine dspMousePos). If it is the event command (accEvent) then the doEvent routine is called.

The doEvent routine handles 4 types of events - keyDown, autoKey, updateEvt, and activateEvt. The updateEvt will re-draw the coordinates and the window name. The activateEvt only re-draws the coordinates. The keyDown and autoKey events do most of the work in this code. When either of these events occur, a string is allocated, the coordinates and window name placed into the string (with the Munger ROM call), and moved to the clipboard.

Why did I append perfectly good strings into another string? I'm lazy I guess (plus the string is temporarily allocated off the heap and is released immediately). Notice that if the Cut or Copy keys are capitals (the CapsLock key is down) then the current TEXT contents of the clipboard are placed in the string. This allows the user to "append" coordinates together as previously described.

The dspMousePos routine first gets the current coordinates of the mouse. If the mouse has moved from the last time this routine was called, then processing continues, otherwise this routine just returns. This keeps down the "flicker" of the display, since the window is only updated when the mouse moves. It also keeps the DA from being a CPU hog.

Next, the name of the window the mouse is currently over is retrieved. If it is a different window than the last time, the new name is displayed (by the routine dspWindowTitle).

If the mouse is not on the desktop, then the local coordinates must be recomputed. GetMouse gives the mouse in local coordinates of the active window, not the window the mouse is currently over (which may be inactive or even invisible). Hence, the local coordinates must be recomputed with respect to the window the mouse is over. The rest of this routine is straightforward.

The coordinates are converted to strings, the "h" and "v" characters are appended to them, and these strings are displayed right justified in the window. Next, the four "Fat Bit" rectangles are displayed. Notice that 24 pixels surrounding the cursor in the horizontal direction and 16 pixels surrounding the cursor in the vertical direction are displayed (using CopyBits) in the window.

The dspWindowTitle routine first determines if the window passed to it is the desktop or a real window. If it is a real window, then its name is retrieved. Otherwise the name "DeskTop" is used. It then displays this name center justified in the DA window. It also adds a carriage return ('\n') to the name so that when the name is Cut or Copied to the clipboard, the coordinates will be on the next line (like in the window).

The drawWindow routine just draws the "static" portion of the window. This includes the "G" and "L" characters, the horizontal dividing lines, and the gray "crosshairs".

Consulair's DeskMaker

Now all of you desk accessory veterans are saying - "this stuff will never work, look at all of the global variables this guy has in a DA". Well, an application called DeskMaker by Consulair (included with their Mac C development system) takes alot of the headache out of writing DA's. After talking with Bill Duvall, he informed me that the way DeskMaker works is that it takes all of the global variables (referenced off of A4 by the #Options R=4 line) and makes them part of the DRVR resource (he appends them to the end of the code). This allows them to be global and still be accessed by the code in the DA. Of course, I didn't call him until I had already stayed up all night allocating my globals from the heap and accessing them through a handle. Oh well, it wasn't the first time I threw out code, and it won't be the last.

In addition to this, DeskMaker takes commands from a ".desk" text file to set up the DA's flags and header constants they require. You can turn any flag on or off, set up the other constants (like drvrDelay, drvrMask, etc.), and specify the names of the standard routines (Open, Close, Control, etc.) He has also added another command "Test" which allows you temporarily install the DA in the system menu to try it out. This is nice since you do not have to use Font/DA Mover or any of the other applications/DA's that run DA's from a file.

The "MousePos.Desk" listing shows the commands sent to DeskMaker for this DA. First, the filename, map, and name of the DA is set up. Next, the names of the 5 routines are defined. Finally, the drvrEMask, drvrDelay, and drvrFlags are set up. This DA was given the ID of 22 and the test flag was set to allow debugging. Since most of the C compilers handle DAs differently, this information should allow you to recreate this DA on other compilers.

MousePos.c Lisiting



     This is a desk accessory that shows three things about the position 
of the mouse cursor -

     - Name of the window the cursor is currently over
     - Local and global coordinates of the cursor
     - "Fat Bits" display of a rectangle around the cursor

      It also allows the user to Copy or Cut the window name and the 
local & global coordinates to the clipboard (CapsLock-Copy or CapsLock-Cut 
will append the coordinates to the clipboard).

 Written by: Rick Flott                           Mac C (Consulair) V 

#Options R=4 L=500 F=8000 Z Q=0 O=200

#include "MacCDefs.h"// Mac ROM data structure def's
#include "Events.h"
#include "Window.h"
#include "Font.h"
#include "TextEdit.h"
#include "Osmisc.h"
#include "Osio.h"
#include "Desk.h"

    Global Data

/* ------ Constants ----- */

#define FALSE 0
#define TRUE  0xFF

/* ------- Types ------- */

typedef struct    // 6 char strings for the coord's
 char count;
 char s[6];
 } Str6;

/* ---- Rectangles ---- */

Rect titleRect      = {  0,  0, 10,100},   // Window title rect
     localStrRect   = { 11,  1, 21,  6},
     localHRect     = { 11,  6, 21, 49},     // Local horiz coord's rect
     localVRect     = { 11, 52, 21, 94},   // Local vert  coord's rect
     globalStrRect  = { 21,  1, 31,  6},
     globalHRect    = { 21,  6, 31, 49},   // Global horiz coord's rect
     globalVRect    = { 21, 52, 31, 94},  // Global vert  coord's rect

     fBTopLeftRect  = { 32,  0, 64, 48}, // "Fat Bits" rect's
     fBBotLeftRect  = { 68,  0,100, 48},
     fBTopRightRect = { 32, 52, 64,100},
     fBBotRightRect = { 68, 52,100,100},

     windowRect     = { 50,  5,150,105}; // DA window rect

/* ----- Strings ------ */

char   deskTopTitle[] = {"\pDeskTop"}; // Constant desktop str

Str6   localVStr,  localHStr, // Local coord strings
       globalVStr, globalHStr;// Global coord strings

Str255 windowT;    // Window name string

/* --- Global Var's --- */

WindowPtr oldFrontWindow = 0; // Last front window ptr
Point     oldPt = {0,0};   // Last position of mouse

struct QDVar *getQD();

    main()     (Open routine)

      The Open routine opens the desk accessory window and intializes 
any global data before the desk accessory is used.

int main(parameterBlock,DeviceControlEntry)
 CntrlParam       *parameterBlock;
 DeviceControl *DeviceControlEntry;
 WindowPtr windowPtr;
 GrafPtr port;

 if ((windowPtr = DeviceControlEntry->dCtlWindow) == 0)
 GetPort(&port); // Preserve appl window
    // Open DA window
 windowPtr = NewWindow(0, &windowRect,
 "\pMouse Pos",0,
 rDocProc, -1, 1, 0);
 if (windowPtr == 0)

   SetPort(windowPtr);       // Use this new window

   // Set it as a system window
   ((WindowPeek)windowPtr)->windowKind =     

  // Save DA window ptr

   TextFont(monaco);    // Set up DA font

   drawWindow();   // Draw static portion of window

   SetPort(port);   // Restore application window

 return 0;

 } // end main()


      The Close routine disposes of the desk accessory window and any 
data allocated on the heap.

int Close(parameterBlock,DeviceControlEntry)
 CntrlParam       *parameterBlock;
 DeviceControl *DeviceControlEntry;
 WindowPtr windowPtr;
 // Get DA window ptr
 windowPtr = DeviceControlEntry->dCtlWindow; 

 DisposeWindow(windowPtr);   // Release DA window
 DeviceControlEntry->dCtlWindow = 0;

 return 0;

 } // end Close()


      This desk accessory does not use a Prime routine.

 CntrlParam       *parameterBlock;
 DeviceControl *DeviceControlEntry;


      This desk accessory does not use a Status routine.

 CntrlParam       *parameterBlock;
 DeviceControl *DeviceControlEntry;


      The Control routine parses the desk accessory command sent from 
the system and routes the data to the proper routine. The commands currently 
used are -

 accRun - Display the mouse position.
 accEvent - Handle Cut and Copy menu commands.


 CntrlParam       *parameterBlock;
 DeviceControl *DeviceControlEntry;
 GrafPtr port;
 WindowPtr windowPtr;
 // Get DA window ptr
 windowPtr = DeviceControlEntry->dCtlWindow; 

 GetPort(&port); // Preserve application window
 SetPort(windowPtr);    // Use DA window

 switch (parameterBlock->CSCode) // What cmd was sent?
 case accRun:      // cmd = RUN
 dspMousePos(windowPtr);      // Display new  position
 case accEvent:   // cmd = HANDLE EVENT
 } // end switch

 SetPort(port);   // Restore appl window

  } // end Control()


      This routine parses the event sent from the system. The events 
currently used are -

 keyDown, autoKey  - Cut or Copy the window name &                   
                                                  mouse coord's to clipboard.

 updateEvt         - Redraw the entire desk acc window.

 activateEvt       - Redraw the only the mouse coord's.


 EventRecord *event;
 WindowPtr    windowPtr;
 Handle strHandle;
 Ptr    strPtr;
 int    scrapOffset;
 long   offset = 0;

 switch (event->what)// Which event occurred?
 case keyDown:
 case autoKey:   // Event = KEY PUSH
 if ((event->modifiers&cmdKey))      // Was it a cmd key?
 strHandle = (Handle)NewHandle(0); // Allocate a string

 // Only allow Cut,Copy
 switch ((char)(event->message))
 case 'C':         // If Shift/CapsLock, copy previous clip
 case 'X':
 offset = GetScrap(strHandle,
 case 'c':
 case 'x':
 if (offset < 0)   // Was there a scrap error?
 SysBeep(2);// Y - return

 if (ZeroScrap())// Clear the clipboard

        // Grow string to place clipboard stuff in

 (sizeof windowT)+
 (sizeof localHStr)+
 (sizeof localVStr)+
 (sizeof globalHStr)+
 (sizeof globalVStr));

        // Place window name, local, global coord's into string

        offset = Munger(strHandle, offset,0,0, windowT.s,      
 (long) windowT.count);
           offset = Munger(strHandle, offset,0,0, localHStr.s, 
 (long) localHStr.count);
        offset = Munger(strHandle, offset,0,0, localVStr.s,    
 (long) localVStr.count);
        offset = Munger(strHandle, offset,0,0, globalHStr.s,
 (long) globalHStr.count);
        offset = Munger(strHandle,offset,0,0, globalVStr.s,
 (long) globalVStr.count);

        HLock(strHandle); // Lock the string down

        strPtr = (Ptr)*strHandle;
        // Put string into clipboard
        if (PutScrap((long)offset,'TEXT',strPtr))

   HUnlock(strHandle);  // Unlock the string

        default: // Beep on other cmd keys

 } // end switch

 DisposHandle(strHandle); // Release the string
   } // end if


 case updateEvt: // Event = UPDATE EVENT
 SetPort(windowPtr);  // Use DA window
 drawWindow();      // Redraw the window
 // Display  new window title

 case activateEvt: // Event = ACTIVATE EVENT
 dspMousePos(windowPtr);   // Display  new mouse pos

    } // end switch
  } // end doEvent()


      This routine displays the position of the mouse. It displays the 
following information -

 - Local and global coordinates of the cursor
 - "Fat Bits" display of a rectangle around the cursor


  WindowPtr windowPtr;
  Rect      cursorRect;
  WindowPtr mouseWindow;
  short     windowCode;
  struct    QDVar *myQD;  // Place for copy of QD pointer
  Point     localPt,globalPt;

  myQD = getQD();// Get a copy of QD pointer

  GetMouse(&localPt);// Get the new mouse position
  globalPt = localPt;
  LocalToGlobal(&globalPt); // Convert it to global coord's

  if (!EqualPt(&globalPt,&oldPt))  // Has the mouse moved?
    oldPt = globalPt;// Y - remember where it now is

  // Determine the window the mouse is now in
    windowCode = FindWindow(&globalPt, 

 // Is mouse in a different window?
    if (oldFrontWindow != mouseWindow)
            // Y - Display  title of new window
      dspWindowTitle(oldFrontWindow = mouseWindow);

    if (mouseWindow) // Is the mouse on the Desktop?
      { // N - get, display  local coord's
 // Get local coord's of window mouse is in
      localPt = globalPt;
           // Convert local coord's to strings

      localHStr.s[localHStr.count++]='h';    // Add in 'h' and 'v'
      localVStr.s[localVStr.count++]='\n';   // Add CR
    else    // Y - don't display local coord's when on desktop

    SetPort(windowPtr);      // Draw in desk acc window
 // Convert global coord's to strings

    globalHStr.s[globalHStr.count++]='h';    // Add in 'h' and 'v'
    globalVStr.s[globalVStr.count++]='\n';   // Add CR

 // Display global coord's
 // Display local coord's

    SetRect(&cursorRect,  // Set up top left "Fat Bits" rect
           globalPt.h, globalPt.v);
    CopyBits(&myQD->screenBits, // Display  top left "Fat Bits"

    SetRect(&cursorRect,  // Set up bottom left "Fat Bits" rect
  globalPt.h, globalPt.v+8);
    CopyBits(&myQD->screenBits,    // Display bot left "Fat Bits"

    SetRect(&cursorRect,  // Set up bottom right "Fat Bits" rect
                      globalPt.h, globalPt.v,
    CopyBits(&myQD->screenBits,  // Display bot right "Fat Bits"

    SetRect(&cursorRect,  // Set up top right "Fat Bits" rect
                     globalPt.h, globalPt.v-8,
    CopyBits(&myQD->screenBits,  // Display top right "Fat Bits"

    } // endif
  } // end dspMousePos()


      This routine displays the name of the window passed to it in the 
window title rectangle.

  WindowPtr windowPtr;
  if (windowPtr) // Is the mouse in a real window?
  // Y - display  window's name
  else   // N - display the desktop name

  windowT.s[windowT.count++] = '\n'; // Add CR

 } // end dspWindowTitle()


 This routine draws the "static" portion of the window.

  struct    QDVar *myQD;  // Place for copy of QD pointer

  myQD = getQD();  // Get a copy of QD pointer

  MoveTo(globalStrRect.left,// Draw "G"
                   globalStrRect.bottom - 1 );

 MoveTo(localStrRect.left,  // Draw "L"
                   localStrRect.bottom - 1);

  MoveTo(0,titleRect.bottom);  // Draw the horiz dividing lines


  MoveTo(fBTopLeftRect.right,    // Draw crosshairs





  } // end drawWindow()


      This routine returns the pointer used by Quikdraw to point to its 
global data.


grafSizeEQU $CA

  SUB.L #grafSize,A0

  } // end getQD()

      NumToString()  (Package glue routine)


  long         theNum;
  struct PStr *theString;

 MOVE.L D1,A0    ; theString
 MOVE   #0,-(SP) ; NumToString selector
 DC.W   $A9EE    ; PACK7
  } Listing

/Output MousePos
/Type 'DFIL' 'DMOV'



MousePos.desk Listing

File MousePos


Name "Mouse Position"

Open main

Close close

Control control

Status status

Prime prime

EventMask 362
Delay 0

+ Periodic
+ Control
+ Status

DeskID 22

+ Test

Community Search:
MacTech Search:

Software Updates via MacUpdate

Square Rave guide - How to grab those te...
Square Rave is an awesome little music-oriented puzzle game that smacks of games like Lumines, but with its own unique sense of gameplay. To help wrap your head around the game, keep the following tips and tricks in mind. [Read more] | Read more »
Snowboard Party 2 (Games)
Snowboard Party 2 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Crowned the best snowboarding game available on the market, Snowboard Party is back to fulfill all your adrenaline needs in... | Read more »
The best games like Animal Crossing on m...
Animal Crossing amiibo Festival is out right now for the Wii U, reminding us of just how much fun that world can be. Or at least to go back and check in on our villages once in a while. [Read more] | Read more »
Between 2 Taps - Tap for Tap interview M...
Hello, and welcome back to Between 2 Taps, Tap for Tap’s Indie Dev interview series. [Read more] | Read more »
Facility 47 (Games)
Facility 47 1.0.1 Device: iOS Universal Category: Games Price: $3.99, Version: 1.0.1 (iTunes) Description: You wake up alone and freezing in an icy cell. You try the cell door but it’s locked, it seems that you are stuck with no... | Read more »
The best Photoshop alternative on iPad
Instagram and Lightroom are great and all, but sometimes people need to get extra creative with their image editing.Like, Photoshop creative. If you're one of these people, take a look at our pick for the best mobile Photoshop experience on iPad... | Read more »
The Walking Dead: No Man’s Land guide -...
A new update for The Walking Dead: No Man’s Land was released last week, making it the perfect time for you to head back to your base and take out some walkers. Here’s the lowdown on what’s new to the game, and how to take advantage. [Read more] | Read more »
Goat Rider guide - Tips and tricks to st...
We've all been there. One second, we're riding high on a crazed goat, and the next, we've been tossed off it like someone who's no good at goat ridin'. [Read more] | Read more »
Real Boxing 2 CREED: How to become a gre...
Just in time for Rocky fans who can’t wait to see CREED, the latest movie, we have the official tie-in game,Real Boxing 2 CREED. It builds on the success of its predecessor and there’s lots to take in so we at 148apps thought we’d run you through... | Read more »
CoinOp Heroes 2 guide - How to build an...
CoinOp Heroes 2 justlaunched and, like all clickers, it's dangerously addictive stuff. You have to furiously tap your screen to defeat wave after wave of foes and earn an insane amount of cash to spend on character upgrades and an army of minions... | Read more »

Price Scanner via

Best Buy Black Friday deals: Up to $200 off M...
Best Buy has posted their Black Friday sale prices for 2015. Save on MacBook Pros, MacBooks, MacBook Airs, iMacs, iPads, and Apple Watches. Choose free shipping or free local store pickup (if... Read more
Save $30-$40 on new Apple TVs after rebate
Adorama has new Apple TVs on sale for up to $40 off MSRP after mail-in rebate, good through December 15th. Shipping is free, and Adorama charges NY & NJ sales tax only: - 32GB Apple TV: $119.99... Read more
13-Inch Haswell MacBook Air At Two Years – Th...
The 13-inch mid-2013 “Haswell” MacBook Air I ordered in Apple’s November 2013 Black Friday sale was my first new Mac in four and a half years — the longest interval I’ve gone between system upgrades... Read more
Target Black Friday Early Access deals: $100...
Target is offering early access to their Black Friday deals on Apple products on their online store for today, the 25th, only. Choose free shipping or free local store pickup (if available): - Apple... Read more
BlackBerry Q3 Mobility Index Report Finds iOS...
BlackBerry has announced results of its thirteenth Good Mobility Index Report, showing that organizations are increasingly building custom secure apps. Among Good Powered by BlackBerry (formerly Good... Read more
Wednesday roundup of early Black Friday Mac s...
Save up to $500 on a new Mac with these early Black Friday deals from Apple resellers, currently the lowest prices available for these models: (1) B&H Photo has all new Macs on sale for up to $... Read more
iPod nano on sale for $119, $30 off MSRP
Walmart has the 16GB iPod nano (various colors) on sale for $119.20 on their online store for a limited time. That’s $30 off MSRP. Choose free shipping or free local store pickup (if available). Sale... Read more
Adorama Black Friday deals: Up to $400 off Ma...
Adorama has released their Black Friday deals for 2015. Save up to $400 on MacBook Pros, $200 on MacBooks and MacBook Airs, and $270 on iMacs. Use code RYBFDEAL during checkout to see these prices.... Read more
B&H Photo Deals: $200 off 12-inch 1.2GHz...
In addition to the B&H Photo Black Friday week sales we posted yesterday, B&H has lowered their price on two products to $200 off MSRP: - 12″ 1.2GHz Gray Retina MacBook: $1399 save $200 - 13... Read more
Best Buy Early Access: Today only, Up to $125...
Best Buy has iPad Air 2s on sale for up to $125 off MSRP and Apple Watch models on sale on their online store for up to $100 off MSRP with special codes through midnight CT tonight. Choose free... Read more

Jobs Board

Hardware Systems Integration Engineer - *App...
# Hardware Systems Integration Engineer - Apple Watch Job Number: 39380139 Santa Clara Valley, Califo ia, United States Posted: Apr. 23, 2015 Weekly Hours: **Job Read more
Sr. Technical/Project Manager, *Apple* Educ...
# Sr. Technical/Project Manager, Apple Education Job Number: 36588557 New York City, New York, United States Posted: Jul. 30, 2015 Weekly Hours: 40.00 **Job Summary** Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Merchant Operations Manager: *Apple* Pay -...
Changing the world is all in a day's work at Apple . If you love innovation, here's your chance to make a career of it. You'll work hard. But the job comes with more than Read more
*Apple* Pay QA Manager - Apple Inc. (United...
Changing the world is all in a day's work at Apple . If you love innovation, here's your chance to make a career of it. You'll work hard. But the job comes with more than Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.