TweetFollow Us on Twitter

Using Vertical Retrace
Volume Number:1
Issue Number:9
Column Tag:C Workshop

Using the Vertical Retrace Manager"

By Robert B. Denny, President, Alisa Systems, Inc., MacTutor Editorial Board

This month, we look at some obscure but very useful features of the Macintosh operating system, and combine them in a complete example program, a CRT saver. The CRT saver does not require a desk accessory slot, nor must it be run as an application to get it installed. The example program also illustrates techniques for using low-level operating system features from C. As usual, the information presented here is meant to supplement that in Inside Macintosh.

The Vertical Retrace Manager

The Vertical Retrace Manager is used to schedule repetitive tasks at timed intervals. It gets its name from the fact that it is activated when the electron beam that paints the Mac screen "snaps back" to its starting place after painting the entire screen from top to bottom. This vertical retrace happens 60 times a second.

Making use of the Vertical Retrace Manager is easy. Simply fill in a data structure with a pointer to the task procedure you want to schedule and the time delay (in ticks). Then issue a Vinstall() with the pointer to that data structure. At each vertical retrace, the delay is decremented. When the number of ticks gets to zero, the task is called.

After the task completes, the Vertical Retrace Manager checks the number of ticks. If it is still zero, nothing further is done. If the task re-loads the tick count, the whole process is repeated. Thus, to have the task periodically scheduled, simply have it re-load the tick count with the desired interval.

The data structure is a queue element, a structure used for various purposes throughout the Mac operating system. The different flavors of queue elements have one thing in common. As suggested by the name, queue elements are used in applications where things are placed on a queue. Queues are typically used to serialize processing or to otherwise establish order. Generically, a queue element may be represented as:

struct QE
 struct QE *QLink; /* Link or NULL */
 short QType;  /* Type of element */
 char QData[1];  /* 1st byte of rest of data */
#define QElem struct QE

The type of queue element is indicated by the value in the QType field. Types include IOQType, for input-output queues, DrvType, for the drive queue, EVType, for the event queue, FSQType for file system queues, and VType for the vertical retrace queue. The contents of the rest of the queue element is specific to the type. A structure definition for a vertical retrace queue element is shown below:

struct  VB
 struct VB *qLink; /* Queue link pointer */
 short qType;  /* Always 1 (VType) */
 ProcPtr vblAddr;/* -> Task to be scheduled */
 short vblCount; /* Delay in ticks */
 short vblPhase; /* Phase (see below) */
#define VBLTask struct VB

When you call Vinstall(), the operating system places your queue element at the end of the vertical retrace queue. This means that your task will get activated following those already scheduled. The VblPhase field is used to interleave tasks which are repetitively scheduled with the same delay so that they are executed in separate "slots".

You might be wondering why "VBL" is used when describing things associated with vertical retrace activity. The VBL stands for "vertical blanking" a synonym for vertical retrace. The two are interchangable.

There are a few things to be aware of when writing a VBL task. The task gets run asynchronously . Whenever the vertical retrace occurs, the current process is interrupted and control transfers to the Vertical Retrace Manager, which saves registers D0-D3 and A0-A3, then calls each task whose tick count has reached zero. When the last task completes (with an RTS), those registers are restored.

This has major consequences. First, the VBL task must save and restore any registers (other than D0-D3 and A0-A3) that it uses. Second, the VBL task must never make Memory Manager requests which allocate or free memory. Since many system services (e.g., resource manipulation) generate Memory Manager requests, this severely restricts activities inside a VBL task. Third, the execution time must be kept short because there may be many VBL tasks scheduled for a particular tick, and all must complete before the next retrace, 16.67 milliseconds later.

The most common way for an application to use a VBL task is to have it control flags and/or timers that are used by the application in its event loop. This way, the timing of application activity is controlled by the VBL task, while the time-consuming processing is done in the application itself.

Why no Memory Manager activity in a VBL task? Since the task is activated asynchronously, it may interrupt the application process right in the middle of Memory Manager services. At that time, the memory management data structures may be in an inconsistent state; a block may be "partially" deallocated, for example. Trying to do something else at that time would cause the whole thing to become corrupt.

VBL tasks have many uses. Any time you have animation to do, consider using a VBL task to make the motion smooth. If you rely on the consistency in timing of your application's event loop, you may be disappointed. When your system gets AppleTalk installed, for example, there can be a lot of asynchronous activity, which will upset your timing loops. Have a VBL task set a flag indicating that a certain amount of "real" time has elapsed, and use this knowledge to animate. Remember that you get sixty frames a second on the Mac screen, and the VBL task can schedule things sixty times a second, so there is no loss in scheduling bandwidth.

The Mac system contains several "standard" VBL tasks which handle the following:

• Check whether the stack and heap are getting too close to each other. This is the "stack sniffer" (every tick).

• Increment the global variable Ticks, the number of ticks since system startup (every tick).

• Handle cursor movement (every tick).

• Deglitch the mouse button and post mouse events (every other tick).

• Post a disk-inserted event if a disk was inserted (every 30 ticks).

In the CRT saver, the VBL task periodically examines the amount of time that has elapsed since the current application got a non-null event. If it has been long enough, the VBL task blanks the screen and sets a flag indicating this fact. That's it.

The GetNextEvent Filter

There is an undocumented "hook" in GetNextEvent() that allows special processing to be performed before control is returned to the calling application. In the global location JGNEFilter there is a pointer to a procedure that gets jumped-to just prior to returning to the application. In fact, the filter procedure completes with an RTS instruction which returns directly to the application.

When the filter procedure is entered, A1 points to the event record in the application's address space. The event has been dequeued and copied into the application's event record. Finally, the top of the stack contains the address of the instruction following the application's _GetNextEvent trap, and just under that is the boolean result being returned by GetNextEvent(). Be aware that this information was obtained by digging with MacsBug, and may change without notice in future operating system revisions.

It may be of interest that the "real" filter procedure appears to perform the following services (there may be more):

• Checks for and beeps the alarm clock.

• Handles the special "command shift" keys, which eject disks, etc.

The CRT saver intercepts the JGNEFilter and keeps track of how long it has been since the application received a non-null event from GetNextEvent(). Then it jumps to the "real" filter procedure.

INIT Resources

Each time the Mac is started up, the operating system installs ROM patches, loads keyboard maps and opens certain drivers. The mechanism used for this process is the INIT resource. You can make use of this feature of the Mac bootstrap code.

During startup, the boot code looks in the "System" file for up to 32 resources of type INIT, starting with ID=1. For each such resource found, the following steps are taken:

1. The INIT resource is loaded into the system heap.

2. DetachResource() is called, which "orphans" the resource, removing it from the map.

3. A JSR is made to the first location in the resource.

4. When the INIT code returns, via an RTS instruction, the first two locations in the INIT are bashed with NOP instructions.

This action may seem a little strange, so let's look at an INIT resource which installs a ROM patch.

First, the resource is loaded and detached, making it invisible to the Resource Manager. It is important to understand the need for detaching the resource. If you start an application on a new disk containing a System file, that disk becomes the new "system" disk. The current System file is closed, the System file on the new disk is opened, and all system resources start coming from the new System file.

When the old System file is closed, all resources that were loaded from there are released to make way for those in the new system. If the INIT resources were not detached after loading, they too would be released, with unfortunate results.

Once the INIT resource has been made permanently resident in the system heap, it is called at its first location, which is usually a jump to some one-time initialization code located at the end of the resource. This allows the initialization code to be chopped off with a _SetHandleSize after it is run, freeing up that system heap space.

The initialization code installs the ROM patch, computes the amount of space needed by the patch code only, then does a _SetHandleSize to reduce the resource's size in the system heap. Then it places a handle to itself in register D7 and returns to the boot code.

At this point, the boot code assumes that there is no need in the INIT resource for the jump to the initialization code, since it has run and may have been chopped off. So it uses that handle to bash the first 2 words of the INIT resource with No-Op instructions.

The CRT Saver

The example C program is a CRT saver which gets installed via an INIT resource, uses a VBL task to time the screen blanking, and uses the GetNextEvent filter to keep track of the last time the application received a non-null event. Please remember that this is an example, written to present and illustrate ideas. In real life, this small program would be written entirely in assembler, and would use the "normal" installation method just explained.

The example shows an alternate installation method, where the initialization code copies the action code to a locked-down area in the system heap and then releases the entire INIT resource. There are two bugs in the CRT saver, which I have purposely left for you to solve.

The first one should be easy. If the application does not call GetNextEvent, the time of last non-null event does not get updated, and the screen may be prematurely blanked. Hint: use the global variables MBTicks and KeyTime.

The other bug will be harder to fix (I have not solved it yet). The usual method for flashing a cursor on the screen (such as the TextEdit insertion bar) is to repeatedly XOR the pattern, which makes it flash white then black. If the cursor happens to be white (invisible) at the moment the screen is blanked, the effects of succeeding XOR's are reversed. The cursor's manager thinks the cursor is white, yet it was secretly bashed black by the screen clearing process.

Because the XOR method is "open loop", the manager never finds out that the cursor's state was reversed. So when it's time to move the cursor, the manager tries to XOR it as needed to make it invisibly white, but instead leaves the space black. This has the effect of leaving behind a ghost of the cursor. Keep in mind that TextEdit isn't the only agent that uses flashing cursors.

The example uses specifics of the Apple 68000 Development System, and the Consulair Mac C compiler. You may need to take different approaches to producing the INIT resource and accessing static variables from both C and assembler. In addition, the interface into C from the Vertical Retrace Manager and the GetNextEvent filter may differ.

  *Screen Saver INIT Resource
  *Written by:   Robert B. Denny, Alisa Systems, Inc.
  *June, 1985
  *Written for:  Apple Computer MDS Development System and Consulair 
Mac C™
  *This program uses specific features of the MDS system and Mac C
  *and will almost certainly require modifications for other systems.
  */Globals -0
  */Type 'RSRC'
  *Copyright (C) 1985, MacTutor Magazine
  *Permission granted to use only for non-commercial purposes.  This 
notice must be
  *included in any copies made hereof.  All rights otherwise reserved.
  *Warning: This code was edited for publication which could have introduced 
minor errors
#Options R=4/* Mac C: Use R4 to access globals */

#include"MacDefs.H"/* Basic Macintosh structures */
#include"Events.H" /* Event Manager & Event Record */
#include"OSMisc.H" /* Queue Elements and VBL defs */

#define TRUE1
#define FALSE  0
#define NULL0
#define SAVE_DELAY  18000 /* 5 Minutes in ticks.  Saver delay */

  * Definitions which allow easy to read access to system variables.
#define Ticks    (*((unsigned long *)(0x16A)))     /* Ticks since boot 
time */
#define GrayRgn  (*((unsigned long *)(0x9EE)))     /* Desktop region 
w/rounded corners */
#define JGNEFilter (*((ProcPtr *)(0x29A)))   /* -> GetNextEvent filter 
procedure */

  * Screen geometry parameters work on both 128K and 512K
#define ScreenLow((unsigned long *)(0x7A700))      /* -> base of screen 
map */
#define scrnLongwords  (5472) /* No. of longwords in screen map */

  * Static variables for the VBL Task and the GNEFilter
VBLTask VBQElement;  /* Vertical Retrace Queue Element */
unsigned long EvTicks;  /* 'Ticks' value of  last non-null event */
ProcPtr SavedJGNEFilter;  /* Entry point of "normal" GNE filter proc 
unsigned short BlankScreenFlag;  /* TRUE means screen already blanked 

  * The following assembler code executes as called from the Mac boot 
process as an INIT
  * resource.  Here is an example where C is just not appropriate.
 RESOURCE 'INIT' 28 'CRT Saver' 80 ; System/Locked att's
 Include MacTraps.D
 Include SysEquX.D
 XDEF InitSaver
 MOVE.L #(TheEnd-TheStart),D0 ; Allocate space for saver
 _NewPtr ,SYS  ; Locked, in system heap
 BNE @10  ; (not enough space)
   MOVE.L A0,A1         ; A1 -> destination area
   LEA  TheStart,A0       ; A0 -> source area
   MOVE.L #(TheEnd-TheStart),D0    ;Size of code & static data
   _BlockMove  ; Copy stuff to allocated block
 MOVE.L A1,A0  ; A0 -> Moved code & data
 LEA  (OurStatics-TheStart)(A0),A0 ; A0 -> "Top" of real statics
 MOVE.L Ticks,EvTicks(A0) ; Initialize Last Event Ticks
 MOVE.L JGNEFilter,SavedJGNEFilter(A0) ; Save "real" GNE filter proc
 PEA  (GNEIntfc-TheStart)(A1) ; Push -> to GNE filter interface
 MOVE.L (SP)+,JGNEFilter  ; Now we catch GNE calls also
 LEA  VBQElement(A0),A0 ; A0 -> VBL Queue Element
 PEA  (VBLIntfc-TheStart)(A1) ; Push -> VBL Service Task
 MOVE.L (SP)+,vblAddr(A0) ; Fill in entry point in Q-Elem
 MOVE.W #Vtype,qType(A0)  ; Indicate the queue element type
 MOVE.W #300,vblCount(A0) ; Schedule at 5 sec. intervals
 Move.W #5,vblPhase(A0) ; Off-the-wall phasing
 _VInstall; Start the VBL task
; We finish up by disposing of ourselves.
 LEA  InitSaver,A0 ; A0 -> Ourselves (INIT resource)
 MOVE.L A0,(A0)  ; Make a handle to ourselves
 MOVE.L A0,D7  ; Save handle in D7 for MacBoot
 _RecoverHandle ,SYS ; Get our real resource handle
 _DisposHandle ; Free ourselves

  * The rest of this is copied into the allocated non-relocatable block 
and runs from there.
  * There are 2 interface routines in assembler which call C to do the 
real work, one for
  * the VBL task and the other for the GNE filter.  Also, there is space 
allocated for our
  * local static variables.

TheStart: ; Static data goes here via A4
 DCB.B  32,0; Enough room for statics
OurStatics: ; "Top" of static area

; Interface to C for Vertical Blanking Task
VBLIntfc: ; Interface for VBL task service
 MOVEM.LA4-A5/D4-D7,-(SP) ; Save registers
 LEA  OurStatics,A4; A4 -> Our static variable area
 JSR  VBLRoutine ; Call C for dirty work
 MOVEM.L(SP)+,A4-A5/D4-D7 ; Restore registers
; Interface to C for GetNextEvent filter.  This must finish up
; by jumping to the "real" filter whose address was originally 
; in the global "JGNEFilter".
 MOVEM.LA1-A5/D0-D7,-(SP) ; Be safe.
 LEA  OurStatics,A4; A4 -> Our static variable area
 MOVE.L A1,D0  ; Pass -> Event Record as parameter to C
 JSR  GNEFilter  ; Call C to filter the events, etc.
 MOVE.L SavedJGNEFilter(A4),A0; Where to next?
 MOVEM.L(SP)+,A1-A5/D0-D7 ; Restore saved reg's
 JMP  (A0); Jump to "real" GNE filter

  * Vertical Blanking task.  This is periodically rescheduled and handles 
watching for 
  * no-activity intervals and blanking the screen if more than a specified 
time elapses
  * between non-null events.
 unsigned long *lp;
 unsigned long n;
 extern GNEIntfc();  /* Declare this as a proc */
 VBQElement.vblCount = 300; /* Reschedule ourselves */
   * If the screen is already blank, do nothing.
   * You might enhance this by doing something interesting with the cursor 
   * this "if" statement, knowing you'll get here every 5 seconds.
   * Blank the screen if there hasn't been a non-null event in the last 
 if((Ticks - EvTicks) > SAVE_DELAY) 
 BlankScreenFlag = TRUE;  /* Set the blanked flag */
 HideCursor ();  /* Hide the cursor from blanking */
 lp = ScreenLow;
 for(n=0; n<scrnLongwords; n++)  /* Blank the screen */
 *lp++ = 0xFFFFFFFF;
 ShowCursor ();  /* Restore the cursor */

  * GNE Filter Procedure
  * If there has been either a key press or mouse click since the screen 
was blank, restore the
  *  screen and switch the GNEFilter back to normal.
ProcPtr GNEFilter(ep)
EventRecord *ep; /* -> Event Record just dequeued */
 if(ep->what != nullEvent)/* If appl is getting non-null event */
 EvTicks = Ticks;/* Remember ticks at non-null event */
 if(BlankScreenFlag) /* If the screen is black */
 BlankScreenFlag = FALSE; /* It's going to get refreshed */
 DrawMenuBar (); /* Draw the menu bar, then */
 PaintBehind (FrontWindow (), GrayRgn);/* Draw all windows and desktop 


TheEnd: ; Mark the end of the resident code/data

Community Search:
MacTech Search:

Software Updates via MacUpdate

Spotify - Stream music, crea...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
VOX 2.8.26 - Music player that supports...
VOX just sounds better! The beauty is in its simplicity, yet behind the minimal exterior lies a powerful music player with a ton of features and support for all audio formats you should ever need.... Read more
beaTunes 5.0.1 - Organize your music col...
beaTunes is a full-featured music player and organizational tool for music collections. How well organized is your music library? Are your artists always spelled the same way? Any R.E.M. vs REM?... Read more
LibreOffice - Free, open-source...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
Sparkle Pro 2.2 - $79.99
Sparkle Pro will change your mind if you thought building websites wasn't for you. Sparkle is the intuitive site builder that lets you create sites for your online portfolio, team or band pages, or... Read more
calibre 3.1.1 - Complete e-book library...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more
calibre 3.1.1 - Complete e-book library...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more
Sparkle Pro 2.2 - $79.99
Sparkle Pro will change your mind if you thought building websites wasn't for you. Sparkle is the intuitive site builder that lets you create sites for your online portfolio, team or band pages, or... Read more
Spotify - Stream music, crea...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
beaTunes 5.0.1 - Organize your music col...
beaTunes is a full-featured music player and organizational tool for music collections. How well organized is your music library? Are your artists always spelled the same way? Any R.E.M. vs REM?... Read more

Latest Forum Discussions

See All

This War of Mine gets a new ending and m...
This War of Mine just got a big new update, featuring free DLC that adds a new ending to the game, among other exciting changes. The update is celebrating the game's two-year release anniversary. Apart from the new ending, which will be quite... | Read more »
Summon eight new heroes in Fire Emblem H...
Nintendo keeps coming at us with Fire Emblem Heroes updates, and it doesn't look like that trend is stopping anytime soon. The folks behind the game have just announced the new War of the Clerics Voting Gauntlet, expected to start next Tuesday. [... | Read more »
The best deals on the App Store this wee...
iOS publishers are pulling out all the stops this week -- there's a huge number of seriously great games at discounted prices this week. Let's not waste any time and get right down to business. [Read more] | Read more »
The House of da Vinci (Games)
The House of da Vinci 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: Enter The House of Da Vinci, a new must-try 3D puzzle adventure game. Solve mechanical puzzles, discover hidden... | Read more »
Solve the disappearance of history’s gre...
Blue Brain Games invites you to indulge in an immersive hands-on 3D puzzle adventure in similar vein to The Room series, with its debut release The House of Da Vinci. Set during the historic period of the Italian Renaissance (when Leonardo himself... | Read more »
Age of Rivals (Games)
Age of Rivals 3.3 Device: iOS Universal Category: Games Price: $.99, Version: 3.3 (iTunes) Description: Deep civilization-building strategy in a fast-paced card game! | Read more »
Panthera Frontier (Games)
Panthera Frontier 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: | Read more »
Angry Birds Evolution beginner's gu...
Angry Birds changes things up a fair bit in its latest iteration, Angry Birds Evolution. The familiar sling-shot physics mechanics are still there, but the game now features team-based gameplay, RPG elements, and a new top-down view. With all of... | Read more »
Sega Forever is for the retro game fans
Sega is launching a new retro games service titled Sega Forever, in a move that's sure to delight games enthusiasts with a bit of nostalgia. Sega's releasing five classic games for free. The titles include Sonic the Hedgehog, Phantasy Star II,... | Read more »
The Little Acre (Games)
The Little Acre 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: | Read more »

Price Scanner via

ABBYY TextGrabber 6 for iOS Implements Instan...
ABBYY has announced the release of TextGrabber 6.0.0, an important feature update to the company’s productivity app developed for iOS and Android devices. TextGrabber 6.0 now offers Real-Time... Read more
vPhone, First Smartphone That Can’t Be Lost,...
Austin, Texas based Hypori has introduced the vPhone, a virtual smartphone that affords every business user the benefits of separate work and personal phones, conveniently delivered on a single... Read more
Save this weekend with 2016 refurbished MacBo...
Apple has dropped prices on Certified Refurbished 2016 15″ and 13″ MacBook Pros by as much as $590 off original MSRP. An Apple one-year warranty is included with each model, and shipping is free: -... Read more
New 27-inch 3.4GHz iMac on sale for $1699, sa...
MacMall has the new 2017 27″ 3.4GHz iMac (MNE92LL/A) in stock and on sale for $1699 including free shipping. Their price is $100 off MSRP. Read more
Clearance 2016 MacBook Pros available for up...
B&H Photo has clearance 2016 13″ and 15″ MacBook Pros in stock today and on sale for up to $400 off original MSRP. Shipping is free, and B&H charges NY & NJ sales tax only: - 15″ 2.7GHz... Read more
Apple Ranks 9th In comScore Top 50 U.S. Digit...
comScore, Inc. has released its monthly ranking of U.S. online activity at the top digital media properties for May 2017 based on data from comScore Media Metrix Multi-Platform. * Entity has... Read more
10.5-inch iPad Pros available for up to $20 o...
B&H Photo has the new 2017 10.5″ iPad Pros available for up to $20 off MSRP including free shipping plus NY & NJ sales tax only: - 64GB iPad Pro WiFi: $649 - 256GB iPad Pro WiFi: $749 - 512GB... Read more
Three Off-The-Beaten-Track iOS Apps That Dese...
One of the great things about using iPads and iPhones is the vast selection of apps available for most anything you want or need to do. The three outlined in this article have been in my core app... Read more
Apple No. 1 Spot In Gartner Top 100 Vendors i...
Gartner, Inc. has unveiled the top global 100 vendors in IT in 2016 based on their revenue across IT (excluding communication services) and component market segments. In the Gartner Global Top 100:... Read more
Clearance iMacs available for up to $300 off...
B&H Photo has clearance 21″ and 27″ Apple iMacs available starting at $949, each including free shipping plus NY & NJ sales tax only: - 27″ 3.3GHz iMac 5K: $1999 $300 off original MSRP - 27″... Read more

Jobs Board

*Apple* News Product Marketing Mgr., Publish...
…organizational consensus on strategy and vision for publisher tools, authoring, and Apple News Format.Carries this strategy and vision across the organization to Read more
*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Security Data Analyst - *Apple* Information...
…data sources need to be collected to allow Information Security to better protect Apple employees and customers from a wide range of threats.Act as the subject matter Read more
Lead *Apple* Solutions Consultant - Apple I...
…integrity, and trust.Success Metrics/Key Performance Indicators:Quantitative* Year over Year growth in Apple Product and Beyond the Box sales in the assigned Point of Read more
*Apple* Solutions Consultant till v%u00E5r...
…ethics, integrity, and trust.Success Metrics/Key Performance Indicators:QuantitativeYear over Year growth in Apple Product and Beyond the Box sales in the assigned Point Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.