TweetFollow Us on Twitter

AppleEvents, Mops
Volume Number:8
Issue Number:4
Column Tag:Jörg's Folder

Mops & More Apple Events

Mops is improved, again and more LS Fortran Apple Events

By Jörg Langowski, MacTutor Regular Contributing Author

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

Two themes this month: first, the OOPS Forth lovers among you will appreciate that Michael Hore has again improved his MOPS system (see also V7#9); we are at version 2.1 now. Second, we’ll continue a little our experiments with Apple Events; this time with some more examples in LS Fortran.

MOPS 2.1

Not even half a year after the announcement of Mops 2.0, I received a new diskette from Australia with Michael Hore’s newest release of MOPS, version 2.1. Again, he has added a whole stock of new things, and I only hope that the word will spread that this is probably one of the best high level programming systems on the Mac. Many systems that you pay a lot of money for get much less support from its developers than MOPS, which is free.

I wish MOPS many users, and wouldn’t actually be surprised if it went commercial one day. Up to now you can get it from me at langowski@frembl51.bitnet, though. I’ll also try again and post it on, although they don’t seem to receive my mailings somehow. The compacted MOPS system is 800 K long, so we can’t put it on the source code disk.

Here’s Michael’s letter and the release notes (edited somewhat):

Dear Jörg,

Thanks for a great writeup of Mops in the Sept. MacTutor! I’ve only got one complaint-now I’m surely going to get enquiries from non-Neon users and all kinds of people, so I really ought to write a manual! Horrors!!! (Seriously though, I’ve already started on it. I think I can reasonably assume some knowledge of Forth, and start from there. Maybe in another few months it’ll be ready. Maybe.)

Well, time never stands still, so here’s release 2.1. Sorry, but after your CtlWind example, what have I gone and done but altered the handling of windows with controls!! Would you believe it was a complete coincidence. I’ve introduced the “view” concept, similar to MacApp and TCL, so now controls belong to views, and views belong to windows. The changeover is very straightforward, though, and I think will make it much easier in the long run to put all kinds of things in windows. We don’t have fully automatic handling of scrolling yet, but that should come. The other big change is that classes can now be exported from Modules. All the changes are listed in the “Mops 2.1 release notes” file.

The other big news is that I’m isolated no longer! CompuServe is now in Australia, so anyone can now send email to me at [100033,3164]. I think I’ll have an InterNet address in the new year, too.

Michael Hore, PO Box 821, Nhulunbuy, NT 0881, Australia

[Parts of the release notes follow]

Classes can be exported from modules

Yes, it’s true! You can now define a class in a module, include the class name in the imports list, and instantiate objects of that class anywhere. In fact in the Mops system itself, we are now handling windows, menus and dialogs this way. All the methods of the class are in effect exported along with the class name; you don’t have to take any special action, apart from putting the class name in the imports list, and taking care with action handlers (see below). Whenever you send a message to an exported class, the module will be invoked automatically.

Naturally this has some performance implications. There is a fair amount of overhead involved in invoking a module. You can reduce this to some extent by locking the module over a number of calls (this is true for ordinary exported words as well). But if message execution for a particular class is really time-critical, it would really best to leave the class in the main dictionary. Where exported classes are most useful is for those classes that depend heavily on Toolbox calls for most of their methods (such as windows, menus and dialogs). Toolbox calls are generally much slower than Mops module invocations, so the extra time penalty of putting the class into a module won’t be significant.

Now for the point about action handlers. If the class is defined in module 1, let’s say, and if it is instantiated in another module, module 2, and if this object has action handlers which are also words from the module 2 (rather than in the main dictionary), you will need to declare these action handlers with a new syntax :a .... ;a (pronounced “colon A” and “semi A”) instead of : ... ; . This is because these action handlers will probably be invoked from the class implementation, in module 1, which amounts to a “back-door” entry to module 2. As I have pointed out in the main documentation file, this is a big no-no. But any word declared with the :a ... ;a syntax avoids this problem.

This is a rather subtle condition, so it is probably best simply to declare all action handlers with the :a ... ;a syntax no matter what-it won’t hurt. There is no performance penalty. In fact, :a definitions in the main dictionary compile identical code to normal definitions. And if you use :a definitions routinely, then it is always obvious if a word is an action handler. And this way, whenever you move class definitions into modules, you won’t run into the above problem.

Here are the technical details for those who are interested. An action handler is either in the main dictionary or a module. If it’s in a module, module 2 let’s say, the object using it must also be in module 2 (otherwise you would get a “Can’t store a module address outside the module” error when you tried to install the action handler in the object).

The problem comes up if the class implementation is in another module, say module 1. When a method (in module 1) invokes the action handler, A5 (modBase) will still be set up for module 1, and so will be wrong for the action handler (in module 2). So :a definitions, at the start, first push A5 on to the return stack, then set A5 to the correct value for the current module. This is done by PC-relative addressing, so it makes no assumptions about the previous value of A5. Then at the end of the definition (or if EXIT is done), the previous A5 value is popped back from the return stack.

Note that the overhead is only a few machine instructions. But if the :a word is compiled in the main dictionary, these extra instructions are unnecessary and are omitted, so there is no penalty at all. This is a blatantly undisguised attempt to encourage use of the :a syntax for all action handlers no matter where they are, which will minimize problems with moving class implementations into modules.

CallBefore and CallAfter

This is a new feature which has been in my “coming attractions” list, and has now arrived. It is a bit complex to explain, but if you don’t need this feature, ignore it. It is entirely optional, but can be really useful in some situations.

We have wanted to provide a bit more flexibility in the way a subclass overrides a method. Up to now, it could either override or not. If it did, it could possibly call the Super version of the method within the new definition, but that was all. A superclass had no way of limiting what a subclass may do. So now, along with other languages such as Flavors and Eiffel, we provide a superclass with the power to limit the extent to which a subclass may override a method, basically by allowing the provision of code which must be executed BEFORE the subclass’s version of the method executes, and code which must be executed AFTER the subclass’s method has finished. These pieces of code can do things like check that certain constraints haven’t been violated, or do some other obligatory setting up and winding up housekeeping.

The best way do describe this feature is by means of a real-life example-this code is extracted from class Window (now in the file WindowMod.txt):

/* 1 */

 get: fPrect\ Save fPrect as it might get changed
 ^base  call BeginUpdate   ;m

 ^base  call EndUpdate
 put: fPrect   ;m\ Restore fPrect

callFirst setup_draw:

:m  DRAW: (draw): self   ;m

Drawing to a window in response to an update event requires certain housekeeping chores to be done at the beginning and the end. Rather than require them to be repeated

in every window subclass that overrides Draw:, we move them into two private methods, Setup_draw: and Windup_draw:. Then we use the callFirst and callLast syntax to specify that these methods are to be called (as messages to Self) before and after Draw: , respectively. Whenever Draw: is redefined in a window subclass, Setup_draw: and Windup_draw: are executed at the beginning and the end, so that the housekeeping code doesn’t need to be repeated (and you can even forget what it is, if you want to).

Note that the CallFirst and CallLast declarations always apply to the next method declared. You can actually use these declarations more than once, as long as all the CallFirsts come before the CallLasts. A subclass may add methods to the CallFirst and CallLast list of any method (thus, the subclass doesn’t need to know if there are already CallFirst or CallLast declarations in existence for a method it is overriding).

There is no need for CallFirst or CallLast messages to be private, although we have done it in this example. But it wouldn’t really make much sense to call them directly from the outside world.

The order of execution is significant. All entries on the CallFirst list are called in order from the beginning to the end. Thus the CallFirst entries specified by the highest superclass get executed first. This is exactly what you would expect, given the hierarchical nature of Mops code.

But notice carefully, that the same logic applied to the CallLast list means that the entries specified by the highest superclass should get executed last. So what we do is execute the entries in the CallLast list from the end backwards. The entries are put on the list simply in the order they are declared, but they will be executed in the reverse order.

A CallFirst or CallLast method is executed as an early-bound message to Self. All stack parameters and results will be as they are for the method to which the CallFirst/CallLast is being applied. If this “main” method uses the named parameters syntax, then at the time any CallFirst method is invoked these parameters will still be on the stack. Thus the CallFirst method is free to use the named parms syntax itself, as long as it pushes the parms back on the stack when it finishes-otherwise the main method would find its parameters had mysteriously disappeared!

I probably shouldn’t say this. But there is a way to override a CallFirst/CallLast. Forth programmers are notoriously anarchic, and may resent a superclass autocratically decreeing that certain things must take place at the beginning and end of the method they are about to write. (Even if they wrote the superclass themselves. Especially if they wrote it themselves.) Well... the entries on the CallFirst/CallLast lists are simply the hashed forms of the selector names. The binding isn’t actually done until the main method is compiled, at which time the hashed selectors are grabbed and used to insert calls to Self at the appropriate places. So... if, earlier in the class, you have declared a method with the same name as a CallFirst or CallLast method declared in a superclass, the normal method lookup process will find this new method first, and it will be called instead! Now forget you ever read this. Thanks.

MacApp, TCL, and windows with controls

I have been looking at both MacApp and TCL, since these are undoubtedly destined to become the “mainstream” OOP systems on the Mac. I plan to progressively incorporate various ideas from these into Mops. This, I hope, can be done entirely by the addition of new classes, rather that the alteration or replacement of anything there already. Well having said that, I’m going to have to say that I really hope that the following change will be a rare exception!

This change involves the handling of controls within windows, and it unfortunately may affect some existing code. I am really sorry about that, but I think the change is a definite improvement, and will simplify the implementation of windows with complex controls. Anyway the changes to existing code ought to be fairly mechanical.

MacApp and TCL both have the philosophy that anything that can appear on the screen is a “view”, and views may be hierarchical-views may contain any number of subviews. Thus it is straightforward to have a window with scroll bars which can contain a little rectangle of scrolling text with its own separate scroll bars. Also multiple panes in windows can work along similar lines.

So what we now have in Mops, is a new class, View, which logically comes between a window and its controls. Controls now no longer belong directly to a window as such, but they belong to a view, and views belong to windows.

The new window class which supports views is Window+ (in the Toolbox Classes folder). This class replaces CtlWind. Each window+ object has one special view which corresponds to the whole content area of the window; we call this the ContView. The address of this view is passed to a Window+ object when NEW: is called, and otherwise the view doesn’t need any special initialization. Controls work exactly as they always did, except that where you used to pass a window address to various methods of controls, you now pass a view address.

Thus if you already have a CtlWind, it can be changed over to the new scheme quite easily. The CtlWind becomes a Window+. Declare a view, and add that view’s address to the parameters passed to NEW: on the window+. Then all the messages you send to your controls need to have the view passed instead of the former CtlWind. Here is an example (from InstlMod.txt):


vScroll VS1
vScroll VS2


 wRect “  “ dlgWind true false  new: iWind
 180 15 48 iWind  new: vs1  180 85 48 iWind  new: vs2


vScroll VS1
vScroll VS2

window+ IWIND
view    IVIEW

 wRect “  “ dlgWind true false  iView  new: iWind
 180 15 48 iView  new: vs1  180 85 48 iView  new: vs2

I have also added a new “Scroller” class, which is a subclass of View, and makes it easier to add scroll bars to a rectangular area. It’s not really complete yet, but may be worth a look. If you use a Scroller as the ContView of a Window+, then when you resize the window the scroll bars automatically do the right thing. In the next Mops release I expect to be able to enhance Scroller along the lines of the Panorama idea in TCL, where Scroller will automatically handle scrolling of its subviews, whenever they take up a larger area than the Scroller view itself.

When you execute the Draw: method on a view, the clip region will have been set to the bounding rectangle for the view, and the coordinate origin will have been changed so that the top left corner of this rectangle is at (0, 0). Both MacApp and TCL do something very similar, so I guess it’s a good idea. Also, it was easy. This whole thing is achieved in Mops with just a few lines of code in the View class, thanks to the CallFirst and CallLast feature.

I hope soon to give some thought to the “command” class in MacApp which makes “Undo” so straightforward, and also to the idea of a command hierarchy as implemented by both MacApp and TCL, in which various classes in turn can have a shot at an incoming command. I expect something in this area will turn up in the next Mops release.

Bugs fixed

There was a bug involving Install, when the installed application used fWind. This window wasn’t being properly initialized when the application was called, and wouldn’t appear on the screen. This is now fixed.

There was a very subtle bug involving indexed ivars not being properly set up in certain particular situations. This is now fixed too.

I also found and fixed a couple of obscure bugs involving optimization of floating point code (i.e., with UseFPU? set True).

I have just found that the Debug command generates a system error 28 when running in virtual memory mode in System 7. I won’t delay this release, especially as I am just about to go on holidays, but hope to fix this in the next release. If you need to use Debug, do it in real mode. If you aren’t using System 7 yet, this won’t affect you.

[end of release notes - letter continues]

MOPS - the fastest high-level language for the Mac?

I think I might have been underselling the performance of Mops. I was very interested in the April MacTutor article by Jonathan Bell, “Beat the Optimizer!” Now people who want to use a high-level language but are primarily interested in number-crunching performance generally use Fortran. Jon documents some extensive speed testing on floating-point matrix multiplication using Language Systems Fortran, both optimized and unoptimized, and also using hand-coded assembler. So I thought this might be a good chance to see how the performance of Mops stacks up.

Jon’s article gives all the details about matrix multiplication, so I won’t repeat it here. Anyway, the main bit of code that we are interested in for performance purposes is the innermost of the three nested DO loops. For the multiplication of matrices A and B to give result matrix C, Jon gives this loop as

 DO K = 1, M
 SUM = SUM + A(I,K) * B(K,J)

This loop goes over a row of A and a column of B and the eventual value of SUM is assigned to C(I,J).

This loop involves a floating multiplication and a floating add, as well as array indexing calculations. Jon shows how LS Fortran optimization levels 2 and 3 move the indexing calculations out of the loop to improve performance.

Now for some philosophy. No self-respecting Forth programmer would write the equivalent of the above code. As Jon points out, successive accesses to matrices A and B are a constant distance (or “stride”) apart (although different for A and B). In Forth, where lean and mean is the order of the day, the programmer, not the compiler, would have the responsibility for writing code that exploits this fact (which isn’t really very hard). It shouldn’t be the job of a Forth compiler to improve terrible code!

Still, to be quite fair, and to avoid accusations of cheating, I did it both ways in Mops. I wrote a matrix class, and included ROW: and COL: methods. These return a start address, a limit address and a “stride”, ready for a DO loop over the row or column. Using these methods, the inner loop becomes

(don’t need the limit here )

i col: B -> stride -> Baddr drop

Alimit Aaddr

do i f@ Baddr f@ f* ++> %sum

stride ++> Baddr

12 +loop

(Aaddr, Alimit, Baddr and stride are all local variables. %sum is a floating local. The stride value for a matrix row in Mops is always 12, so this value is used to step through a row of the A matrix. The stride for a column of the B matrix is obtained from the col: B call.)

Doing a straight conversion from Fortran, without using the new methods, we have

 m 0 do
 k i  at: A   i j  at: B   f*  ++> %sum

Now for the results. I have a IIsi with FPU, so Jon’s results for an SE/30 are comparable if we allow for the difference in clock speeds (16 Mhz for the SE/30, 20 Mhz for the IIsi). Accordingly I have scaled my results by 20/16 to get figures which should compare meaningfully with Jon’s SE/30 results.

There are three sets of results. Mops has a value FPU? which is set True by the startup code if an FPU is present. If we set this flag False, even with an FPU present, we force Mops to call SANE for all floating operations.

Here are Jon’s SE/30 results for SANE, with Mops underneath. Times are average times, in seconds, for a 500 * 500 matrix multiply.

total calcs overhead

LSF1 26.283 21.773 4.510

LSF2 22.755 21.653 1.102

Mops(normal) 26.99 23.35 3.64

Mops(slow) 35.22 23.38 11.85

The Mops results aren’t as good as LSF here, but it was handicapped. If we leave the FPU? flag alone, Mops finds at startup that there is an FPU, and sets the flag True. The Mops FP routines for the common operators test this flag and bypass SANE if it is True. This gives a second set of results which doesn’t really correspond to any of Jon’s, since LS Fortran doesn’t apparently have this feature. But we can see that bypassing SANE is well worth doing:

total calcs overhead

Mops(normal) 9.92 6.28 3.64

Mops(slow) 18.34 6.50 11.85

Note that this is code which will run on any Mac, since the presence of the FPU is determined on the fly. Even the simple-minded, “slow” version is faster than LSF2, and the “normal” version is more than twice as fast. The “overhead” came out the same as in the previous test, which is good, because it ought to.

The third set of results for Mops is obtained by setting another value, UseFPU? to True. This produces code which utilizes the FPU in line, with some optimization, and so corresponds to the LSF -mc68882 option.

Here are the results:

total calcs overhead

LSF1 3.998 2.182 1.817

LSF2 2.873 2.158 0.715

Assembly 1.355 1.192 0.163

Mops(normal) 1.62 1.26 0.35

Mops(slow) 11.81 1.09 10.72

The “calcs” figure in the last line is definitely underestimated-it is difficult to isolate the “overhead” meaningfully, so I just fetched the floating values to the stack and then dropped them, a process which would overestimate the overhead in most situations. With the FPU being used directly, the calculations are so fast that the error is magnified by comparison.

Anyway the main point to note is that the “normal” Mops times are almost twice as good as LSF2, and very competitive with hand-coded assembly. This is largely because Mops detects sequences of FP operations and leaves the intermediate results in the FPU’s registers. Also FP named local variables and parameters are assigned to FPU registers (up to 6). Moving floating values to and from the FPU is fairly slow, and Mops tries to avoid it if it can. Looking at the generated machine code, the time penalty as compared with assembly is largely in the DO loop operations rather than in the FP instructions. Even this overhead could be reduced by using a FOR ... NEXT loop.

I’m now going to make the outrageous assertion that provided normal Forth philosophy is followed, Mops produces faster code than any other high-level language for the Mac. Would anybody like to prove me wrong?

End of Michael’s letter. If only C wasn’t so much in fashion, this could be one of the most widely used languages on the Mac. Really.

Example 1: MOPS’ matrix methods

\ Matrix timing test.  Nov 91.

need     floating point

\  Usage:   50 100  dimension   Fmatrix MM

    0     value    ROWDIM
    0     value    COLDIM

            -> colDim   -> rowDim
            colDim  rowDim  *  ;

:class   FMATRIX         super{  Farray  }

            var      #rows
            var      #cols
            var      rowLength
            var      colLength

:m  #ROWS:    get: #rows   ;m
:m  #COLS:      get: #cols   ;m

:m  ^ELEM:  { row col \ temp - addr }
            row  get: #cols  *  col +   ^elem: super   ;m

:m  AT:             ^elem: self  f@   ;m

:m  TO:             ^elem: self  f!   ;m

:m  ROW:  { row - limit start stride }           
                        \ Sets up for a DO over the row.
            row  get: rowLength *   idxBase +     \ addr
            get: rowLength  bounds           \ ( limit addr )
            12   ;m                                                                                    \ stride

:m  COL:  { col - limit start stride }  
                        \ Sets up for a DO over the column.
            col 12 *  idxBase +    \ addr
            get: colLength  bounds             \ ( limit addr )
            get: rowLength   ;m                             \ stride

:m  PUTROW:  \ ( 1st ... last  row - )
            row: self   drop  ( we know stride is 12 )
            swap   12 -
            do   i  f!   -12 +loop   ;m

:m  PRINTROW:  { row - }
            row  row: self    drop
            ?do   i f@ 10 e.r   12 +loop    ;m

:m  PRINTCOL:  { col \ stride - }
            col  col: self   -> stride
            ?do   i f@  10 e.r  cr   stride +loop    ;m

:m  PRINT:
            get: #rows  0
            ?do   i printRow: self  cr   loop   ;m

            rowDim  put: #rows   colDim  put: #cols
            get: #cols 12 *  put: rowLength   
            get: #rows  get: rowLength *   put: colLength
            classinit: super   ;m


5 3 dimension  Fmatrix         FF

objPtr A          class_is  Fmatrix
objPtr B         class_is  Fmatrix
objPtr C          class_is  Fmatrix

: DIMSCHK  { l m n - }
            #rows: B        m         <>
            l  #rows: C     <>
            n  #cols: C      <>
            or  or  
abort” Wrong operand dimensions for matrix multiply”   ;

: MXMPY  { m1 m2 m3 \
                                     l m n  Aaddr Alimit Baddr stride %sum - }
            m1 -> A   m2 -> B   m3 -> C
            #rows: A  -> l   #cols: A  -> m   #cols: B  -> n
            l m n  dimsChk
            l  0  do
                        i row: A  drop   -> Aaddr  -> Alimit
                        n  0  do
                                    0.0 -> %sum
                                    i col: B  -> stride  -> Baddr  drop
                                    Alimit  Aaddr
                                    do        i  f@  Baddr f@   f*  ++> %sum
                                                stride ++> Baddr
                                    12 +loop
                                    %sum   j i to: C
            loop   ;

: DUMMY  { m1 m2 m3 \
                                     l m n  Aaddr Alimit Baddr stride %sum - }
            m1 -> A   m2 -> B   m3 -> C
            #rows: A  -> l   #cols: A  -> m   #cols: B  -> n
            l m n  dimsChk
            l  0  do
                        i row: A  drop   -> Aaddr  -> Alimit
                        n  0  do
                                    0.0 -> %sum
                                    i col: B  -> stride  -> Baddr  drop
                                    Alimit  Aaddr
            \          i f@   Baddr f@   f2drop
            \ Note: omit this line entirely for UseFPU? True test,
            \ otherwise overhead figure is artificially high.
                                                stride ++> Baddr
                                    12 +loop
                                    %sum   j i to: C
            loop   ;

: SLOWMPY  { m1 m2 m3 \ l m n %sum - }
            m1 -> A   m2 -> B   m3 -> C
            #rows: A  -> l   #cols: A  -> m   #cols: B  -> n
            l m n  dimsChk
            l  0  do
                        n  0  do
                                    0.0 -> %sum
                                    m 0 do
                                                k i  at: A   i j  at: B   f*  ++> %sum
                                    %sum   j i to: C
            loop   ;

: SLOWDUMMY  { m1 m2 m3 \ l m n %sum - }
            m1 -> A   m2 -> B   m3 -> C
            #rows: A  -> l   #cols: A  -> m   #cols: B  -> n
            l m n  dimsChk
            l  0  do
                        n  0  do
                                    0.0 -> %sum
                                    m 0 do
                                                k i  at: A   i j  at: B   f2drop

            %sum   j i to: C
            loop   ;

3 5 dimension  fmatrix  matA
5 3 dimension  fmatrix  matB
3 3 dimension  fmatrix  matC

-2.0 -7.0 -4.0 8.0 1.0        0  putRow: matA
-3.0 0.0 -1.0 0.0 -9.0        1  putRow: matA
0.0 -1.0 -8.0 -9.0 -3.0      2  putRow: matA

-1.0 3.0 -2.00  putRow: matB
4.0 -1.0 1.0  1  putRow: matB
9.0 -4.0 -8.02  putRow: matB
-5.0 0.0 -3.03  putRow: matB
6.0 3.0 -6.0  4  putRow: matB

0.0      fvalue  TOTAL
0.0      fvalue  OVERHEAD
0.0      fvalue  CALCS
0.0      fvalue  SLOWTOTAL
0.0      fvalue  SLOWOVERHEAD
0.0      fvalue  SLOWCALCS

: MATINIT        \ ( mat - )
            -> A
            #rows: A  0
                        #cols: A  0
                                    i j +  >float  j i to: A
            loop   ;

: TICKSglobal Ticks  @  ;

: .RESULTS      \ ( flt - )
            fdup  6  f.r  6 spaces
            20.0  f*  16.0 f/   .” scaled: “  6  f.r   cr  ;

: TIMER  { mx1 mx2 mx3 - }
            mx1 matinit   mx2  matinit
            10 0 do   mx1  mx2  mx3  mxmpy   loop
            ticks  swap -  >float  600.0 f/  -> total
            10 0 do   mx1  mx2  mx3  dummy   loop
            ticks  swap -   >float  600.0 f/  -> overhead
            total  overhead  f-  -> calcs
            10 0 do   mx1  mx2  mx3  slowmpy   loop
            ticks  swap -  >float  600.0 f/  -> slowtotal
            10 0 do   mx1  mx2  mx3  slowDummy   loop
            ticks  swap -  >float  600.0 f/  -> slowoverhead
            slowTotal  slowOverhead  f-  -> slowCalcs
            .” Total         “  total  .results
            .” Calcs       “  calcs  .results
            .” Overhead”  overhead  .results
            .” Slow total”  slowTotal  .results
            .” Slow calcs”  slowCalcs  .results
            .” Slow overhead”  slowOverhead  .results  ;

50 50 dimension  fmatrix  SOURCE
50 50 dimension  fmatrix  RESULT

Adding more Apple Events to Fortran code

At the end, I would like to show you how to use more than the four required ‘built-in’ Apple Events in Language Systems Fortran. The high level event support in the Fortran run time system contains the subroutine F_SendEvent, which will send an ‘aevt’ class Apple Event, and takes three parameters: the first is the four character event ID, ‘EVT1’ or ‘EVT2’ in our case, the second is the name of the target application that the event is sent to, and the third specifies an optional file name. There are some predefined target application names: ‘*browse’ specifies that the target process should be selected with the PPC browser (the ‘Select a program to link to:’ dialog), ‘*lastbrowse’ means that the last process selected with the browser is the target, and ‘*sender’ sends the event to the process that last sent an ‘odoc’ event to this application.

There are some limitations; you can not (for the moment, I hope this will change) use an event class other than ‘aevt’, and you cannot send any data with the event, except for specifying a file name in the third parameter. But because this name is converted by the sending routine into a ‘file system specifier’, this has to be the name of a real-existing file, you cannot just send any character string here (I tried this to add data to the Apple event - no luck).

In order to receive an Apple Event other than one of the four required ones, you have to install a new event handler for it. The main program in example 2 does just this - installs the event handlers via the AEInstallEventHandler function and sets up a new menu with two items which correspond to the two subroutines that send the two types of events. When one of the menu items is selected, you can choose a target process with the PPC browser and the event will be sent to it. If you try to send an event to yourself, you’ll notice something funny: the program will seem to hang for a while and then finally report an error message, but the receive message will also be printed! This is because the event has been posted OK and will be eventually taken by the program, but only on the next passage through its main event loop. Now, because F_SendEvent uses a send mode that waits for the event to have arrived at its target until a timeout, the receipt of the event will never be acknowledged. The send routine waits patiently until it times out (about a minute), then returns with an error message, which will be displayed in the output window together with the message that is printed by the receiving routine. When you make a duplicate of the AEMenu program (on the source code disk) and launch both the original and the copy, sending messages between the two programs works fine.

Actually, this should have been an example on distributed processing. What I wanted to show was how you can split up a lengthy operation, such as multiplication of large matrices, into chunks that can be processed independently and later be assembled to a final result. This requires that you can send data with the event, have that processed by the other program (possibly on another machine), and have the result sent back to you. Sorry, but my exploration have not come that far yet because the generic Apple Event send routine that I wanted to write always broke down on me. An Apple Event is such a complex data structure that it is hard to see where you’ve made a mistake when the send routine returns with an error message. In other words, Apple Events are hard to debug; if someone out there knows a good utility that can be used to debug Apple Events, I’d appreciate to know about it. Until then, I’ll work on a more extended high level event example. The idea of doing distributed processing through Apple Events is really intriguing. You might imagine little ‘math routine servers’ turning as background processes on Macintoshes on some network; when these machines are not used for heavy calculations, like when someone is just typing text into the machine like I am doing right now, these servers can be used by other machines on the network to help doing their number crunching. I am convinced that a large percentage of the raw power of big computer installations is contained in the workstations on user’s desks, and these machines are not being used most of the time. Distributed processing may help in channeling some of that power.

Example 2: Adding new Apple Events in Fortran

!!M Inlines.f
!!G AEvent.finc
 program AEMenu

 implicit none
 external action1, action2, AE1, AE2
 integer*2 err
 err = AEInstallEventHandler (%val(‘aevt’),
 1 %val(‘EVT1’),%val(%loc(AE1)),
 2 %val(int4(0)),%val(int2(0))) 
 if (err. ne. 0) then
 type *,’Error installing first Apple event, 
 1 result code = ‘,err
 end if
 err = AEInstallEventHandler (%val(‘aevt’),
 1 %val(‘EVT2’),%val(%loc(AE2)),
 2 %val(int4(0)),%val(int2(0))) 
 if (err. ne. 0) then
 type *,’Error installing second Apple event, 
 1 result code = ‘,err
 end if
 call AddMenuItem (‘AE menu’,’action1’,action1)
 call AddMenuItem (‘AE menu’,’action2’,action2)

 subroutine action1
 implicit none
 integer*2 err,F_SendEvent
 external F_SendEvent
 err = F_SendEvent (‘EVT1’,’*browse’,0)
 type *,’Sent EVT1. Error code = ‘,err

 subroutine action2
 implicit none
 integer*2 err,F_SendEvent
 external F_SendEvent
 err = F_SendEvent (‘EVT2’,’*browse’,0)
 type *,’Sent EVT2. Error code = ‘,err
 integer*2 function 
 1 AE1(theAppleEvent,reply,%val(handlerRefCon))
 record /AppleEvent/ theAppleEvent
 record /AppleEvent/ reply
 integer*4 handlerRefCon
 type *,’Event 1 received’
 AE1 = 0! noErr

 integer*2 function 
 1 AE2(theAppleEvent,reply,%val(handlerRefCon))
 record /AppleEvent/ theAppleEvent
 record /AppleEvent/ reply
 integer*4 handlerRefCon
 type *,’Event 2 received’
 AE2 = 0 ! noErr


Community Search:
MacTech Search:

Software Updates via MacUpdate

Tor Browser 11.5.8 - Anonymize Web brows...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Alarm Clock Pro 15.0 - $19.95 (91% off)
Alarm Clock Pro isn't just an ordinary alarm clock. Use it to wake you up in the morning, send and compose e-mails, remind you of appointments, randomize the iTunes selection, control an internet... Read more
Google Chrome 107.0.5304.121 - Modern an...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
calibre 6.9.0 - Complete e-book library...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more
Safari Technology Preview 16.4 - The new...
Safari Technology Preview contains the most recent additions and improvements to WebKit and the latest advances in Safari web technologies. And once installed, you will receive notifications of... Read more
FileZilla 3.62.2 - Fast and reliable FTP...
FileZilla (ported from Windows) is a fast and reliable FTP client and server with lots of useful features and an intuitive interface. The FileZilla Client not only supports FTP, but also FTP over TLS... Read more
djay Pro 4.0.13 - Transform your Mac int...
djay Pro provides a complete toolkit for performing DJs. Its unique modern interface is built around a sophisticated integration with iTunes and Spotify, giving you instant access to millions of... Read more
Opera 93.0.4585.21 - High-performance We...
Opera is a fast and secure browser trusted by millions of users. With the intuitive interface, Speed Dial and visual bookmarks for organizing favorite sites, news feature with fresh, relevant content... Read more
AppCleaner 3.6.6 - Uninstall your apps e...
AppCleaner allows you to uninstall your apps easily. It searches the files created by the applications and you can delete them quickly. Supports macOS Ventura. Fixed an issue causing failed updates... Read more
QuickBooks - Financial manag...
QuickBooks helps you manage your business easily and efficiently. Organize your finances all in one place, track money going in and out of your business, and spot areas where you can save. Built for... Read more

Latest Forum Discussions

See All

‘Top Hunter Roddy & Cathy’ Review –...
The NEOGEO is generally characterized by, with only a few notable exceptions, fighting games and Metal Slug. Within a couple of years of its launch, the vast majority of the output on the console seemed to be mining (quite successfully) a few... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for November 28th, 2022. In today’s article, we’ve got a pair of reviews to check out. Full reviews of Pokemon Scarlet and Violet and The Oregon Trail are waiting for you to read. There’... | Read more »
‘OPUS: Echo of Starsong’ Interview: Port...
With OPUS: Echo of Starsong ($8.99) having finally launched on iOS after hitting PC and consoles, I had a chance to talk to Scott Chen who is the co-founder and executive producer of Sigono. In our chat, I touched on topics like game subscription... | Read more »
Best iPhone Game Updates: ‘Rush Rally 3’...
Hello everyone, and welcome to the week! It’s time once again for our look back at the noteworthy updates of the last seven days. As November breaths its last, the holiday season is right around the corner. That means we should start seeing more... | Read more »
‘Total Football’ is an Arcade-Style Socc...
GALA SPORTS recently launched its brand new soccer title, Total Football, and, true to its name, it is a pure arcade-style soccer game in the same vein as FIFA Mobile and PES Mobile. It also features official licensing from FIFPro and Manchester... | Read more »
Genshin Impact will recieve two new char...
HoYoverse has announced that Genshin Impacts version 3.3 will be arriving on December 7th. Titled All Senses Clear, All Existence Void, the update will bring two powerful new characters and a brand new card-based minigame. [Read more] | Read more »
‘Wreckfest’ Mobile Compared With Console...
HandyGames’ mobile version of Bugbear’s demolition derby-style racer Wreckfest ($9.99) released on iOS and Android recently, and we featured it as our Game of the Week. | Read more »
Black Friday Deals Here – The TouchArcad...
After taking a couple of weeks off we return on this glorious Black Friday with another episode of The TouchArcade Show. We get into a big discussion about virtual assistants like Alexa, Siri, and Google, and their place in the greater smarthome... | Read more »
TouchArcade Game of the Week: ‘Station 1...
I’m a big fan of Glitch Games and their unique brand of point-and-click adventure/escape room/puzzle games, and while they’re a tiny outfit and there’d typically be a couple years gap in-between their new releases, they were always worth the wait.... | Read more »
SwitchArcade Round-Up: ‘Super Lone Survi...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for November 25th, 2022. Today we look at the remaining releases for the week, and I’ll be honest with you: it’s not a great assortment. Still, there are at least a couple of things... | Read more »

Price Scanner via

Cyber Monday: 24″ Apple M1 iMacs for $150 off...
Amazon has Apple’s 24″ M1 iMacs on Black Friday sale for $150 off MSRP. Their prices are currently the lowest available for new iMacs among the Apple retailers we track: – 24″ M1 iMacs (8-Core CPU/7-... Read more
Cyber Monday Sale: 25% off Apple MagSafe acce...
Apple retailers are offering MagSafe accessories for up to 25% off MSRP for Cyber Monday. Here are the best deals available, currently from Verizon and Amazon: (1) Verizon has Apple MagSafe Chargers... Read more
Cyber Monday Sale: Apple AirPods for up to $1...
Looking for Apple AirPods, AirPods Pro, or AirPods Max this Cyber Monday? Look no further than our Apple AirPods Price Tracker. We track prices from 20+ Apple retailers and update the tracker... Read more
Final day for Apple’s Black Friday/Cyber Mond...
CYBER MONDAY Apple’s four day Black Friday/Cyber Monday 2022 event is now live and will run from November 25, 2022 to November 28, 2022 (ends today!). Receive a free $100-$250 Apple Gift Card with... Read more
Cyber Monday: Apple 13″ M2 MacBook Airs for $...
Apple retailers have posted their Cyber Monday prices on 13″ MacBook Airs. Take up to $200 off MSRP on M2-powered Airs with these sales with prices starting at only $1049. Free shipping is available... Read more
The best Cyber Monday iPhone sale? This $500...
If you switch to Xfinity Mobile and open a new line of service, they will take $500 off the price of a new iPhone, no trade-in required. This is the best no trade-in Cyber Monday Apple iPhone 14 deal... Read more
Cyber Monday Sale: Apple 16″ MacBook Pros for...
Amazon is offering $500 off MSRP discounts on Apple 16″ MacBook Pros with M1 Pro CPUs as part of their Cyber Monday sale. Their prices are the lowest available for these models from any Apple... Read more
Cyber Monday Sale: Apple 14″ MacBook Pros for...
Amazon is offering $300-$500 off MSRP discounts on Apple 14-inch MacBook Pros with M1 Pro CPUs as part of their Cyber Monday sale. Their prices are the lowest available for these models from any... Read more
Cyber Monday Sale: Apple Watch Ultra for $60...
Amazon has Apple Watch Ultra models (Alpine Loop, Trail Loop, and Opean Bans) on sale for $60 off MSRP as part of their Cyber Monday sale, each including free shipping, reducing the price for an... Read more
Cyber Monday MacBook Sale: 13″ M1 Apple MacBo...
Amazon has Apple 13″ M1 MacBook Airs back on sale for $200 off MSRP, starting at only $799, for Cyber Monday 2022. Their prices are the lowest available for new MacBooks this Cyber Monday. Stock may... Read more

Jobs Board

*Apple* Electronic Repair Technician - PlanI...
…a highly motivated individual to join our Production Department as an Apple Electronic Repair Technician. The computer repair technician will diagnose, assemble, Read more
Product Manager II - *Apple* - DISH (United...
…you will be doing We seek an ambitious, data-driven thinker to assist the Apple Product Development team as our new Retail Wireless division continues to grow and Read more
Staff Engineer 5G Protocol, *Apple* - DISH...
…metrics. Essential Functions and Responsibilities for a Staff Engineer 5G protocol( Apple ) Knowledge of 5G and 4G/LTE protocols and system architectures Experience Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States ( - Apple Blossom Mall Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States ( - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.