TweetFollow Us on Twitter

Using Windows
Volume Number:1
Issue Number:4
Column Tag:C Workshop

Using Windows

By Robert B. Denny

Layers and Interfaces

One of the most important things to come out of the computer world in the seventies is the concept of layered architecture. Layering provides us with a clean way to deal with the complexities of modern operating system and communications architectures. One of the most visible instances of layering is the ISO Open Systems Architecture which is widely used and quoted in standards for networks.

I consider layering to be a survival skill for software developers. Take time to consider the Macintosh from bottom to top. At the bottom, we have solid-state physics which attempts to explain the behavior of what might be particles or waves. At the top (user’s view) we have dragging, clicking, icons, windows, etc. Both the physics and the user concepts are abstract ideas. How many layers can you conceive of in a Macintosh?

Let’s formalize this a bit. A layer is a structured set of related things that together provide a set of tools or services for implementing other things. An interface is a set of means for accessing the services provided by a layer. Finally a given layer might make use of the services provided by a “lower” layer in implementing it’s own services. It is this latter notion that makes layers have ranking.

How does all of this help us deal with complex systems? By restricting our thinking to the layer we are working on, we avoid cluttering our mind with unnecessary details. This kind of thinking comes naturally, but we can reinforce it by being aware of it’s importance.

Most of the developers I have talked with share the feeling that the Mac is a difficult system to learn. Inside Macintosh is a wealth of information, but it has little overall structure. There is a section called Inside Macintosh: A Road Map which does discuss the overall architecture, but this thread is not carried elsewhere, and one tends to “dive in” to a particular area of interest.

Here is my personal view of the Macintosh operating system as a set of layers. Below these layers are the low-level stuff I seldom deal with and above these layers are the programs I write. The boxes show the sections of the Mac system that I frequently encounter when developing user-oriented applications.

Data-Driven Software

Another key concept needeed for Macintosh programming is that of data or table-driven software. This is another common technique that grew out of the seventies, when system complexity took a quantum jump.

A data-driven routine consists of a combination of code and data, split up so that variations are possible with no changes to the code. This technique is usually employed where there are a variety of related objects that need some sort of service or management that can be done with a common “engine” in code.

This is sort of a gray area; you might say that all routines are sensitive to data, or they wouldn’t be useful. True, but a routine that stores no data of it’s own is special. It is usually called with a reference to a data structure which contains the state and attributes of the particular object that the routine is to work on. The data structure could even contain a reference to one or more “action routines” which are unique to the object in question. Examining the contents of such data structures can often provide great insight into the sublties of the routine or service.

Most of the “managers” in the Macintosh interface use this technique. The data structures are referred to as “records” from the Pascal terminology. In C, they can be implemented as struct’s.

The Window Manager

From the user’s viewpoint, a window is an object on the desktop that provides some sort of user interface. There is a whole set of guidelines describing how windows should look and behave. Window appearance and behavior is the essence of the Macintosh.

From the developer’s viewpoint, a window is a structured set of regions in a port under the control of the Window Manager. The Window Manager provides a layered interface to window services on the Macintosh, using QuickDraw to draw the pictures that create the abstract notion of windows on the screen.

Besides handling the windows themselves, the Window Manager handles shuffling, dragging and re-sizing of overlapping windows, generating events for owning applications to update window contents as required. This powerful and complex layer of the Mac architecture has a surprisingly simple interface.

The Window Manager uses a data structure, called a window record, to keep track of each window. It contains the currrent attributes and state of the corresponding window. The window records are kept on a linked list whose order corresponds to the planar ordering of the window images on the screen, as shown in figure 2.

If you haven’t looked over the section on the Window Manager in Inside Macintosh, now would be a good time to do so. In particular, study the section describing the window record and each of it’s fields. We’ll look at some of the more important fields here, but we can’t cover them all. In C, the window record can be represented as follows:

C STRUCT FOR WINDOW RECORDS

#define boolean char
struct WindowRec
 {
 grafPort port;
 short  windowKind;
 booleanvisible;
 booleanhilited;
 booleangoAwayFlag;
 booleanspareFlag;
 RgnHandlestrucRgn;
 RgnHandlecontRgn;
 RgnHandleupdateRgn;
 Handle windowDefProc;
 Handle dataHandle;
 Handle titleHandle;
 short  titleWidth;
 Handle controlList;
 struct WindowRec *nextWindow;
 PicHandlewindowPic;
 long   refCon;
 };

Note that the first thing in the window record is a GrafPort structure. This is the data structure used by QuickDraw for manipulating “ports” in general. Of course, a window is a port, so it follows that the window’s data would include (nested within) a GrafPort.

Before we dig any deeper into the window record, lets look at how it relates to other important data structures. Pointers and handles are represented alike in the interest of simplicity in Fig. 3.

PORTS, REGIONS AND WINDOWS

Looking at figure 3, observe the linkage of the region structs. The visRgn and clipRgn are hooked to the GrafPort, while the strucRgn, contRgn and updateRgn are hooked to the WindowRecord. The latter three regions are used only in the context of a window. If you are unclear about the role of regions, refer to Chris Derossi’s Pascal Procedures in MacTutor, Vol.1, No.3, February, 1985.

Note also that the ControlRecord for each control that is associated with the window is hooked to a linked list, and has a “back-link” pointing back to the owning window’s WindowRecord. This implies that the Window Manager uses information about the controls, and that the Control Manager uses information about the owning window and it’s port. For example, the Window Manager function drawControls() traces down the linked list of ControlRecords, drawing each control in turn.

The various “boolean” fields in the WindowRecord indicate the current state of the window’s visibility, highlighting (see below) and whether it has a “go-away” box. CAUTION: the Window Manager uses 255 as TRUE and 0 as FALSE. Typically C defines TRUE as 1. You should test these flags for “not FALSE”, rather than explicitly TRUE.

The three RgnHandles point to Rgn structs which describe important parts of the window’s port. We’ll cover these later in the section on anatomy and next month’s column on window dynamics.

The windowDefProc field is a handle that points to a vectored set of routines that give the window it’s look. Associated with this is the dataHandle field, which points to private data used by the DefProc. “DefProc” is short for Definition Procedure, really a set of routines that perform the following:

Window Definition Procedure Tasks

• Draw window frame

• Return region where mouse was clicked

• Calculate structure & content regions

• Draw “grow” image of the window

• Draw a “size box” in the content region

Note that the Window Manager has no idea what the window actually looks like. The appearance is completely governed by the DefProc, which is described by a handle in the WindowRecord. The six standard DefProcs handle windows of the types shown below in figure 5 with the symbolic value for the definition ID you pass to the Window Manager when creating the window.

Note that the documentProc flavor has the outlines for scroll bars. Scrollers are controls, not part of the basic window’s definition. These are the standard window types. You could write a DefProc package for a custom window type. The hooks for this are described in Inside Macintosh in the Window Manager section.

The titleHandle field points to the window’s title string and the titleWidth field contains the width of the title in pixels. ControlList is the listhead for the linked list of ControRecords for the controls associated with this window.

NextWindow is a pointer to the next window on the window list. As we stated earlier, the “next” window is the one behind this window. If this is the back-most window, NextWindow is NULL.

WindowPic is a handle to a QuickDraw picture for the window, or NULL if the application is responsible for updating the window. This implies that the window manager will automatically update a window if it’s contents are a QuickDraw Picture without generating update events.

Finally, there is a “hack” in the definitions used in Inside Macintosh. A WindowPtr is defined as a pointer to a grafPort, rather than a pointer to a WindowRecord. The name for the later is WindowPeek. It seems that the most frequent use of WindowRecord information involves the data contained in the embedded grafPort. Keep this quirk in mind.

Anatomy of a Document Window

The six standard window types are shown in figure 5. Of the six, the documentProc type is the most complex. In this section we’ll look at the window as a set of regions. Viewing the window this way is essential when writing programs which manipulate them, particularly the routines that handle activation and updating of the window. A document window with scroll bars is shown in figure 6.

All windows have a structure region and a content region. The structure region covers the entire window, frame and all. The content region is the area inside the frame. These regions change only when the window is moved or re-sized.

The frame may include go-away and drag regions. The content region may include a grow region.These are not really regions in the formal sense, as defined by QuickDraw. The DefProc is responsible for handling these regions, not QuickDraw. The scroll bars are handled by the Control Manager, not the Window Manager.

The WindowRecord contains a handle to another region, the Update Region. This region describes the portion of the content region that needs updating, redrawing, after some change. We’ll deal with this in next month’s column on window dynamics.

One of the fine points not made clear in Inside Macintosh is the relationship between the “grow image”, the grow region and the scroll bars usually present in a document window. The grow image is the line-tracing of the window that appears when you click in the grow region.

The Control Manager can build scroll bars of any dimension. The convention is that scroll bars are 16 pixels wide. This matches the width of the “scroller” areas that appear in the grow image, and the width and height of the grow icon. These areas are fixed, set by the documentProc DefProc. Here is a fat-bits view of the lower right corner of the document window shown above (see fig. 7). Note that the scroll bar edges overlap the grow icon and the window frame by one pixel. The following fragment of C code computes the boundsRects for the scrollers, given the portRect for the window. Get the portRect from the grafPort that is embedded in the WindowRecord:


 struct rect/* Define a “rect” */
 {
 short  top;
 short  left;
 short  bottom;
 short  right;
 };

struct grafPort *wp; /* Window Pointer */
struct rect *pr; /* -> portRect */
struct rect vs_rect; /* Vert. scroller */ 
struct rect hs_rect; /* Hor. scroller */

pr = &(wp->portRect);

/*
 * Compute bounds rect for vertical scroll
 */
vs_rect.top = pr->top - 1;
vs_rect.left = pr->right - 15;
vs_rect.bottom = pr->bottom - 14;
vs_rect.right - pr->right + 1;
/*
 * Compute bounds rect for horiz. scroll
 */
hs_rect.top = pr->bottom - 15;
hs_rect.left = pr->left - 1;
hs_rect.bottom = pr->bottom + 1;
hs_rect.right = pr->right - 14;

Afterword

Next month we’ll deal with window dynamics, dragging, growing, updating and activating. This is an area of Mac programming that seems complex on the surface. If you have tried your hand at window-oriented programs, you probably had many surprises and mysteries and you may have developed a few OPT’s (old programmer’s tales). One of my most memorable surprises was discovering what happens if you omit the beginUpdate() and endUpdate() calls when handling an update event.

There is an underlying consistency to window dynamics. It’s all there in Inside Macintosh, but in peices. Understanding window dynamics is essential if you are to get beyond trivial programs without unnecessary screen drawing or ugly hacks. See you then.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Senior Product Associate - *Apple* Pay (AME...
…is seeking a Senior Associate of Digital Product Management to support our Apple Pay product team. Labs drives innovation at American Express by originating, Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.