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

Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
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 »

Price Scanner via MacPrices.net

May 2024 Apple Education discounts on MacBook...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $300 off the purchase of a new MacBook... Read more
Clearance 16-inch M2 Pro MacBook Pros in stoc...
Apple has clearance 16″ M2 Pro MacBook Pros available in their Certified Refurbished store starting at $2049 and ranging up to $450 off original MSRP. Each model features a new outer case, shipping... Read more
Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more
Every version of Apple Pencil is on sale toda...
Best Buy has all Apple Pencils on sale today for $79, ranging up to 39% off MSRP for some models. Sale prices for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more

Jobs Board

Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.