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

Minecraft 302 - Popular sandbox building...
Minecraft allows players to build constructions out of textured cubes in a 3D procedurally generated world. Other activities in the game include exploration, gathering resources, crafting, and combat... Read more
FotoMagico 5.2b8 - Powerful slideshow cr...
FotoMagico lets you create professional slideshows from your photos and music with just a few, simple mouse clicks. It sports a very clean and intuitive yet powerful user interface. High image... Read more
TeamViewer 11.0.65452 - Establish remote...
TeamViewer gives you remote control of any computer or Mac over the Internet within seconds, or can be used for online meetings. Find out why more than 200 million users trust TeamViewer! Free for... Read more
Dropbox 9.4.49 - Cloud backup and synchr...
Dropbox is an application that creates a special Finder folder that automatically syncs online and between your computers. It allows you to both backup files and keep them up-to-date between systems... Read more
Geekbench 4.0.0 - Measure processor and...
Geekbench provides a comprehensive set of benchmarks engineered to quickly and accurately measure processor and memory performance. Designed to make benchmarks easy to run and easy to understand,... Read more
Nisus Writer Pro 2.1.5 - Multilingual wo...
Nisus Writer Pro is a powerful multilingual word processor, similar to its entry level products, but brings new features such as table of contents, indexing, bookmarks, widow and orphan control,... Read more
Default Folder X 5.0.6 - 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 on... Read more
Alfred 3.1 - 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
MYStuff Pro 2.0.25 - Create inventories...
MYStuff Pro is the most flexible way to create detail-rich inventories for your home or small business. Add items to MYStuff by dragging and dropping existing information, uploading new images, or... Read more
OmniOutliner Pro 4.6 - Pro version of th...
OmniOutliner Pro is a flexible program for creating, collecting, and organizing information. Give your creativity a kick start by using an application that's actually designed to help you think. It's... Read more

Lifeline: Crisis Line (Games)
Lifeline: Crisis Line 1.0.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.0 (iTunes) Description: | Read more »
BLUK (Games)
BLUK 1.1 Device: iOS Universal Category: Games Price: $1.99, Version: 1.1 (iTunes) Description: ** ‘Upcoming Game of the Year’ Finalist at NGF Awards 2015 ** ** ‘Big Indie Pitch’ Nominee at Pocket Gamer Connects 2016... | Read more »
How to get coins faster in Madden NFL Mo...
All aboard the coin train. By that I mean you need coins to improve your team in Madden NFL Mobile. Whether you prefer the excitement of opening packs or hitting up the auction house, your squad won't get any better without more coins to spend. [... | Read more »
Six! Tips, tricks, and hints for beginne...
There's nothing pretentious about Six!, the latest release from Gram Games. As puzzlers go, it's so unassuming that it took me some time to even realize why it was called what it was. Somewhere, my high school geometry teacher is now sobbing... | Read more »
Mobius Final Fantasy: Multiplayer update...
Up until now, Mobius Final Fantasy has been about as single-player an experience as an RPG can be. Not only do you play solo, but you are literally one among a seemingly unending wave of faceless warriors on the road toward the same goal. [Read... | Read more »
Find out the story behind League of Ange...
If you’re looking for a new thrilling MMORPG to play with your friends then you’ll be excited to hear that there is a sequel to one of the most well known titles in the genre – namely League of Angels 2. With a brand new 3D engine offering... | Read more »
Naruto Shippuden: Ultimate Ninja Blazing...
I'm not sure if it's possible to say you are an anime fan but also never have seen one episode of Naruto. If it is, then I resemble that remark, and if not, I offer a hearty apology. [Read more] | Read more »
5 mobile games that let you explore spac...
No Man's Sky hasn't exactly turned out to be everything it was promised. Though its core concept of exploring an unimaginably vast universe of different planets is an intriguing one, the execution has left many PS4 and PC gamers feeling like they... | Read more »
Mummy madness in new action game Tomb He...
Hot on the tail of Bump Hero, ZPlay is giving gamers another reason to get screen bashing with a brand new release. Tomb Heroes is a challenging action game in which you battle enemies in various tombs around the world. You can select from nine... | Read more »
Siralim 2 (RPG / Roguelike) (Games)
Siralim 2 (RPG / Roguelike) 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Siralim 2 is an old-school monster catching RPG. Summon and customize hundreds of creatures to fight for you as... | Read more »

Price Scanner via

That Upgrade Itch; How Often Do You Upgrade Y...
I have a quandary to resolve as we head into what is typically a major Apple product upgrade season. My mid-2013 MacBook Air will be three years old and my iPad Air 2 will be two come late November.... Read more
Apple refurbished 12-inch iPad Pros available...
Apple has Certified Refurbished 12″ iPad Pros available for up to $160 off the cost of new iPads. An Apple one-year warranty is included with each model, and shipping is free: - 32GB 12″ iPad Pro... Read more
Tim Cook Posts Open Letter To The Apple Commu...
Apple Inc. CEO Tim Cook has posted an open letter commenting on the European Commission’s bizarre demand that Apple pay more than $14 billion in allegedly underpaid back taxes on its Irish... Read more
Streetwise Drivers Club App Now Features Open...
Streetwise Drivers Club, an app that rewards drivers with deals on everything from dining and gift cards to tires and insurance, has announced the launch of a new enhancement connecting app users... Read more
15-inch Retina MacBook Pros on sale for up to...
B&H Photo has 15″ Retina Apple MacBook Pros on sale for up to $200 off MSRP. Shipping is free, and B&H charges NY tax only: - 15″ 2.2GHz Retina MacBook Pro: $1799 $200 off MSRP - 15″ 2.5GHz... Read more
RESCUECOM 2016 Semi-Annual Computer Reliabili...
The beginning of a new school year is upon us again, in which students and parents have some very important choices to make, often including the purchase of a computer or tablet. Whether you are... Read more
VRS Design Damda Glide Series iPhone 7 and 7...
What makes the Damda Glide Series for the iPhone 7 and iPhone 7 Plus special? Case maker VRS Design says its Damda Glide Series is the first mobile case to incorporate a semi-automatic mechanism for... Read more
Apple refurbished iMacs available for up to $...
Apple has Certified Refurbished 2015 21″ & 27″ iMacs available for up to $350 off MSRP. Apple’s one-year warranty is standard, and shipping is free. The following models are available: - 21″ 3.... Read more
Clearance 2015 13-inch MacBook Airs available...
B&H Photo has clearance 2015 13″ MacBook Airs available for $350 off original MSRP. Shipping is free, and B&H charges NY sales tax only: - 13″ 1.6GHz/4GB/128GB MacBook Air (MJVE2LL/A): $829... Read more
Check Apple prices on any device with the iTr...
MacPrices is proud to offer readers a free iOS app (iPhones, iPads, & iPod touch) and Android app (Google Play and Amazon App Store) called iTracx, which allows you to glance at today’s lowest... Read more

Jobs Board

*Apple* Retail - Multiple Positions Norfolk,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Retail - Multiple Positions- Tampa,...
Job Description:SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
SW Engineer *Apple* TV - Apple Inc. (United...
The Apple TV team is looking for excellent software engineers with experience in hardware, media management, media playback, content delivery and a passion for Read more
*Apple* Solutions Consultant - Apple (United...
Apple Solutions ConsultantJob Number: 51218534Pleasant Hill, California, United StatesPosted: Aug. 18, 2016Weekly Hours: 40.00Job SummaryAs an Apple Solutions Read more
*Apple* Solutions Consultant - Apple (United...
# Apple Solutions Consultant Job Number: 51218354 Fredericksburg, Virginia, United States Posted: Aug. 18, 2016 Weekly Hours: 40.00 **Job Summary** As an Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.