TweetFollow Us on Twitter

Windows in Action
Volume Number:1
Issue Number:5
Column Tag:C WORKSHOP

Windows in Action

By Robert B. Denny

Windows in Action

There is an initial “hill” that every Macintosh developer must climb before doing anything useful. Most applications require use of windows for presentation and control. Unfortunately for the developer, this fundamental requirement makes it necessary to understand a large part of the Mac’s internals. This information is presented piecemeal in Inside Macintosh (IM).

Last month, we covered the “static” aspects of windows, including data struc- tures and the functions of the Window Manager. Much of this information can be gleaned from IM relatively easily.

The dynamic aspects of windows, how- ever, are far more subtle. Most of what we learn about window dynamics comes from our experience implementing window-based applications. Take some time to observe how various Mac applications handle things like activating overlapped windows and dragging or re- sizing of windows. Some applications take an “overkill” approach, erasing the entire window and re-drawing everything. Others behave in a more refined fashion, updating only what’s necessary.

The goal of this month’s column is to provide you with some insights into window dynamics and how to apply that knowledge to avoid over-updating and ghost images.

In particular, we will cover creating, updating, dragging, re-sizing, activating and deactivating of windows. The details of scroll-bars, textEdit and other window “content” items will be covered in next month’s column.

Regions Again

Before we go any further, let’s quickly review the various regions involved in window construction and dynamics.

Fig 1.

Fig. 1 shows the various component regions of a common “edit” window. The terminology used here and in Inside Macintosh is confusing. The go-away, drag and grow regions aren’t really “regions” in the QuickDraw sense. They are areas within the window that are handled specially by the Window Manager. For the purposes of compatibility with IM, however, we will use the same termin- ology.

The structure and content regions are true regions. The structure region encloses the entire window, frame and all. The frame consists of the entire title bar and the border (even the drop-shadow, if any). The content region is that area inside the frame. Note that the scroll bars and size box are located within the content region. These regions change only when the window is moved or re-sized.

The Update Region

There is another region that we will be dealing with extensively, the update region. It’s not a structural part of the window as are the structure and content regions. Instead, it is a dynamic descrip- tion of the area(s) of the window which need updating at any given instant.

The update region, like the structure and content regions, is linked directly to the windowRecord. It is used by the Window Manager to control QuickDraw updates to the screen. We’ll look at this in more detail later.

When windows are shuffled front and back, or moved about the desktop, it can be confusing as to whom is responsible for re-drawing what parts of the window. What will the window manager do for you, and what must your application do itself? Here is a simple rule to remember:

The Window Manager handles the frame; your application must handle the contents.

The contents include any controls (e.g., scroll bars) and the “grow icon” in the grow region, as well as whatever you have placed elsewhere in the window area.

How a Window is Drawn

Let’s look at the process of creating a new window, neglecting the programming needed and concentrating on what actually happens. Keep in mind the rule presented above regarding who handles what.

First, the Window Manager calls the “definition procedure” (DefProc) for the window type and asks it to draw the frame. In doing this, the DefProc manipulates the desktop visRgn and clipRgn to make sure that only the visible portion of the frame will be actually drawn. The DefProc may also draw a go-away box in the title bar area. If you are unclear about DefProcs, refer to last month’s C Workshop.

When the DefProc returns to the Window Manager (with the frame drawn), the Window Manager posts an update event for the application that requested the window to be drawn, then returns control to the application.

It is important to understand just how this update event gets generated. The Window Manager determines which areas of the window’s content region need updating. This set of areas is accumu- lated into the window’s update region, which is now no longer empty. When the Toolbox Event Manager sees a window with a non-empty update region, it queues an update event for that window.

Note that drawing and updating is supported for any window on the desktop. the window being drawn need not be frontmost nor the “active” window. It might not be visible at all.

Sometime later, when the application de-queues the update event just posted, it must draw the window contents. This could be tricky, since all or part of the window could be obscured, and if it’s being re-drawn, some of the image might not need updating.

The proper method of handling update events involves use of two very important Window Manager services, BeginUpdate() and EndUpdate() as follows:

/*
 * Handle update event
 */
do_update(wp)
WindowPtr wp;    /* Update this window */
   {
   BeginUpdate(wp);
   ...            /* Draw everything */
   EndUpdate(wp);
   }

BeginUpdate() calculates the intersec- tion of the window’s visRgn and the update region. The result of this intersection is “the area that is visible and needs updating”. It then replaces the visRgn with this newly calculated region. Finally, it clears the update region so that the update event will not be repeated for the window. Then control is returned to the update event handler.

At this point your application may draw the entire window contents without fear. Actual drawing will be restricted to the (temporary) visRgn, which encloses only what may and should be drawn. Nothing else will be drawn.

After this has been done, call EndUpdate() to restore the original visRgn. This completes the actions needed to service an update event.

So the steps are, restrict actual drawing by hacking the visRgn, draw everything, then restore the real visRgn. This approach to window content maintenance is absolutely basic to successful Mac application development.

Don’t be tempted to try analyzing the hacked visRgn calculated by BeginUpdate() and manually restrict your drawing to that region only. You may think you’re saving time by not drawing invisible areas, but you’re more likely to chew up at least that much time figuring out what you don’t want to do!

Deferred Drawing

Window contents must be updated whenever something happens to cause a portion of the window’s image to become visible after being obscured. The Window Manager will automatically accumulate areas into a window’s update region, and your application may manually add to the update region as well.

In either case, when the update event occurs, part or all of the window may need re-drawing. In order to do this properly, you must have a description of the window’s contents stored somewhere. Think about the implications of this.

Let’s say your application requests input of a set of 10 values that you use to draw a figure. You simply read the values and draw the figure as they are read in. Now let’s say you drag the window partially off-screen, release it, then drag it back on screen. You’ll get an update event for the area that was off-screen. How can you reproduce the figure? The values are gone.

You should have stored the values in an array so that they could be used by the update event handler to re-draw the figure as needed. And why draw any time except after an update event? This is a trivial example of an important rule in Mac programming:

Never “store” anything in the window’s image. Always maintain the data needed to re-draw the window and draw only in response to an update event.

If you change something in the window, change the descriptive data then force an update event by calling InvalRect() or InvalRgn() to put the changed area into the update region. Let the update event handler do the actual drawing. This method of window maintenance is called “deferred drawing” because the changes are made to the descriptive data and the actual drawing is deferred to the time of the update event.

If you follow the above rule, it will usually simplify your program’s logic, making it more reliable and less likely to leave “fossils” on the screen or blow holes in the window image.

Activation and Deactivation

The Macintosh User Interface Guideines specify that only one window on the screen may be “active”. What does active mean? Remember that any window on the screen can (and may) be updated at any time. But the user should be able to tell which window will react to keystrokes and/or mouse clicks. Which window is “hooked up” to the mouse and keyboard?

The active window is the one the user is “working in” at the moment. It is always the frontmost window (alerts and dialogs excepted) and has a distinctive highlighted appearance.

The Window Manager provides services to activate and deactivate windows. Also, the system delivers activation events to the the application so that it can make any changes to the window contents as a result of activation or deactivation. Remember, the Window Manager handles the frame and the application handles the contents.

Fig 2.

Fig. 2 shows a document window in its deactivated state. The title bar (drag region) has no stripes and the go-away box is not present. These items are controlled by the Window Manager. The scroll bars are hidden and the grow icon is gone. These items are controlled by the application’s deactivation event handler.

Fig 3.

Fig. 3 shows an activated document window. The title bar has stripes showing and the go-away box is visible. The Window Manager handles these items. The scroll bars and the grow icon are visible. The application’s activate event handler handles the latter items.

Fig. 4

Activation and deactivation are signalled by the same “activation” event being queued for the window. The application must decode which action to take.

What your application should do in response to update and activation events can become confusing. Servicing update and activation events is a simple matter if you keep the following rule in mind:

Drawing should be done only for update events. Activation and deactivation should cause only changes in appearance of activation dependent items such as controls and menus.

If you follow this rule, it will simplify the logic of your program and prevent unnecessary drawing. Do actual drawing only in response to update events. Use activation events to change the appearance of items.

Fig 5.

Putting it All Together

Let’s take the concepts we have learned and apply them to some common situations. Fig. 4 shows the sequence of events when a window is activated and brought to the front. Look at the steps involved and note the roles of the update and activation events, and the formation of the update region.

There are some fine-points of handling the scroll bars and grow icon that we will discuss next month, when we cover controls and textEdit.

The next illustration shows what happens when a window which is partially off-screen is dragged back on to the screen. It was this case which turned the light on for me personally.

Fig 6.

Interestingly enough, no update event is generated for a window which is dragged from one place to another on the screen. The window manager has a complete image of the window already on the screen, so it simply “bit-blits” (fast image copy) the image from one place to the other.

The surprise comes when you drag the window off-screen, release it, then drag it back on. Now part of the window must be re-constructed as if it was being drawn for the first time. An update event is posted and the application must re-draw the part that was off the screen.

The last “movie”, fig. 6, shows what happens when a window is re-sized. No activation events are posted for this action.

Note particularly the manual invalidation of the scroll bars by calling InvalRect() for each. This is needed because the window manager has no idea that the controls are going to be moved, invalidating the area covered by them.

Final Words

Next month, we’ll finish up the treatment of windows with a description of controls and textEdit. By treating these two subjects together, we’ll learn a lot from their interrelatedness. I’ll also include some C routines for handling update, activate, deactivate, drag and grow actions for windows.

In the near future, The C Workshop will contain a complete application written in C which supports multiple windows of two types, one of which supports fully functional scroll bars and textEdit. The other window type supports a crude “blackboard” which does not remember the blackboard contents. We hope you’ll find this useful as a basis for non-trivial applications.

For now, please be patient. I have not included much C in the last few columns, since the template application. I feel that there is so much to know before one can write even a trivial application that it’s best to hold off until the foundation is complete.

 
AAPL
$111.16
Apple Inc.
+1.75
MSFT
$47.05
Microsoft Corpora
+1.31
GOOG
$510.51
Google Inc.
+5.62

MacTech Search:
Community Search:

Software Updates via MacUpdate

BBEdit 11.0.2 - Powerful text and HTML e...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
ExpanDrive 4.2.1 - Access cloud storage...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more
Adobe After Effects CC 2014 13.2 - Creat...
After Effects CC 2014 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous After Effects customer). After Effects CS6 is still available... Read more
Command-C 1.1.7 - Clipboard sharing tool...
Command-C is a revolutionary app which makes easy to share your clipboard between iOS and OS X using your local WiFi network, even if the app is not currently opened. Copy anything (text, pictures,... Read more
Tidy Up 4.0.2 - Find duplicate files and...
Tidy Up is a complete duplicate finder and disk-tidiness utility. With Tidy Up you can search for duplicate files and packages by the owner application, content, type, creator, extension, time... Read more
Typinator 6.3 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more
GraphicConverter 9.5 - Graphics editor w...
GraphicConverter is an all-purpose image-editing program that can import 200 different graphic-based formats, edit the image, and export it to any of 80 available file formats. The high-end editing... Read more
Toast Titanium 12.0.1 - The ultimate med...
Toast Titanium goes way beyond the very basic burning in the Mac OS and iLife software, and sets the standard for burning CDs, DVDs, and now Blu-ray discs on the Mac. Create superior sounding audio... Read more
QuickBooks 2015 16.0.2.1422 R3 - Financi...
Save 20% on QuickBooks Pro for Mac today through this special discount link QuickBooks Pro 2013 helps you manage your business easily and efficiently. Organize your finances all in one place, track... Read more
Remotix 3.0.6 - Access all your computer...
Remotix is a fast and powerful application to easily access multiple Macs (and PCs) from your own Mac. Features: Complete Apple Screen Sharing support - including Mac OS X login, clipboard... Read more

Latest Forum Discussions

See All

Brothers in Arms 3: Sons of War Review
Brothers in Arms 3: Sons of War Review By Jennifer Allen on December 18th, 2014 Our Rating: :: FUN BUT PUSHYUniversal App - Designed for iPhone and iPad Brothers in Arms 3: Sons of War could be great fun, but its plethora of... | Read more »
The Snow is Falling on the French Countr...
The Snow is Falling on the French Countryside of Carcassonne’s Newest Update Posted by Jessica Fisher on December 18th, 2014 [ permalink ] < | Read more »
Creatures Such As We Review
Creatures Such As We Review By Jennifer Allen on December 18th, 2014 Our Rating: :: INTERESTING DISCUSSIONSUniversal App - Designed for iPhone and iPad Taking a more sedate approach to interactive fiction, Creatures Such As We... | Read more »
Give It Up! (Games)
Give It Up! 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: GIVE IT UP is a rather hard game where you have to assist this cheerful, singing Blob in jumping through 9 different tracks.So far... | Read more »
The Drive : Devil's Run (Games)
The Drive : Devil's Run 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: ON THE ROAD AGAIN! The Drive - Devil’s Run is classic point to point style racing game that pays homage to the classics... | Read more »
Procreate Pocket (Entertainment)
Procreate Pocket 1.01 Device: iOS iPhone Category: Entertainment Price: $2.99, Version: 1.01 (iTunes) Description: Create - anytime, anywhere. Made by the developers of the award-winning Procreate® for iPad®, Procreate Pocket™ allows... | Read more »
IRON FINGER - Mini Games Championship (...
IRON FINGER - Mini Games Championship 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Quick to play, easy to learn yet hard to master.. TAP, SWIPE & TILT your way through mini games that... | Read more »
Pentaction: Medieval (Games)
Pentaction: Medieval 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Pentaction: Medieval is a turn-based strategy board-game about chance and skill on the battlefield. Take control of your... | Read more »
Hipstify Review
Hipstify Review By Jennifer Allen on December 17th, 2014 Our Rating: :: COOL FILTERSUniversal App - Designed for iPhone and iPad Add filters, quotes, and fancy frames to your images, thanks to Hipstify.   | Read more »
Mighty Smighties Gets Evolve Cards and N...
Mighty Smighties Gets Evolve Cards and New Worlds Posted by Jessica Fisher on December 17th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »

Price Scanner via MacPrices.net

KMI MIDI K-Board Great Gift for Amateur &...
The K-Board is a MIDI Nano keyboard for music creation for iPad, Android, And computers; the easiest way to make music with iPads & Android tablets, and Mac, Windows, or Linux computers. Ultra-... Read more
Amazon offers 15-inch 2.2GHz Retina MacBook P...
 Amazon.com has the 15″ 2.2GHz Retina MacBook Pro on sale for $1699 including free shipping. Their price is $300 off MSRP. Stock is limited, so act now if you’re interested. Read more
Holiday sales continue: MacBook Pros for up t...
 B&H Photo has new MacBook Pros on sale for up to $300 off MSRP as part of their Holiday pricing. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1699... Read more
Google Search App For iOS Gets A Major Makeov...
Google has given iOS users an early Christmas present with a substantial update of it’s not-very-often-upgraded Google Search app. Google Search has been my go-to tool for Web searches since it was... Read more
ShopKeep Apple Pay And Chip Card Reader Avail...
ShopKeep, a cloud-based technology provider to more than 10,000 small business owners to manage retail shops and restaurants with iPads, has released its new Apple Pay and chip card reader. This... Read more
Holiday sale! 27-inch 5K iMac for $2299, save...
 B&H Photo has the 27″ 3.5GHz 5K iMac in stock today and on sale for $2299 including free shipping plus NY sales tax only. Their price is $200 off MSRP, and it’s the lowest price available for... Read more
Holiday Sale! 3.7GHz Quad Core Mac Pro availa...
 B&H Photo has the 3.7GHz Quad Core Mac Pro on sale for $2599 including free shipping plus NY sales tax only. Their price is $400 off MSRP, and it’s the lowest price for this model from any... Read more
iPhone 6 Number 3 Canadian Google Search Of 2...
CTVNews.ca reports that Apple’s iPhone 6 was the third highest-trending Google Canada search topic of 2014, exceeded only by Robin Williams largely after his death by suicide in August, and the FIFA... Read more
New iPad mini 3 Counter-Top & Wall Mount...
newMacgadgets has announced new secure all-acrylic displays for the iPad mini 3 (also works fine with the mini 2, last year’s iPad mini With Retina Display, and the original iPad mini). The new iPad... Read more
Holiday sales continue, MacBook Airs for up t...
B&H Photo has 2014 MacBook Airs on sale for up to $120 off MSRP, for a limited time, for the Thanksgiving/Christmas Holiday shopping season. Shipping is free, and B&H charges NY sales tax... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.