TweetFollow Us on Twitter

Winter 92 - SIMPLE TEXT WINDOWS VIA THE TERMINAL MANAGER

SIMPLE TEXT WINDOWS VIA THE TERMINAL MANAGER

CRAIG HOTCHKISS

[IMAGE Hotchkiss_rev1.GIF]

A major feature of System 7 is the fact that the Macintosh Communications Toolbox is built in and available for all to use. This article presents code that uses the Communications Toolbox Terminal Manager to implement a simple text window that can be dropped into any application. The window is useful for displaying debugging or status information such as variable values or memory usage during application development.


Many times, when writing code, I've wished I had some sort of text repository, a place to write some quick text. I tried to use TextEdit for this at first, but its structures grow as you add text, so my memory accounting became confused. Sprinkling DebugStr calls throughout the code told me what I needed to know most of the time, but they were interruptive to both the user interface and timing- sensitive functions. Finally, I turned to the Terminal Manager because in addition to a terminal tool it contains the nuts and bolts necessary to display a text window and uses a fixed amount of memory.

TermWindow, included on theDeveloper CD Series disc, consists of a few simple routines that use the Terminal Manager and a terminal tool to display text in a Macintosh window. The package can be used in any application for purposes such as displaying variable values, heap checks, memory usage, and routine paths. I've even used some features of the terminal tool to grab attention, like having text blink when I encounter an OSErr or when memory begins to get tight.

Figure 1 shows a sample TermWindow terminal emulation window. I used the Developer Technical Support (DTS) Sample application (included with MPW) and the Apple VT102 tool to produce the display. The double-high/double-wide text shown in the figure is a feature of the VT102 emulator. I displayed it by writing the escape sequences shown on the next page to the window. (Two lines are needed for double-high text, one to display the top half of the line, and one for the bottom half.)

<ESC>#3HELP! I'm trapped in here!
<ESC>#4HELP! I'm trapped in here!

[IMAGE Hotchkiss_rev2.GIF]

Figure 1A TermWindow Window

THE HEADER FILE

The file TermWindow.h defines a basic TermWindowRec structure that TermWindow uses internally for housekeeping and for storage of other structures, including the handles for the terminal and control records.
struct TermWindowRec
{
    WindowRecord    fWindowRec;     // so it can be a WindowPtr
    short           fWindowType;    // for application use
    TermHandle      fTermHandle;    // CTB terminal handle
    TermEnvironRec  fTermEnvirons;  // environment info
    ControlHandle   fVertScroll;    // vertical scroller
    ControlHandle   fHorizScroll;   // horizontal scroller
    Point           fMinWindowSize; // min. width/height of window
};
typedef struct TermWindowRec TermWindowRec;
typedef TermWindowRec *TermWindowPtr;

Six prototype routines, used to put TermWindow to work in an application, are also defined in the header file TermWindow.h.

pascal  OSErr   InitTermMgr(void);
pascal  OSErr   NewTermWindow(TermWindowPtr *termPtr,
                                const Rect *boundsRect, 
                                ConstStr255Param title, 
                                Boolean visible,
                                short theProc, 
                                WindowPtr behind,
                                Boolean goAwayFlag,
                                Str31 toolName);
pascal  OSErr   DisposeTermWindow(TermWindowPtr termPtr);
pascal  Boolean IsTermWindowEvent(TermWindowPtr termPtr, 
                                const EventRecord *theEventPtr);
pascal  void    HandleTermWindowEvent(TermWindowPtr termPtr, 
                                const EventRecord *theEventPtr);
pascal  OSErr   WriteToTermWindow(TermWindowPtr termPtr,
                                Ptr theData, Size *lengthOfData);

HOW TO USE TERMWINDOW

The six TermWindow routines are easy to use. After normal Macintosh manager initialization, you'll initialize the Terminal Manager with a call to InitTermMgr and then call NewTermWindow. The NewTermWindow function allocates the TermWindowPtr, terminal handle, and control handles. It also creates a Macintosh window complete with scroll bars and then attaches the terminal emulation region to the window with a call to TMNew. (See the next section for more on initialization.)

There are two functions to handle events, IsTermWindowEvent and HandleTermWindowEvent. These should be placed in your application event loop. IsTermWindowEvent determines whether the incoming event is for the emulation window by looking at the EventRecord structure, and it also provides time to the terminal emulator by calling TMIdle. HandleTermWindowEvent is a dispatcher that routes the event to routines that in turn call the Terminal Manager to process the event. These routines are discussed in more detail in the section "Handling Events."

The WriteToTermWindow routine, discussed later in this article under "Writing Text," uses the Terminal Manager to display your data in the terminal emulation window. And finally, DisposeTermWindow performs window and structure cleanup.

INITIALIZATION

The InitTermMgr routine prepares to initialize the Terminal Manager by checking the status of three Gestalt selectors: gestaltCTBVersion, gestaltCRMAttr, and gestaltTermMgrAttr. (We don't have to check for Gestalt, since MPW 3.2 contains the code to make Gestalt work.) The gestaltCTBVersion selector tells us which version of the Communications Toolbox is available, thereby letting us know that it exists. The gestaltCRMAttr and gestaltTermMgrAttr selectors tell us, respectively, whether the Communications Resource Manager (which must be initialized for tool resource handling) and Terminal Manager are available for use. InitTermMgr then calls the Communications Toolbox initialization routines if each Gestalt call returns a value of true. It all looks like this:
pascal OSErr InitTermMgr(void)
{
    OSErr   result = noErr;
    Boolean hasCTB, hasCRM, hasTM;
    long    gestaltResult;
    
    hasCTB = (Gestalt(gestaltCTBVersion, &gestaltResult) ? 
                            false : gestaltResult > 0);
    hasCRM = (Gestalt(gestaltCRMAttr, &gestaltResult) ? 
                            false : gestaltResult != 0);
    hasTM = (Gestalt(gestaltTermMgrAttr, &gestaltResult) ? 
                            false : gestaltResult != 0);
    if ((hasCTB) && (hasCRM) && (hasTM))
        if (noErr == (result = InitCRM()))
            if (noErr == (result = InitCTBUtilities()))
                if (noErr == (result = InitTM()))
    
    return (result);
} /*InitTermMgr*/

You may wonder whether the Communications Toolbox requires that the Macintosh Toolbox managers be started up at initialization time. The Communications Toolbox managers are loaded in the system heap, so you may have other reasons for starting them up in your initialization routine, but TermWindow's only requirement is that InitTermMgr be called at some point beforeNewTermWindow. Because the NewTermWindow routine has the potential to allocate nonrelocatable memory, calling InitTermMgr and NewTermWindow at initialization removes the possibility of heap fragmentation.

NewTermWindow begins by validating each parameter that was passed and assigns default values if necessary (see Table 1 below; refer to "The Header File" earlier in this article for the NewTermWindow declaration). You might notice that a good deal of the parameter list to NewTermWindow is very similar to that for the NewWindow function in the Macintosh Toolbox. The NewTermWindow parameter list is designed to provide as much window control as possible when calling NewWindow, while also adding the functionality for the terminal emulation region. Calls to NewControl attach scroll bars to the window being created.

Table 1 NewTermWindow Defaults

Parameter NameDefault Value
termPtrPointer allocated for TermWindow storage
boundsRectFrontWindow window size
title"\pStatus"
visibleTrue
theProcZoomDocProc
behindFrontWindow
goAwayFlagFalse
toolNameTMChoose user setup dialog box

Once the Macintosh window is ready, NewTermWindow attaches the terminal emulation region to the window with a call to TMNew. Parameters to the TMNew routine tell the terminal tool, via the Terminal Manager, how to set up the emulation. (Terminal tools, not the Terminal Manager, implement the emulation.) The basic TMNew prototype is as follows:

pascal TermHandle TMNew(const Rect *termRect,
            const Rect *viewRect,
            TMFlags flags, short procID, WindowPtr owner,
            TerminalSendProcPtr sendProc, 
            TerminalCacheProcPtr cacheProc,
            TerminalBreakProcPtr breakProc, 
            TerminalClikLoopProcPtr clikLoop, 
            TerminalEnvironsProcPtr environsProc, 
            long refCon, long userData);

In TermWindow's case, NewTermWindow sets termRect and viewRect to the portRect of the window's grafPort minus the scroll bar area and sets the flags parameter to 0L. (This enables the terminal tool to put up custom menus or provide error alerts to the user.) The procID parameter is a terminal tool reference number (obtained with TMGetProcID) that tells the Terminal Manager which tool to use. The owner parameter is set to the WindowPtr of our Macintosh window. The procedure pointers, refCon, and userData are all set to nil or 0L.

termPtr->fTermHandle = TMNew(&termRect, &termRect, 0L, procID,
                            (WindowPtr)(*termPtr), nil, nil, nil, 
                            nil, nil, 0L, 0L);

HANDLING EVENTS

Your application's main event loop should use the two event-handling routines, IsTermWindowEvent and HandleTermWindowEvent, to process events for the emulation window and to determine whether the event has already been handled. I use the following fragment just after calling WaitNextEvent; it sets the gotEvent flag to false when TermWindow has processed the event, so that I don't try to handle the event twice.
if (IsTermWindowEvent(&gTheEvent, gTermWindowPtr)) {
    HandleTermWindowEvent(&gTheEvent, gTermWindowPtr);
    gotEvent = false;
}
IsTermWindowEvent uses FindWindow or the message field of the event record to determine whether the event is for the terminal window. (SeeInside Macintosh Volume I, page 250, for details.) IsTermWindowEvent is also a convenient place to give the terminal tool idle time; it calls TMIdle to give the tool a chance to draw text or blink the cursor. (Some terminal tools also have the ability to display blinking text; that would be done here also.)

The HandleTermWindowEvent routine is fairly straightforward, especially if you've written window- and scroll-handling code before. As is true when handling normal windows, the what field of the event record defines the work to be done. Terminal Manager routines exist for most of this work, so handling events is primarily a matter of calling the right routine at the appropriate time. For example, window activation and deactivation are communicated to the tool with a call to TMActivate.

TMActivate(termPtr->fTermHandle, 
            (0 != (theEventPtr->modifiers & activeFlag)));

Figure 2 illustrates how a message like TMActivate is routed to accomplish its goal. The Terminal Manager receives the TMActivate call and routes the tmActivateMsg message to the terminal tool. The terminal tool then takes the opportunity to call Macintosh Toolbox routines such as InsertMenu or RemoveMenu (if the tool uses a custom menu, as the VT102 tool does) to keep the screen up to date.

Update events are handled by a call to TMUpdate sandwiched between BeginUpdate and EndUpdate. You'll just need to pass TMUpdate the update region freshly calculated by BeginUpdate. Of course, if you check for an empty region first, you won't have to call TMUpdate at all.

BeginUpdate((WindowPtr)termPtr);
    if (nil != ((WindowPtr)termPtr)->visRgn)
        TMUpdate(termPtr->fTermHandle, ((WindowPtr)termPtr)->visRgn);
EndUpdate((WindowPtr)termPtr);

[IMAGE Hotchkiss_rev3.GIF]

Figure 2 Calling TMActivate

Mouse-click handling is also fairly traditional. FindWindow is used to determine where in the window the click took place, and Terminal Manager routines are called to let the terminal tool know what to do. When a zoom or grow event causes the size of the emulation rectangle to change, the window's portRect gets passed to TMResize. If FindWindow returns inContent, FindControl is used to determine the control in which the click occurred, so that TermWindow will know whether to scroll horizontally or vertically. The partCode returned from FindControl tells how much to scroll by indicating the part of the control where the click took place. If FindControl returns nil for the ControlHandle parameter, the click is in the emulation region and TMClick is called.

WRITING TEXT

Writing data is easy via the WriteToTermWindow routine. Here's an example of a WriteToTermWindow call with tempString declared as a char array:
sprintf(tempString, "Hello, world");
dataLength = strlen(tempString);
osResult = WriteToTermWindow(termPtr, tempString, &dataLength);

In a debugging situation, you might want to do something like the following to keep track of heap size:

gAppHeapRef -= FreeMem();
if (gAppHeapRef) {
    sprintf(tempString, "\t\t#M# App. heap grew by %ld bytes",
                    gAppHeapRef);
    dataLength = strlen(tempString);
    osResult = WriteToTermWindow(termPtr, tempString, &dataLength);
}

WriteToTermWindow hands the data off to the terminal tool, via a call to TMStream. You might be tempted here to think that the data should appear in the window immediately, but it doesn't--it's simply put in the terminal tool buffer. The terminal tool waits for a TMUpdate or TMIdle before actually writing to the window. Another point to remember when working with terminal tools is that display fonts are controlled by the terminal tool; in fact, many use specific terminal fonts.

NOW IT'S YOUR TURN . . .

That's really all there is to using this simple text window. Now that you have some base code to work from, you might want to add the communication abilities needed to talk to another computer by using Connection Manager calls like CMRead or CMWrite and telling the terminal tool when to use them with procedure pointer parameters to TMNew. How about extending TermWindow to write all data displayed to a file? Or if you're really up to a challenge, try adding a scroll-back cache to store data that gets scrolled out of the emulator. Just scrolling the data around is not too difficult, but brush up on your region handling when you try to work with selections.

I hope you find the TermWindow package useful. Put it to work, add some features, and pass it on. Everything should evolve over time.

CRAIG HOTCHKISS works on the Connectivity team in Apple's system software group. When he's not pondering new ways for you to discover the world via your Macintosh, you might catch him practicing maneuvers with his stunt kite, playing chess, or "on his way" to a volleyball game. Before coming to Apple, Craig spent several years (in the great state of theworld champion Twins) at the telephone company frustrated with DOS in preparation for database work on PDP and VAX machines.*For more details on using the Macintosh Communications Toolbox, see Inside the Macintosh Communications Toolbox,   by Apple Computer, Inc. (Addison-Wesley, 1991).*

THANKS TO OUR TECHNICAL REVIEWERSJames Beninghaus, Mary Chan, Byron Han *

 
AAPL
$116.47
Apple Inc.
+0.16
MSFT
$47.98
Microsoft Corpora
-0.72
GOOG
$537.50
Google Inc.
+2.67

MacTech Search:
Community Search:

Software Updates via MacUpdate

Cobook 3.0.7 - Intelligent address book....
Cobook Contacts is an intuitive, engaging address book. Solve the problem of contact management with Cobook Contacts and its simple interface and powerful syncing and integration possibilities.... Read more
StatsBar 1.9 - Monitor system processes...
StatsBar gives you a comprehensive and detailed analysis of the following areas of your Mac: CPU usage Memory usage Disk usage Network and bandwidth usage Battery power and health (MacBooks only)... Read more
Cyberduck 4.6 - FTP and SFTP browser. (F...
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Evernote 6.0.1 - Create searchable notes...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more
calibre 2.11 - Complete e-library manage...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital... Read more
Herald 5.0.1 - Notification plugin for M...
Note: Versions 2.1.3 (for OS X 10.7), 3.0.6 (for OS X 10.8), and 4.0.8 (for OS X 10.9) are no longer supported by the developer. Herald is a notification plugin for Mail.app, Apple's Mac OS X email... Read more
Firetask 3.7 - Innovative task managemen...
Firetask uniquely combines the advantages of classical priority-and-due-date-based task management with GTD. Stay focused and on top of your commitments - Firetask's "Today" view shows all relevant... Read more
TechTool Pro 7.0.6 - Hard drive and syst...
TechTool Pro is now 7, and this is the most advanced version of the acclaimed Macintosh troubleshooting utility created in its 20-year history. Micromat has redeveloped TechTool Pro 7 to be fully 64... Read more
PhotoDesk 3.0.1 - Instagram client for p...
PhotoDesk lets you view, like, comment, and download Instagram pictures/videos! (NO Uploads! / Image Posting! Instagram forbids that! AND you *need* an *existing* Instagram account). But you can do... Read more

Latest Forum Discussions

See All

Ubisoft Gives Everyone Two New Ways to E...
Ubisoft Gives Everyone Two New Ways to Earn In-Game Stuff for Far Cry 4 Posted by Jessica Fisher on November 21st, 2014 [ permalink ] | Read more »
Golfinity – Tips, Tricks, Strategies, an...
Dig this: Would you like to know what we thought of being an infinite golfer? Check out our Golfinity review! Golfinity offers unlimited ways to test your skills at golf. Here are a few ways to make sure your score doesn’t get too high and your... | Read more »
Dark Hearts, The Sequel to Haunting Meli...
Dark Hearts, The Sequel to Haunting Melissa, is Available Now Posted by Jessica Fisher on November 21st, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Meowza! Toyze Brings Talking Tom to Life...
Meowza! | Read more »
Square Enix Announces New Tactical RPG f...
Square Enix Announces New Tactical RPG for Mobile, Heavenstrike Rivals. Posted by Jessica Fisher on November 21st, 2014 [ permalink ] With their epic stories and gorgeous graphics, | Read more »
Quest for Revenge (Games)
Quest for Revenge 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: The great Kingdom of the west has fallen. The gods ignore the prayers of the desperate. A dark warlord has extinguished... | Read more »
Threadz is a New Writing Adventure for Y...
Threadz is a New Writing Adventure for You and Your Friends Posted by Jessica Fisher on November 21st, 2014 [ permalink ] In the tradition of round-robin storytelling, | Read more »
SteelSeries Stratus XL Hardware Review
Made by: SteelSeries Price: $59.99 Hardware/iOS Integration Rating: 4 out of 5 stars Usability Rating: 4.5 out of 5 stars Reuse Value Rating: 4.25 out of 5 stars Build Quality Rating: 4.5 out of 5 stars Overall Rating: 4.31 out of 5 stars | Read more »
ACDSee (Photography)
ACDSee 1.0.0 Device: iOS iPhone Category: Photography Price: $1.99, Version: 1.0.0 (iTunes) Description: Capture, perfect, and share your photos with ACDSee. The ACDSee iPhone app combines an innovative camera, a powerful photo... | Read more »
ProTube for YouTube (Entertainment)
ProTube for YouTube 2.0.2 Device: iOS Universal Category: Entertainment Price: $1.99, Version: 2.0.2 (iTunes) Description: ProTube is the ultimate, fully featured YouTube app. With it's highly polished design, ProTube offers ad-free... | Read more »

Price Scanner via MacPrices.net

Save up to $400 with Apple refurbished 2014 1...
The Apple Store has restocked Apple Certified Refurbished 2014 15″ Retina MacBook Pros for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and shipping... Read more
New 13-inch 1.4GHz MacBook Air on sale for $8...
 Adorama has the 2014 13″ 1.4GHz/128GB MacBook Air on sale for $899.99 including free shipping plus NY & NJ tax only. Their price is $100 off MSRP. B&H Photo has the 13″ 1.4GHz/128GB MacBook... Read more
Apple Expected to Reverse Nine-Month Tablet S...
Apple and Samsung combined accounted for 62 percent of the nearly 36 million branded tablets shipped in 3Q 2014, according to early vendor shipment share estimates from market intelligence firm ABI... Read more
Stratos: 30 Percent of US Smartphone Owners t...
Stratos, Inc., creator of the Bluetooth Connected Card Platform, has announced results from its 2014 Holiday Mobile Payments Survey. The consumer survey found that nearly one out of three (30 percent... Read more
2014 1.4GHz Mac mini on sale for $449, save $...
 B&H Photo has lowered their price on the new 1.4GHz Mac mini to $449.99 including free shipping plus NY tax only. Their price is $50 off MSRP, and it’s the lowest price available for this new... Read more
Check Apple prices on any device with the iTr...
MacPrices is proud to offer readers a free iOS app (iPhones, iPads, & iPod touch) and Android app (Google Play and Amazon App Store) called iTracx, which allows you to glance at today’s lowest... Read more
64GB iPod touch on sale for $249, save $50
Best Buy has the 64GB iPod touch on sale for $249 on their online store for a limited time. Their price is $50 off MSRP. Choose free shipping or free local store pickup (if available). Sale price for... Read more
15″ 2.2GHz Retina MacBook Pro on sale for $17...
 B&H Photo has the 2014 15″ 2.2GHz Retina MacBook Pro on sale for $1799.99 for a limited time. Shipping is free, and B&H charges NY sales tax only. B&H will also include free copies of... Read more
New Logitech AnyAngle Case/Stand Brings Flexi...
Logitec has announced the newest addition to its suite of tablet products — the Logitech AnyAngle. A protective case with an any-angle stand for iPad Air 2 and all iPad mini models, AnyAngle is the... Read more
Notebook PC Shipments Rise Year-Over-Year as...
According to preliminary results from the upcoming DisplaySearch Quarterly Mobile PC Shipment and Forecast Report, the global notebook PC market grew 10 percent year-over-year in Q3’14 to 49.4... Read more

Jobs Board

*Apple* Solutions Consultant (ASC)- Retail S...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*Apple* Store Leader Program - College Gradu...
Job Description: Job Summary As an Apple Store Leader Program agent, you can continue your education as you major in the art of leadership at the Apple Store. You'll 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
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.