TweetFollow Us on Twitter

Events in ZBASIC
Volume Number:3
Issue Number:9
Column Tag:BASIC School

Mixing Event Manager Calls with ZBASIC

By Dave Kelly, MacTutor Editorial Board

Toolbox Event Manager from ZBASIC

Let’s explore ZBASIC from the perspective of the toolbox. At this point it should be observed that although ZBasic (version 4.0) works, it does not answer a few of our needs. Perhaps we can encourage Zedcor to add a few missing features which I will explain here.

As most of you know, programming the Macintosh in most languages involves heavy use of the toolbox routines. You might say that programming in Basic makes you soft. That’s why so many programmers move on to other languages like Pascal or C. It is easy to be lazy when the implementation of the language does most of the complex programming for you. Actually, once you know what to do, the complex stuff doesn’t seem so bad. However, because ZBasic provides statements which do a set of toolbox functions for you, your time is free to work on the organization problems of your program.

DOS versus Mac OS

In a recent discussion on the merits ( or demerits) of MS/DOS with a co-worker, my friend remarked that he thought that MS/DOS had more flexibility than the Mac operating system because the programmer could manipulate files with “powerful” statements (that he had to remember long enough to type into the computer in the correct syntax, I might add). Of course, we (as Mac programmers) all know that the power of the Mac goes beyond “powerful” statements to copy files. The Mac user interface allows “the rest of us” to cut through the mush and get to the heart of the machine. I wonder how much time has been wasted by MS/DOS users as they wade through their manual to figure out how to do something as simple as copying a file. Their time could have been used more usefully. After all, computers are supposed to make life easier, right?

Hard to Program?

The only reason I mention all this is that I feel that the Mac has taken a lot of flak about begin hard to program. Well, some have found it very difficult to program, especially when they don’t follow standard guidelines and try to write with the “look and feel” of MS/DOS on the Mac! ZBasic is different. If you want to program with toolbox calls exclusively, you can still do it. Or, if using ZBasic statements (like MENU or WINDOW) would make it easier, then use them. Maybe now that ZBasic is here the rest of the world out there might notice that it isn’t so hard to program the Mac after all.

Fig. 1 IM Sample Program in ZBasic

Some Things Require Direct Intervention

There are a few things that ZBasic does not yet support. A disk insertion event is one of them. ZBasic does mount and unmount volumes properly, but to sense the insertion of a disk requires us to create our own GETNEXTEVENT loop. The problem with this comes with the fact that if you use your own GETNEXTEVENT loop you will not be able to do any ON DIALOG or ON MENU etc. type event trapping. You will be trapping events yourself the same way that Pascal or C programmers do it. ZBasic inserts a GETNEXTEVENT statement at the beginning of every line between the ON and OFF statements (such as MENU ON or DIALOG ON). If you insert your own GETNEXTEVENT you will lose some events to the ZBasic GETNEXTEVENT statements. There may be times when you need to have precise control over where the GETNEXTEVENT is placed. Fortunately, you can do this (yes, it can and may be done), but it requires you to abandon some of the built-in capability and rely on the toolbox directly; i.e., become a “real” Mac programmer! In some ways this is better anyway. And you may still mix ZBasic statements (any that don’t trap events) along with the toolbox statements.

This month I have adapted the Sample program found at the beginning of Inside Macintosh vol 1 into a working ZBasic toolbox program. This program has revealed some interesting things about ZBasic which should be noted.

Event Manager and ZBasic

The Macintosh is event-driven. That is, the application decides what to do from moment to moment by requesting information from the Event Manager portion of the toolbox ROM through the GETNEXTEVENT statement and then responding to each event one by one in an appropriate way.

Most events are held in a queue called the event queue. The event queue normally has a capacity of 20 events. The event queue is a FIFO (first-in-first-out) buffer which holds events until they can be read from the queue.

There are several different types of events which the Event Manager will keep track of. The most important of these are

• Mouse-down, Mouse-up events;

• Key-down, Key-up events including Auto-key events which occur when the user holds down a repeating key;

• Disk inserted events;

Other important events include update and activate events which involve events which concern the Window Manager. The Event Manager always returns the highest-priority event available of the requested types.

First thing to mention is the method for setting up records of various kinds found in Inside Macintosh. The procedure is fairly painless. For example, the event record must be defined. In Pascal the event record is defined as:

TYPE EventRecord = RECORD
 what:  INTEGER; {event code}
 message: LONGINT; {event message}
 when:  LONGINT; {ticks since startup}
 where: Point;   {mouse location}
 modifiers: INTEGER; {modifier flags}

Remember that Pascal integer types are 2 bytes, and longint types are 4 bytes. By declaring ZBasic’s static variables, the location of the record will be preserved where we will always know where to find it. Therefore we define the event record in ZBasic as follows:

myEvent%=0‘event code
message&=0‘event message
when&=0 ‘ticks since startup
where&=0‘mouse location
modifiers=0 ‘modifier flags

The ‘what’ variable is the same location as myEvent% as shown by the Pascal record. The other variables of the record follow sequentially in memory. That is, the next variable declared is statically defined at the next memory location. The only thing left to do is use the GETNEXTEVENT statement to see what events happen. Of course it may be harder to decide what you want to happen when the event occurs. This is where the ZBasic built-in automatic statements would have been nice to use. When GETNEXTEVENT is called, the event record will then contain the desired information regarding what, when, where and other pertinent information. Unwanted events may be screened out if desired. Maybe you only want to know when a key is pressed and don’t care about any other events.

This quick overview will never be a substitute for your own experience, but I will attempt to explain some of the ‘features’ of the Sample program.

Mixing Event Manager Calls with ZBasic

The typical ZBasic program for the Macintosh should start out with the WINDOW OFF, COORDINATE WINDOW statements and if the mouse is used any place you will probably want to use the DEF MOUSE=-1 statement. These statements turn off the default window, set the coordinate system to pixel coordinates and set up the mouse to read in a more Macintosh like mode.

The charCodeMask and keyCodeMask variables are masks we may use to mask the keyboard events to get the character and/or key code of keys pressed. It would be helpful for you to read about the Toolbox Event Manager in Inside Macintosh for a complete overview events and how to handle them.

The label “EventLoop” starts the main event loop. You may have loops within loops, even using ZBasic event statements within subroutines called from the main loop, but just keep in mind how the events will be handled. ZBasic events should definitely be confined to their own subroutines and turned off at the end of the routine.

The SELECT-CASE statement lends itself very well to the toolbox implementation of event trapping. Be careful not to exit a CASE statement with out going through the END CASE statement. For example if you try to do a RETURN from within the CASE structure you may have unpredictable results, such as system bombs??

How to Handle Variable Screen Size

I’m excited about the new Macintosh II and the possibility of larger screens and color. This will also mean that programmers must be aware that much more, of the expected uses of their program. I suppose that if you know for certain that your application is only going to be run on a 9" screen Mac then there is no problem in programming the window to open to (0,0)-(512,342). Remember that Macintosh II or other users with large screens are not going to think much of your program if it doesn’t open to full screen size.

How do I know how big the screen is? Well, the answer is not found in your ZBasic manual. The manual will help you get there, but not without some help from Inside Macintosh. In Pascal, the Quickdraw global variable, screenbits.bounds, refers to the rectangle of the screen of the Macintosh being used. But ZBasic can’t access screenbits directly because it is accessed through internal 68000 registers relative to A5. Fortunately there is another way to do it. The global variable WMgrPort (at $9DE) points to Window Manager port. [ Note: Is there a better method of finding this global variable than hard coding a memory address which could change in future memory management implementations? How about calling the toolbox window manager routine GetWmgrPort? -Ed ] The Window Manager port is a grafPort that has the entire screen as its portRect and is used by the Window Manager to draw window frames.

For those of you that don’t know what a grafPort is: a grafPort includes a bitmap to draw in, a character font, patterns for drawing and erasing, and other pen characteristics. When you open a window, a grafPort is created for that window. You may set the grafPort to the current window by using the SETPORT call. The pointer to the grafPort of the current window can be found by using the statement: GET WINDOW #1, GrafPtr&, where GrafPtr& contains the pointer. More on this is found on page E167 of the ZBasic Manual (4th edition). Also found on that same page is a description of the grafPort record (also found on page I148 of Inside Macintosh).

Notice that the 8th byte of the record contains the boundary rectangle of the image (called PortRect). The boundary rectangle of the Window Manager Port is the entire screen of whatever Macintosh the application is being run on. Therefore all that is necessary is to PEEK LONG (2 bytes) the WMgrPort pointer to see what the boundary is. Example:

PortRecttop=PEEK WORD(WMgrPort&+8)
PortRectleft=PEEK WORD(WMgrPort&+10)
PortRectbottom=PEEK WORD(WMgrPort&+12)
PortRectright=PEEK WORD(WMgrPort&+14)

Now that you have the boundary you can open your window to an appropriate size, for example: (4,24)-(PortRectright-4,PortRectbottom-4) represents the rectangle the size of the entire screen minus the menu bar and a little on the sides for good looks. In the sample the variable windowrect%(0) represents the rectangle for the window opened by the program. More on GrafPorts can be found in chapter 6 (Quickdraw) and chapter 9 (Window Manager) of Inside Macintosh Vol. 1.

Toolbox Call Fixes ZBasic Bug

I found something about ZBasic type 1 windows that can be programmed around by opening your window with the NEWWINDOW toolbox function. If you use the following code instead of the NEWWINDOW method you will find that the right border of my blank window gets erased at the place where the scroll bars would be if I had any. Apparently, the window housekeeping for a type 1 window assumes or clears space for the scroll bars even if you don’t have any.

WINDOW 1,”Sample Window”,(dragleft, dragtop+20)-(dragright-4, dragbottom-4), 

This doesn’t happen if I use NEWWINDOW to create the window. You can see this as you type in some text and look at the characters that appear at the very right edge of the window.

I’m using ZBasic version 3.85 so hopefully this minor annoyance can be remedied by Zedcor. Fortunately, there is an alternative that is compatible with ZBasic statements. Remember some of the other Basic interpreters/compilers that aren’t so lucky.

As you can see from this example and some of the past few columns of Basic School here in MacTutor we are well on our way to creating a full text editor in ZBasic. Why is this important? Because it proves Basic really can access the power of the Mac ROMs and support real Mac programs. Stay tuned for more

REM  Sample Demo (adapted from Inside Macintosh)
REM ©MacTutor 1987
REM By Dave Kelly
everyevent=-1:REM ALL events
False=0:True=NOT False:doneflag=False
REM Setup the EventRecord
myEvent%=0:REM ‘what’ is first variable
DIM Rect%(3),windowrect%(3)
keyCodeMask&= VAL(“&H0000FF00”)
GOSUB “SetUpMenus”
PortRecttop=PEEK WORD(WMgrPort&+8)
PortRectleft=PEEK WORD(WMgrPort&+10)
PortRectbottom=PEEK WORD(WMgrPort&+12)
PortRectright=PEEK WORD(WMgrPort&+14)
CALL SETRECT(windowrect%(0), dragleft, dragtop+20,       
 dragright-4, dragbottom-4)
myWindow&=FN NEWWINDOW(0,windowrect%(0), “Sample Window”, 1, 
txRect1&=PEEK LONG(GrfPtr&+16)
txRect2&=PEEK LONG(GrfPtr&+20)
CALL INSETRECT(txRect1&,4,2)
textH&=FN TENEW(txRect1&,txRect1&)

“EventLoop”: REM Main Event Loop
 CALL SETRECT(Rect%(0),PEEK WORD (GrfPtr&+16), 
 PEEK WORD (GrfPtr&+18), PEEK WORD (GrfPtr&+20), 
 PEEK WORD (GrfPtr&+22))
 InRectangle=FN PTINRECT(xpos,Rect%(0))
 LONG IF FN GETNEXTEVENT(everyevent,myEvent%)
 SELECT myEvent%
 CASE 0 :REM No Event
 CASE 1 :REM mousedown
 wResult=FN FINDWINDOW(where&,whichwindow&)
 SELECT wResult
 CASE 0 :REM inDesk (do nothing)
 CASE 1 :REM inMenuBar
 mResult&=FN MENUSELECT(where&)
 GOSUB “DoCommand”
 CASE 2 :REM inSysWindow
 CALL SYSTEMCLICK(myEvent%,whichwindow&)
 CASE 3 :REM inContent
 LONG IF whichwindow& <> FN FRONTWINDOW 
 CALL SELECTWINDOW (whichwindow&)
 boolean=FN BITAND(modifiers,512)<>0
 CALL TECLICK (where&, boolean, textH&)
 CASE 4 :REM inDrag
 CALL SELECTWINDOW(whichwindow&)
 CALL DRAGWINDOW(whichwindow&, where&, dragtop)
 CASE 5 :REM inGrow
 CASE 6 :REM inGoAway
 CASE 2 :REM mouseup
 CASE 3,5 :REM keydown or autokey
 theChar&=FN  BITAND(message&,charCodeMask&)
 LONG IF FN BITAND(modifiers,256)<>0
 mResult&=FN MENUKEY(theChar&)
 GOSUB “DoCommand”
 CALL TEKEY(theChar&,textH&)
 CASE 4 :REM keyup
 CASE 6 :REM updateEvt
 CALL TEUPDATE(txRect1&,textH&)
 CASE 7 :REM diskEvt
 CASE 8 :REM activateEvt
 LONG IF FN BITAND(modifiers,1)<>0
 CASE 10:REM networkEvt
 CASE 11:REM driverEvt
 CASE 12:REM app1Evt
 CASE 13:REM app2Evt
 CASE 14:REM app3Evt
 CASE 15:REM app4Evt
UNTIL doneflag
APPLE MENU “About Sample”
MENU 1,0,1,”File”
MENU 1,1,1,”Quit/Q”
Mhndl2&=FN GETMHANDLE(130)
Mhndl0&=FN GETMHANDLE(255)
theMenu=FN HIWORD(mResult&)
theItem=FN LOWORD(mResult&)
SELECT theMenu
 CASE 255
 GOSUB “appleID”
 GOSUB “fileID”
 GOSUB “editID”
LONG IF theItem=1
 WINDOW 5,””,(100,100)-(400,250),-2
 TEXT 0,12,0,0
 PRINT @(2,2)”Sample adapted from Inside Macintosh”
 PRINT @(10,3)”by”
 PRINT @(8,4)”Dave Kelly”
 PRINT @(6,5)”©MacTutor, 1987"
 outsiderect=(MOUSE(1)<0 OR MOUSE(1)>300 OR MOUSE(2)<0 OR MOUSE(2)>150)
 UNTIL x<>0 AND NOT (outsiderect)
 CALL GETITEM(Mhndl0&,theItem,Var$)
 CALL SETPORT(myWindow&)
 SELECT theItem
 CASE 1:REM undo command
 CASE 3:REM cut command
 CASE 4:REM copy command
 CASE 5:REM paste command
 CASE 6:REM clear command


Community Search:
MacTech Search:

Software Updates via MacUpdate

RapidWeaver 6.0.5 - Create template-base...
RapidWeaver is a next-generation Web design application to help you easily create professional-looking Web sites in minutes. No knowledge of complex code is required, RapidWeaver will take care of... Read more
Alfred 2.6 - Quick launcher for apps and...
Alfred is an award-winning productivity application for OS X. Alfred saves you time when you search for files online or on your Mac. Be more productive with hotkeys, keywords, and file actions at... Read more
1Password 5.1 - Powerful password manage...
1Password is a password manager that uniquely brings you both security and convenience. It is the only program that provides anti-phishing protection and goes beyond password management by adding Web... Read more
GarageSale 6.9.2 - Create outstanding eB...
GarageSale is a slick, full-featured client application for the eBay online auction system. Create and manage your auctions with ease. With GarageSale, you can create, edit, track, and manage... Read more
calibre 2.17 - Complete e-library manage...
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
OmniGraffle Pro 6.1.2 - Create diagrams,...
OmniGraffle Pro helps you draw beautiful diagrams, family trees, flow charts, org charts, layouts, and (mathematically speaking) any other directed or non-directed graphs. We've had people use... Read more
OmniGraffle 6.1.2 - Create diagrams, flo...
OmniGraffle helps you draw beautiful diagrams, family trees, flow charts, org charts, layouts, and (mathematically speaking) any other directed or non-directed graphs. We've had people use Graffle to... Read more
RoboForm 2.0.2 - Password manager; syncs...
RoboForm is a password manager that offers one-click login, mobile syncing, easy form filling, and reliable security. Password Manager. RoboForm remembers your passwords so you don't have to! Just... Read more
Apple MainStage 3.1 - Live performance t...
Love the sound you got on your recording? MainStage 3 makes it easy to bring all the same instruments and effects to the stage. Everything from the Sound Library and Smart Controls you're familiar... Read more
Freeway Pro 7.0.2 - Drag-and-drop Web de...
Freeway Pro lets you build websites with speed and precision... without writing a line of code! With its user-oriented drag-and-drop interface, Freeway Pro helps you piece together the website of... Read more

Sentinel 4: Dark Star Adds New Campaign...
Sentinel 4: Dark Star Adds New Campaign and More Posted by Ellis Spice on January 27th, 2015 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Wheel & Deal Review
Wheel & Deal Review By Tre Lawrence on January 27th, 2015 Our Rating: :: SIMPLE FUNUniversal App - Designed for iPhone and iPad A simple arcade shooter that has a retro feel.   | Read more »
This Week at 148Apps: January 19-23, 201...
Warm Your Winter With New Apps!   How do you know what apps are worth your time and money? Just look to the review team at 148Apps. We sort through the chaos and find the apps you’re looking for. The ones we love become Editor’s Choice, standing out... | Read more »
Eggmaster Review
Eggmaster Review By Jennifer Allen on January 26th, 2015 Our Rating: :: BRIEFLY COMPELLINGUniversal App - Designed for iPhone and iPad Tap like crazy to gain eggs, so that you can buy upgrades to gain more eggs, and so on. It... | Read more »
Cloudy Or Dry – Funny Or Die Release a W...
Cloudy Or Dry – Funny Or Die Release a Weather App Posted by Ellis Spice on January 26th, 2015 [ permalink ] iPhone App - Designed for the iPhone, compatible with the iPad | Read more »
Mediocre, the Team Behind Smash Hit, is...
Mediocre, the Team Behind Smash Hit, is Teasing Their Latest Unnamed Project Posted by Jessica Fisher on January 26th, 2015 [ permalink ] | Read more »
Heroes of Gaia Review
Heroes of Gaia Review By Campbell Bird on January 26th, 2015 Our Rating: :: TIMERS OF MIGHT AND MAGICUniversal App - Designed for iPhone and iPad This free-to-play rpg looks a lot like Heroes of Might and Magic, but it’s poor... | Read more »
Choice Provisions is Set to Launch Destr...
Choice Provisions is Set to Launch Destructamundo on iOS This Month Posted by Tre Lawrence on January 23rd, 2015 [ permalink ] Choice Provisions – home stable to | Read more »
King of Thieves – An Interview With Zept...
Ahead of the release of ZeptoLab’s King of Thieves, we were able to ask ZeptoLab’s co-founder, Semyon Voinov, a few questions about the inspiration behind the game and what that means for the Cut the Rope franchise. | Read more »
Handle Review
Handle Review By Jennifer Allen on January 23rd, 2015 Our Rating: :: SPEEDY ORGANIZINGUniversal App - Designed for iPhone and iPad Handle is a very convenient way of juggling your emails, To Do list, and Calendar all through one... | Read more »

Price Scanner via

Save up to $340 on iMacs with Apple Certified...
The Apple Store has Apple Certified Refurbished iMacs available for up to $340 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. These are the best prices on... Read more
AppleCare Protection Plans on sale for up to...
B&H Photo has 3-Year AppleCare Warranties on sale for up to $105 off MSRP including free shipping plus NY sales tax only: - Mac Laptops 15″ and Above: $244 $105 off MSRP - Mac Laptops 13″ and... Read more
Apple refurbished Time Capsules available sta...
The Apple Store has certified refurbished Time Capsules available for up to $60 off MSRP. Apple’s one-year warranty is included with each Time Capsule, and shipping is free: - 2TB Time Capsule: $255... Read more
3TB AirPort Time Capsule on sale for $349, $5...
B&H Photo has 3TB AirPort Time Capsules on sale for $349 including free shipping plus NY sales tax only. Their price is $50 off MSRP, and it’s the lowest price available for this model (except... Read more
16GB iPad Air 2 on sale for $446, save $53
Walmart has 16GB WiFi iPad Air 2s on sale for $53 off MSRP on their online store. Choose free shipping or free local store pickup (if available). Sale prices available for online orders only, in-... Read more
Save up to $300 on a new Mac, $30 on an iPad,...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
MasterCard Brings Contactless Payment, Apple...
MasterCard, the official card of the Waste Management Phoenix Open, and the PGA TOUR are bringing the latest payment technology to the spectator experience with the introduction of contactless... Read more
Petitioning Dropbox For Mac OS X 10.4 and 10....
Last week Dropbox announced to its users that app support for Mac OS X 10.4 and 10.5 will end May 18 — disappointing news for those of us who are still getting useful service out of older PPC Macs... Read more
Stop Street Harassment, Bullying, and Assault...
The STOP-ATTACK ( app will leverage smartphone technology to make the world a safer place. Whether it’s bullying, street harassment or something even more sinister, the app... Read more
Stir Kinetic Desk M1 Standing Or Sitting Desk...
The age of the standing desk is upon us, and according to medical research, it’s arriving none too soon. The World Health Organization (WHO), reports that 60 to 85 percent of people worldwide lead... Read more

Jobs Board

Detailer *Apple* Ford Body Shop / Collision...
Apple Automotive is one of the fastest growing dealer…and it shows. Consider making the switch to the Apple Automotive Group today! At Apple Automotive , Read more
*Apple* Acura/Subaru Service Technicians - A...
Apple Automotive is one of the fastest growing dealer…and it shows. Consider making the switch to the Apple Automotive Group today! At Apple Automotive , Read more
Business Development Manager - *Apple* Pay...
**Job Summary** Apple Pay is seeking an experienced business development manager to support the identification, recruitment, negotiation and ongoing management of Read more
*Apple* Solutions Consultant (ASC)- Retail S...
**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 - Retail Sales...
**Job Summary** As an Apple Solutions Consultant (ASC) you are the link between our customers and our products. Your role is to drive the Apple business in a retail Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.