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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.