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}
END;

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:

WMgrPort&=PEEK LONG(&H9DE)
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), 
257
myWindow&=WINDOW(14)

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
WINDOW OFF
COORDINATE WINDOW
DEF MOUSE=-1
everyevent=-1:REM ALL events
False=0:True=NOT False:doneflag=False
REM Setup the EventRecord
myEvent%=0:REM ‘what’ is first variable
message&=0
when&=0
where&=0
modifiers=0
applemark=&H14
whichwindow&=0
DIM Rect%(3),windowrect%(3)
charCodeMask&=VAL(“&H000000FF”)
keyCodeMask&= VAL(“&H0000FF00”)
FLUSHEVENTS
GOSUB “SetUpMenus”
WMgrPort&=PEEK LONG(&H9DE)
PortRecttop=PEEK WORD(WMgrPort&+8)
PortRectleft=PEEK WORD(WMgrPort&+10)
PortRectbottom=PEEK WORD(WMgrPort&+12)
PortRectright=PEEK WORD(WMgrPort&+14)
dragtop=PortRecttop+24
dragleft=PortRectleft+4
dragbottom=PortRectbottom-4
dragright=PortRectright-4
CALL SETRECT(windowrect%(0), dragleft, dragtop+20,       
 dragright-4, dragbottom-4)
myWindow&=FN NEWWINDOW(0,windowrect%(0), “Sample Window”, 1, 
 0,1,0,0)
CALL SETPORT(myWindow&)
CALL GETPORT(GrfPtr&)
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
DO
 CALL SYSTEMTASK
 CALL TEIDLE(textH&)
 CALL SETRECT(Rect%(0),PEEK WORD (GrfPtr&+16), 
 PEEK WORD (GrfPtr&+18), PEEK WORD (GrfPtr&+20), 
 PEEK WORD (GrfPtr&+22))
 click=MOUSE(0):xpos=MOUSE(1):ypos=MOUSE(2)
 InRectangle=FN PTINRECT(xpos,Rect%(0))
 IF InRectangle THEN CURSOR 1 ELSE CURSOR 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&)
 XELSE
 CALL GLOBALTOLOCAL(where&)
 boolean=FN BITAND(modifiers,512)<>0
 CALL TECLICK (where&, boolean, textH&)
 END IF
 CASE 4 :REM inDrag
 LONG IF whichwindow&<>FN FRONTWINDOW
 CALL SELECTWINDOW(whichwindow&)
 XELSE
 CALL DRAGWINDOW(whichwindow&, where&, dragtop)
 END IF
 CASE 5 :REM inGrow
 CASE 6 :REM inGoAway
 END SELECT
 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”
 XELSE
 CALL TEKEY(theChar&,textH&)
 END IF
 CASE 4 :REM keyup
 CASE 6 :REM updateEvt
 CALL BEGINUPDATE(message&)
 CALL ERASERECT(txRect1&)
 CALL TEUPDATE(txRect1&,textH&)
 CALL ENDUPDATE(message&)
 CASE 7 :REM diskEvt
 CASE 8 :REM activateEvt
 LONG IF FN BITAND(modifiers,1)<>0
 CALL TEACTIVATE(textH&)
 CALL DISABLEITEM(Mhndl2&,1)
 XELSE
 CALL TEDEACTIVATE(textH&)
 CALL ENABLEITEM(Mhndl2&,1)
 END IF
 CASE 10:REM networkEvt
 CASE 11:REM driverEvt
 CASE 12:REM app1Evt
 CASE 13:REM app2Evt
 CASE 14:REM app3Evt
 CASE 15:REM app4Evt
 CASE ELSE
 END SELECT
 END IF
UNTIL doneflag
END
“SetUpMenus”
APPLE MENU “About Sample”
MENU 1,0,1,”File”
MENU 1,1,1,”Quit/Q”
Mhndl1&=FN GETMHANDLE(1)
EDIT MENU 2
Mhndl2&=FN GETMHANDLE(130)
Mhndl0&=FN GETMHANDLE(255)
RETURN
“DoCommand”
theMenu=FN HIWORD(mResult&)
theItem=FN LOWORD(mResult&)
SELECT theMenu
 CASE 255
 GOSUB “appleID”
 CASE 1
 GOSUB “fileID”
 CASE 2
 GOSUB “editID”
END SELECT
CALL HILITEMENU(0)
RETURN
“appleID”
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"
 MOUSE ON
 DO
 x=MOUSE(0)
 outsiderect=(MOUSE(1)<0 OR MOUSE(1)>300 OR MOUSE(2)<0 OR MOUSE(2)>150)
 UNTIL x<>0 AND NOT (outsiderect)
 MOUSE OFF
 WINDOW CLOSE 5
XELSE
 CALL GETITEM(Mhndl0&,theItem,Var$)
 mrefNum=FN OPENDESKACC(Var$)
 CALL SETPORT(myWindow&)
END IF
RETURN
“fileID”
doneflag=True
RETURN
“editID”
LONG IF NOT FN SYSTEMEDIT(theItem-1)
 SELECT theItem
 CASE 1:REM undo command
 CASE 3:REM cut command
 CALL TECUT(textH&)
 CASE 4:REM copy command
 CALL TECOPY(textH&)
 CASE 5:REM paste command
 CALL TEPASTE(textH&)
 CASE 6:REM clear command
 CALL TEDELETE(textH&)
 END SELECT
END IF
RETURN

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.