TweetFollow Us on Twitter

Window Structures
Volume Number:5
Issue Number:6
Column Tag:abC

Related Info: Window Manager

Window Structures

By Bob Gordon, Minneapolis, MN

Welcome to the second incarnation of the MacTutor intro column. The column is called abC because of its introductory nature (the “abc’s”), and it uses the C language (the “C”). What I propose to do is to continue in the spirit of the previous set of articles, but focus less on C and more on the Mac.

I also will not attempt to present a complete program each time. Since an introduction by its very nature tends to be a bit repetitive, I found the last time that the same code would appear for months at a time. This took up a lot of space in the magazine, and made it difficult to focus on one issue as we were always carrying around a large amount of other code just to make an application work. This means that the articles will tend to be shorter, which will likely make it more possible for me to get them done.

One other point before we start. I found that one of the most useful things in writing for MacTutor is getting mail. Feel free to write; comments are much appreciated; and include your phone number.

Making a Window

One of the first steps in a Mac application is putting a window on the screen, typically in response to a request from the user. This method developed here is done entirely in code (as opposed to using resources). This has some limits, but offers the ability to easily add some features to ease the maintenance of windows.

There are two points: First a window consists of the window stuff and the application specific stuff. From the Mac’s point of view, the window stuff consists of only the frame and does not even include the scroll bars (if any). On the other hand the application probably does not want to be concerned with such things as the scroll bars, zoom boxes, sizing, et cetera.

Second, it is good programming practice to separate the application specific code from the more generic user-interface code. This eases maintenance and debugging and modification. To this end I created a file, shell.c which handles many of the generic properties, helper files (e.g. windowhelp.c) to add the capabilities I wanted, and the file app.c, which actually contains the parts of the application. In the snippets of code that follow, you will notice an occasional call to a function like appxxx(). This is a call in the shell part of the program to the app.c file. It is here, after, for example, preparation has been made for updating a window (appupdate() ), that the application must update the application portion.

windowhelp.h

The windowhelp functions work because the WindowRecord defined in the ToolBox is a fixed length object. What I did is add some additional data structures on the end. This simply makes the object a little longer, but all the toolbox window and QuickDraw functions will work correctly. The advantage of doing this is that I can now keep additional information, which I think should be attached to a window in a safe place where I can always find it, and the application parts of the code need to concern themselves with it.

One might suggest that the WRefCon (a field in the WindowRecord specifically for the application’s own use) field is the proper place for this. This is probably true, but so much of this stuff seemed to either be more part of the window than the application (scroll bars) or likely to be part of any application (knowing whether the contents had changed or not), that it seemed a Good Idea to put it all together in one place. In this way much of the Mac user interface is handled for us each time we start a project. I use the WRefCon field to store the reference to the applications information proper.

Now, I make have no pretenses that this is the optimal way of doing things. In fact, I know there are additions and changes I am going to make, but if we wait to get all that worked out, we’ll never get this written.

A few comments about the fields:

The first four are what I call window margins. I noticed that many applications place various graphic objects around the edges of the window. There are scroll bars to the bottom and right, rulers on the top and tools on the left. Whatever it is, it brings in the edge of the window as far where the application can write. The window margins are sizes, in pixels of the areas reserved by things around the edges. The application can change them (if the user asks to see the rulers, for example).

The next field, cursrt, is the rectangle defined by the window and the margins. I called it cursrt because outside the rectangle the cursor is typically the 11 o’clock arrow, and inside the cursor is whatever the application would like.

The zoomrt is the rectangle to hold the size to zoom to if the user clicks the zoom box. Frankly, I haven’t implemented zooming yet. It may be that we’ll want two rectangles for zooming: one to hold the maximum size and one to hold the small (user set) size.

mouser is a code for the mouse cursor. I made it a char simply because I couldn’t imagine anyone wanting more than 255 cursors and because the built-in cursors are numbered one through four. If you want to add a cursor resource, simply start the numbers at five and everything will work fine. And if you want more cursors or want to use bigger numbers, make it a short.

The changed field simply states whether or not the window contents have changed.

The next field, ckind (contents kind) I used to indicate the kind of window. Currently this is either text or a object drawing. Whether this will stay this way or not I don’t know. Currently I use this in the functions that handle update and activation events to determine what to do.

The last field is a handle to the current TextEdit record. A window may have more than one. This is needed because when a window is activated, the blinking cursor needs to be placed in whichever edit record the user left it in.

As you can see, much of this information falls somewhere between what is strictly application specific and what is part of the window. Much of it, however, the application either need not be concerned with or is needed for almost all applications.

Following the WindowStruct definition are several groups of #defines. The most interesting of these are the WDOC/WGROW/WZOOM. By using these when you define a window (simply add together the ones you want), you can specify whether you want a simple document window to have a grow box or a zoom box. You can also add in the codes for the vertical or horizontal scroll bars.

/* 1 */

/*windowhelp.h */
#include “TextEdit.h”
 
#ifndef WINDOWHELP_H
#define WINDOWHELP_H

/* window add-on structure */

#define WindowStruct struct w_struct
WindowStruct
 {
 WindowRecord  wr; /* the original window record */
 uchar  mtop;    /* margin indents */
 uchar  mleft;
 uchar  mbottom;
 uchar  mright;
 Rect   cursrt;  /* rectangle used for cursor control */
 Rect   zoomrt;  /* rectangle for zoom operation */
 char   mouser;  /* mouse pointer id (cursor shape) */
 char   changed; /*if window contents havebeen changed */
 short  ckind;   /* kind of contents */
 TEHandle curtext; /* handle current te rec for window */
 };
 

#define Woffset  18
#define SBarWidth15

/* these definitions allow easy generation of the four square
 * cornered titled windows. The basic (simplest) window is the
 * WDOC (NoGrowDocProc). To this optionally add WGROW to add a 
 * grow box and/or WZOOM to add a zoom box.
 */
#define WDOC4
#define WGROW    -4
#define WZOOM    8
#define WVBAR    16
#define WHBAR    32

/* specify the content of the window */
#define CDRAW    1
#define CTEXT    2

/* Value in windowKind field of WindowRecord by WindowNew
 * if the window has a grow box. This is used by routines that
 * redraw the window to decide whether to draw the grow box
 * or not 
 */
#define HASGROW  9

#endif

WindowHelp.c

WindowHelp.c consists mainly of two functions, WindowNew() and WindowClose().

WindowNew() opens a window after creating a WindowStruct as shown above (no check for memory yet). Note that it only gets four arguments. The title (which can be a null string in which case the window is named “Untitled”), a percentage (the window is opened as a certain percentage of the monitor size), the windowkind (WDOC/WGROW/WZOOM), and the content kind.

A few other notes: The call to AppPage() is a kludge. It is supposed to return the page size. Currently some numbers are just hard coded in AppPage(). The page size is needed for scrolling. Just put in sizes for an 8.5 by 11 piece of paper (in pixels) or whatever size page you want. The call to AppNew() is where the application does the initialization of its own data for a new window and places a reference to it (typically a handle) in the WRefCon.

WindowClose() closes a window. After checking to see if the window is a desk accessory (and handling that), it calls AppClose() to allow the application to close its own structures. Then is closes the window and frees the memory. It is in here that we would check to see if the window contents had changed (and had not been saved) and ask the user if we were to save the file.

/*2 */


/* windowhelp.c
 * provides some routines to aid in opening and closing 
 * windows
 */
 
#include“abc.h”
#include“Quickdraw.h”
#include“EventMgr.h”
#include“WindowMgr.h”
#include“MenuMgr.h”
#include“windowhelp.h” 
#include“controlhelp.h”
#include“cursorhelp.h”

short w_total = 0; /* counts total number of windows opened*/
short w_count  = 0;
 /* counts number of windows actually open */

WindowNew(title,percentsz,windkind,contkind)
 char *title;
 short  percentsz;
 short  windkind;
 short  contkind;
{
 char   *thetitle;
 Rect   boundsrt;
 WindowRecord  *w;
 WindowStruct  *ws;
 short  width;
 short  depth;
 short  leftedge;
 short  topedge;
 Rect   pagesz;
 short  hasscroll;
 
 hasscroll = windkind & WVBAR + WHBAR; 
 /* mask out scroll bar options */
 windkind &= 8;
 if (title)
 thetitle = title;
 else
 thetitle = “Untitled”;
 SetRect(&boundsrt,screenBits.bounds.left + 4,
 screenBits.bounds.top + 24,
 screenBits.bounds.right - 4,
 screenBits.bounds.bottom - 4);
 width = boundsrt.right - boundsrt.left;
 depth = boundsrt.bottom - boundsrt.top;
 AdjustRect(&boundsrt,
 topedge = 30 + Woffset * w_total,
 leftedge = 30 + Woffset * w_total,
 ((depth * percentsz) / 100) - topedge,
 ((width * percentsz) / 100) - leftedge);
 ws = (WindowStruct *)NewPtr(sizeof (WindowStruct));
 w = (WindowRecord *)NewWindow(ws,&boundsrt,CtoPstr(thetitle),True,
 windkind,(WindowPtr)-1,True,0);
 ws = (WindowStruct *)w;
 switch (windkind)
 {
 case documentProc : 
 case zoomDocProc :
 w->windowKind = HASGROW;
 break;
 };
 if (w->windowKind == HASGROW)  /* set window margins */
 {
 ws->mright = ws->mbottom = SBarWidth;
 AppPage(&pagesz);
 if (hasscroll == WHBAR)
 ScrollNew(w,0,0,pagesz.right,HORZ);
 if (hasscroll == WVBAR)
 ScrollNew(w,0,0,pagesz.bottom,VERT);
 DrawControls(w);
 DrawGrowIcon(w);
 }
 else
 ws->mright = ws->mbottom = 0;
 ws->mtop = ws->mleft = 0;
 ws->changed = FALSE;
 ws->ckind = contkind;
 ws->curtext = NIL;
 SetCursorRect(w); /* set cursor rect for cursor control */
 AppNew(w); /* function to open application structure */
 w_count++;
 w_total++;
 PtoCstr(thetitle);
}

/* WindowClose()
 * Closes the window passed to it. Assumes window was opened 
 * with WindowNew(). If window is a desk accessory, it will 
 *  be closed correctly. If it is an application window, prior 
 *  to the window close there is a call to AppClose() (which 
 * the application must supply) to allow any application 
 * specific closing.
 */
WindowClose(w)
 WindowRecord  *w;
{
 WindowStruct  *ws;
 short  refnum;
 
 if (ws = (WindowStruct *)w)
 if ((refnum = w->windowKind) < 0)
 CloseDeskAcc(refnum);
 else 
 {
 AppClose(w);    /* close app storage, must do before */
   CloseWindow(w); /*    CloseWindow */
   DisposPtr(w);
   w_count--;    /* decrement the window count */
   if (w_count == 0) 
 /* if the number of windows on screen goes to */
   w_total = 0;  
 /*  zero, set total to zero so next time we */
   }    /* open a window it will start at the original */
}/*   window position */

/* AdjustRect
 * adjusts coordinates of a rectangle by four separate 
 * amounts. adjustment is in (towards center) if amounts are 
 * positive and out if amounts are negative);
 */
AdjustRect(rec,t,l,b,r)
 Rect *rec;
 short  t,l,b,r; /* values to adjust rectangle by */
{
 rec->top +=t;
 rec->left += l;
 rec->bottom -= b;
 rec->right -= r;
}

/* RtGlobalToLocal
 * Adjusts a rectangle to local coordinates
 */
RtGlobalToLocal(rt)
 Rect *rt;
{
 Point  *pt;
 
 pt = (Point *)rt;
 GlobalToLocal(pt);
 pt++;
 GlobalToLocal(pt);
}

The last little piece of code illustrates how these functions are called from the shell program.dofile() is part of the code that responds to menus.

/* 3 */

dofile(item)
 short  item;
{
 WindowRecord  *w;
 
 switch(item)
 {
 case iNew: WindowNew(“”,40,WDOC+WGROW+WVBAR,CTEXT);
   break;
 case iClose: WindowClose(FrontWindow());
   break;
 case iQuit : while (w = (WindowRecord *)FrontWindow() )
 {
 WindowClose(w);
 }
   ExitToShell();
   break;
 }
}

I hope this gives you some ideas on how to handle windows. Since it can open as many windows as you want, there should be some check for memory limits. I also hope this is suitably introductory. Again, if you have any questions or comments, please write.

 

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

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
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.