REALbasic University Resources:

RBU: Glossary Defines common REALbasic programming terms
  Archives Previously published columns
Translations: Dutch Courtesy of Floris van Sandwijk
  Japanese Courtesy of Kazuo Ishizuka
  Chinese Courtesy of Dong Li
  RBU Translation Guide Information on Translating RBU into other languages
Books: Matt's Book (2nd Edition!) Ideal for experienced programmers
  Erick's Book Best for beginning programmers
Websites: Mother Ship The publisher of REALbasic
  RB Webring Links to hundreds of REALbasic websites
  RESExcellence Another REALbasic programming column
  REALbasic Developer Magazine The premiere source for REALbasic instruction.

REALbasic University is Sponsored by

Make your Mac do what YOU want it to. Create games, utilities, cool Mac OS X tricks. Download REALbasic now and create your own software.


Print This Article

REALbasic University: Column 078

OOP University: Part Two

In our last lesson we learned about "modal" programming. Today we learn about it's opposite, event-driven programming.

Event-Driven Programming

Sometimes event-driven programming is known as user-driven programming. That makes sense, since most events (but not all) are caused by users. The user moves the mouse, clicks the mouse button, inserts a CD, unplugs a cable, etc. The Macintosh, in particular, was known as the "user's computer" when introduced. That's because the user was always in charge. The infamous "modes" that bogged down users of other operating systems were (in general) elminated on the Macintosh.

Technically, the Macintosh (especially the early Macs) didn't eliminate modes, but simply expanded them to include a lot more possibilities.

In Detail

This evolution of eliminating modes continues to this day with Mac OS X. For instance, Mac OS X introduced Sheets -- dialogs attached to document windows -- allowing the user to leave one document with a "Save?" Sheet while switching to another document (or program) and continuing to work. In the old Mac OS, one can't do anything until the dialog is dismissed: a mode.

For example, remember the Opening Menu Mode of our DOS word processor from the last lesson? On the Mac, the user could double-click on a word processing file within the Finder to directly open that document. That methodology doesn't exactly fit into our Opening Menu Mode scenario, does it?

On the Mac the user can launch the app directly, print or open a document from the desktop, drop a file (or files) on the program's icon, or even select several file icons and open them all simultaneously!

Suddenly our little Opening Menu Mode is looking pathetically limited. Our code for that routine is suddenly bigger as well: we have to watch for all sorts of possibilities. Is there one file, or more than one? Is the user opening the files or printing them?

The problem gets worse when we get into our Editing Mode. In DOS, that mode just had to handle typing (keyboard input) and watch for Control key commands. But look at just a few possibilities of what could happen within a Mac program:

Mac "Editing Mode" Events:
  - Mouse Move
    - Cursor needs to change over text versus menu/window widgets, etc.
    - Cursor might need to be different if modifier (i.e. Option) key is pressed
  - Mousedown
    - Click on window widget (title bar, close box, grow box, etc.)?
    - Click on different window?
    - Click on menubar?
    - Click on desktop?
    - Click on window of different application?
    - Click on text editing area?
      - Click on selected text?
        - Is this the start of a text drag?
      - Is this a multi-click and I need to select the current word or paragraph?
      - Is Shift key down to extend text selection?
    - Is the click on some other widget/control (i.e. radio button,
      checkbox, listbox, pushButton, editField, etc.)?
  - Command key down
    - Do keys typed match menubar command?
  - Control key down
    - Do I need to display a contextual menu? And if so, which one?
  - Key pressed
    - Handle typing (deleting if there's a text selection)
    - Handle arrow key navigation
    - Handle Shift key text selection extension

Whew! As you can see, the Mac's user-driven environment is a lot more complicated to handle than the simple linear programming method. And the above is just a partial list of standard Mac behavior: if you wanted to add your own custom features (i.e. a glossary feature that expands abbreviations) that would add even more conditions you need to monitor.

However, while there's the potential for a lot more to happen, most of the above behavior is standard. If the user clicks on a pushButton in Program A, for instance, the process of that button being depressed is the same thing as when a pushButton is pressed in Program B, C, or D. What actually happens after the button is pushed varies from program to program, of course. But the behavior of the button itself -- what it looks like and how it visually depresses to give feedback to the user -- is the same for all programs.

Now if every programmer had to write the same button-pressing code for every program they wrote, life would be pretty meaningless. Eighty percent of every program would be rewriting stuff you'd already written dozens of times before!

Even worse, a few oddballs wouldn't follow the published standard (either out of laziness, craziness, or pure incompetence) and the buttons for their programs would look different. Say Apple defined that pushButtons have round corners. Well, some might round the corners too much, and others might use square corners. Some might even create circular buttons! The results of this could be confusing to the users who are no longer sure what are pushButtons.

What I'm describing is pretty much the situation in the early 1980's. MS-DOS gave programmers few tools so every programmer had to create their own routines for handling standard interface stuff with users. Of course the "interface" back then mostly consisted of Control commands and function keys. But pick up ten word processors and they each used their own unique set of commands. Learning how to save a document in WordPerfect did not help you know how to save a document in XYWrite. (Compare this to today: while Mac word processors might have different features, they all print and save documents the same way.)

Apple saw that programmers were spinning their wheels and every program had a different look and feel. With the Macintosh (technically, this started with Xerox PARC and the Apple Lisa), Apple wanted a graphical operating system. In such an operating system, the visual look and feel of the environment was critical. It had to be consistent or users would be confused. It also had to be easy for programmers to implement or else none of them would bother.

Creating graphic elements, such as a pushButton, was far more involved for the programmer. The programmer had to draw the basic shape, add the text, and handle complicated mouse-clicking-and-pushing-the-button-down visuals. Then the button had to pop back up!

Thinking like a traditional programmer, used to working with modes, how would one write such a thing?

Well, perhaps something like this. A user has clicked the mouse button. We know that. So we'd have a routine that handles the mouseClicked stuff. Something like this:

procedure mouse_clicked;

var k: char;

begin {mouse_clicked}

  { Are we within button? }
  if mouseX >= button_left and mouseX <= button_right then
    if mouseY >= button_top and mouseY <= button_bot then
       { Yes, the user clicked on the pushButton! }
       do_button_animate;
    end if;
  end if;

  { handle other potential mouse clicks here }

end; {mouse_clicked}

Of course this just handles things for a single pushButton! In real life, most programs would have many buttons -- this would have to be rewritten as a loop and check the mouse coordinates with every button until we either found one that was clicked or realized that the user had clicked someplace else.

What a complicated mess. And we haven't even done the drawing (animation) portion. Wouldn't it be nice if somehow all this stuff could be handled for us in a standard, uniform manner?

Well, that's what Apple did. The Macintosh came with all sorts of pre-written routines for handling stuff like this. That's what the operating system was about: several thousand OS calls that did things like draw windows, draw pushButtons, etc. To program on the Mac you simply had to learn the names and features of all these pre-built routines and call them from within your program.

In Detail

No wonder the original Mac came with a 64K ROM chip loaded with stuff! Back in those days of 400K floppy disks there wasn't room to store that stuff on the disk: remember, a single disk held the bootable Mac OS, an application or two (MacWrite and MacPaint), and still had a little bit of room left for the user to save documents!

MS-DOS, on the PC side, barely took up any space at all. It also barely did anything.

Let's take a moment to look at an analogy of what we're talking about. I know this may seem basic, but it's important you get a clear picture of this history so you'll understand where we are today.

In the early days of computing, there was scarcely any operating system at all. If we use the analogy of building a building as compared to building a program, back then you had to carve your own wooden nails and use rocks as hammers. Nothing was pre-built.

By the early 1980's, basics like nails and hammers were available, but you still had to cut your own lumber and pour cement.

When Apple introduced the Macintosh (or go back to the Lisa if you want), suddenly builders were presented with a smorgasbord of options: there were pre-cut boards of every length and style imaginable, nails, nail guns, hammers, and the foundation of the building was already built!

In contrast, programming today is like assembling a pre-manufactured house: you snap the pieces together like Legos, and the walls not only already include electrical wiring and outlets, they're already painted! Need a lamp or ceiling fan? Just pop one in place. All the parts and accessories are available to you in the REALbasic controls palette! Your only work is to design the house and implement any custom functionality.

But so far we've just been talking about pre-written routines that do stuff. Are those different from objects?

Next Week

We discover objects.

REALbasic Developer News

You have been hearing about the new REALbasic Developer magazine since it began publishing last summer, but until now the only way you could read it was to subscribe.

Well, I have some exciting news: REALbasic Developer now has a trial version available for free downloading!

This trial version is a PDF of the premiere issue, and includes almost all of the content. At least a portion of every article is included so you can at least get a taste of it, with the balance of content blocked out. Many articles are included in full. The sample issue should give you a clear idea of the quality of the publication, however, so I'd encourage you to check it out.

You can grab the PDF Sampler here.

Remember, if you subscribe in December your subscription will begin with the current issue (1.3, Dec/Jan 2002)!

Letters

No letters this week.


About the Column
REALbasic University is a weekly instructional column on programming with REALbasic and is brought to you by REALbasic Developer, the magazine for REALbasic programmers.

Each week we answer select reader questions, and we're always open to ideas for future columns. Send your questions to . (Keep your questions simple and specific. General queries like "How do I write my own web browser?" will be neglected.) Your question won't be answered immediately, but will be answered in a future column. (If you don't want your correspondence published, just be sure to indicate that when you write. Otherwise it's fair game.)

About the Author
is an author, philosopher, graphic designer, photographer, film director, soccer fanatic, and programmer (among other things). He writes for MacOpinion, runs his own software company, Stone Table Software, which sells the revolutionary Z-Write word processor, and is Publisher and Editor of REALbasic Developer. He lives in Northern California with his cats, Mischief and Mayhem, and is rapidly running out of free time.

See the REALbasic University Archives


REALbasic University contents ©2001-2004 by Marc Zeedar and REALbasic Developer. All Rights Reserved.

Email This Article - Comment On This Article

.

Reader Specials

Server Racks Online:
Apple Xserve CompatibleServer Racks and Universal Network Racks
42U KVM Switch Solutions:
High-End Mac and Multi-Platform KVM Matrix switching solutions!
Digital Camera Online:
Great prices on Digital Cameras and accessories!
KVM Switches Online:
Great prices on Mac KVM Switches from the leading manufacturers!
LCD Monitors Online:
Great prices on LCD Monitors from the leading manufacturers!
LCD Projectors Online:
Shop online for LCD Projectors from the leading manufacturers!
USB 2.0 Online:
Great prices on USB 2.0 products from the leading manufacturers

Serious Business Software:
Accounting, Sales, Inventory, CRM, Shipping, Payroll & more!

KVM Switch solutions for MACs:
DAXTEN is a KVM switch, KVM extender and monitor splitter specialist for PC, SUN and MAC applications from name brand manufacturers - offices worldwide.

The "Think Different Store: The iPod Accessories Store - iPod cases, iPod mini, iPod photo, speakers, itrip, inMotion, Soundstage and all other iPod accessories

Earn Cash with the ThinkDifferent Store Affiliates Program

Need A Web Site?
Applelinks Web Hosting Starting at 19.95 a Month

iTunes_RGB_9mm

.

iTunes_RGB_9mm

Cool Mac Gear


iPod 1G-2G
iPod 3G
iPod 4G
iPod Mini
PowerBook-iBook
Keyboard Skins
Garageband