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

Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »

Price Scanner via MacPrices.net

New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.