TweetFollow Us on Twitter

Splitting Windows
Volume Number:11
Issue Number:1
Column Tag:Improving The Framework

Splitting Windows in MacApp

You know, programming in MacApp is a lot like playing golf.

By Tom Otvos, EveryWare Development Corp.

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

You know, programming in MacApp is a lot like playing golf. With a little bit of practice, you can become fairly competent and hit a respectable score, and with about the same amount of practice, you can write a respectable, Mac-looking application. There will come a time, however, when you want to stretch the bounds a little bit, and add some cool user interface gadget that will differentiate your application from another. You want to hit a birdie on that par four 15th. To make that kind of advance, you need a little bit more than practice; you need a deeper understanding of the game, and the ability ”to read the greens”. You need to understand how some of these disparate parts of a rather complicated application framework come together, so you can not only make it do what you want, but do it the right way.

Before I lead you too far along, I should say at this point that I am not a very good golfer. I have not yet made that transition to really knowing what I am doing, and then merely applying that knowledge to the situation at hand. Okay, let’s cut to the chase. I am struggling. I have been doing MacApp a bit longer, however, and so I can generally get it to do what I want in the way that I want it with relative ease. Along the way, I have picked up a few tricks that, in the end, are really very simple, but they achieve a neat effect that has a lot of application. In this article, I want to talk about a useful trick that, amazingly, I was not able to find documented anywhere else, namely splitting windows. I really needed to split windows for an app that I am working on, so I created the following two classes to do it. Since it was really very simple and a trivial amount of code, I figured that sharing it would be the right thing to do. I hope you find it useful.

Splitting components

So that we have a clear picture in our heads during the following discussion, let’s look at the geometry a bit. Splitting windows, in MacApp terms, really reduces to taking two TView objects and adjusting their sizes inversely relative to each other. In the simplest case, picture two views joined along one edge, and then dragging that edge so that as one view grows in size, the other shrinks. If the two view objects are the same class, then you can easily implement the classic word processing implementation of splitting, where you are looking at the same document in two or more panes, each displaying a different region of the document. Or, the two views can be from very different classes that display some common data in different ways. An example might be a view editor that shows the view hierarchy as it would appear on screen in one area, and a list representation of the hierarchy in another area.

To split a window, I have created two classes: TSplitterControl and TSplitterTracker. The TSplitterControl class does two very simple things. First, it provides a user interface to the splitting action, giving the user a “knob” to direct the split. Second, it is responsible, at the programmatic level, for initiating the splitting by instantiating the splitter tracker. The TSplitterTracker class is the workhorse of the pair, as it tracks the mouse during splitting, providing continual user feedback and, ultimately, reconfiguring the views after the splitting is done. [Because the code for these classes is so simple, I will include it in the text of this article. Some code polish that I have added to my classes will be omitted, but I assure you that nothing important will be left out.]

TSplitterControl

The class definition for the TSplitterControl is reproduced below.

class TSplitterControl : public TControl
{
private:
 TView* fFirstView;
 TView* fSecondView;
public:
 virtual pascal void Initialize();
 virtual pascal void DoMouseCommand(
 VPoint&    theMouse, 
 TToolboxEvent*  event, 
 CPoint   hysteresis);
 virtual pascal void Draw(const VRect& area); 
 // override
 virtual pascal void SuperViewChangedFrame(
 const VRect&  oldFrame,  
 const VRect&  newFrame,  
 Boolean  invalidate);
 virtual pascal void SetSplitViews(
 TView* firstView, 
 TView* secondView);
};

The only method that is of any real consequence is DoMouseCommand():

pascal void TSplitterControl::DoMouseCommand(
 VPoint&    theMouse, 
 TToolboxEvent*  event, 
 CPoint   hysteresis)
 // override
{
    // mouse hits in our control will immediately post a splitter
    // tracker command
 TSplitterTracker* splitter = new TSplitterTracker;
 splitter->ISplitterTracker(fFirstView, 
 fSecondView, this, theMouse);
 this->PostCommand(splitter);
 
 inherited::DoMouseCommand(theMouse, event, hysteresis);
}

The only function of this method is to detect mouse hits in our control and post an instance of our splitter tracker. Note that in MacApp a TTracker is a TCommand subclass and needs to be posted in the command queue to get executed. Also note that the control passes to the tracker two views as part of its initialization. These two views are the views that are going to be adjusted at the end of the splitting process.

The remaining methods of this class are what I lump into “polish”, and you can provide your own variations as you see fit. Specifically, the Draw() method can be overridden, as I originally did, to draw a filled rectangle as the splitting knob. Users of Microsoft Word or MPW will find this type of splitter familiar. Ultimately, I opted for a splitting more like Object Master or MacBrowse, in which window panes are dragged by their edges to reconfigure their sizes. In this case, the Draw() method is superfluous, and the default MacApp drawing with appropriate adornment suits me just fine. The override to SuperViewChangedFrame() is necessary if you position your control such that its location needs to be modified when the window is zoomed or otherwise resized. I can never understand why MacApp views do not have a position determiner instance variable, with values like posRelRightEdge, so that I do not always have to override this method.

In my implementation, I always had two views defined in my window and so effectively, my window was already split. The splitter was merely adjusting the relative sizes of these views. However, you could easily envision a case where you would want to do true splitting, and every time you dragged down on the splitter control, you would split off a new pane of the existing view. I haven’t tried this, but I would guess that the best way to do this would be to clone the view you wish to split in the DoMouseCommand() method, insert it into the superview at an appropriate location, set its initial size to zero, and then pass it into the TSplitterTracker as one of the views.

One other user interface tip: You can have MacApp automatically change the cursor when it tracks over your control without writing a single line of code. Just use your favorite view editor to tell MacApp that the control is going to handle the cursor (fHandlesCursor), and specify a cursor resource ID (fCursorID) that should be used. I use a neat double-headed arrow

TSplitterTracker

The tracker does most of the work required for splitting, and MacApp handles most of the work required for tracking. Typically, you only need to override methods of TTracker to provide specific user feedback, to constrain tracking in a particular direction, and to “do something” when the tracking is done. The class definition of TSplitterTracker is shown below:

class TSplitterTracker : public TTracker
{
private:
 VCoordinate fDelta;
 TView* fFirstView;
 TView* fSecondView;
 TView* fSplitter;
public:
 virtual pascal void ISplitterTracker(
 TView* firstView, 
 TView* secondView, 
 TView* splitter, 
 VPoint&  itsMouse);
 virtual pascal void TrackConstrain(
 TrackPhase aTrackPhase, 
 const VPoint&   anchorPoint, 
 const VPoint&   previousPoint,
 VPoint&  nextPoint, 
 Boolean  mouseDidMove); 
 // override
 virtual pascal void TrackFeedback(
 TrackPhase aTrackPhase, 
 const VPoint&   anchorPoint, 
 const VPoint&   previousPoint,
 const VPoint&   nextPoint, 
 Boolean  mouseDidMove, 
 Boolean  turnItOn); 
 // override
 virtual pascal void DoIt(); // override
};

I always found trackers a rather mystifying element of the MacApp architecture, until I sat down and actually wrote a couple. They turn out to be quite simple largely because MacApp handles a lot of the gory details for you. For example, if you want to limit tracking in a single direction, the only thing you have to do is override TrackConstrain() and do something like this:

 inherited::TrackConstrain(aTrackPhase, anchorPoint, 
 previousPoint, nextPoint, 
 mouseDidMove);
 if (mouseDidMove)
    // limit tracking to one direction only
 nextPoint.h = previousPoint.h;

Basically, this method gives you a chance to recalculate the position of the mouse, so that MacApp thinks that it only moved in one direction. In the example above, I am forcing the tracker to only track in the vertical direction.

Initializing the tracker includes one important detail that you must pay attention to. When you call ITracker, you must provide a view with which the tracker is associated. One of the side effects of this is that tracking will be clipped to this view, so typically you would specify an enclosing view that will contain all of the tracking, such as, in our case, the window being split.

The TrackFeedback() method, not surprisingly, allows you a chance to provide whatever feedback you wish to the user, as well as hook in during the various track “phases” to extract whatever information you might think is necessary. For example, in the code below, I use my override to initialize an instance variable that will be used to determine how much tracking was done, and when the tracking is done, I calculate how far the mouse tracked in the vertical direction:

 switch (aTrackPhase) {
 case trackBegin:// initialize our track delta
 fDelta = 0;
 break;
 case trackEnd:  // how far did we go?
    // anchor point is always in splitter coordinates
 anchor = anchorPoint;
 fSplitter->LocalToWindow(anchor);
 next = nextPoint;
    // next point is always in view coordinates
 fView->LocalToWindow(next);
 fDelta = next.v - anchor.v;
 break;
 }
    // draw some nice feedback for the user  
 PenSize(2, 2);
 PenPat(&qd.gray);
 fView->GetQDExtent(qdExtent);
 MoveTo(qdExtent[topLeft].h, nextPoint.v);
 LineTo(qdExtent[botRight].h, nextPoint.v);

Additionally, regardless of the track phase, I draw a thick gray line across the width of the views being split, giving the user clear and easily understood feedback. MacApp provides some default feedback for you, if you wish to use it, in the form of a gray outline of the view to which the tracker is attached, but generally, I find that I have to provide my own feedback for one reason or another.

As mentioned earlier, the TTracker class descends from TCommand, and it uses the DoIt() method of TCommand to signal when tracking is complete and you need to react to it in some way. Here is the DoIt() method in its entirety:

pascal void TSplitterTracker::DoIt()
{
 VRect frame1, frame2;
    // adjust fDelta so neither view becomes invalid
 fFirstView->GetFrame(frame1);
 if (fDelta < frame1.top - frame1.bottom)
 fDelta = frame1.top - frame1.bottom;
 fSecondView->GetFrame(frame2);
 if (fDelta > frame2.bottom - frame2.top)
 fDelta = frame2.bottom - frame2.top;
    // adjust the first view from the bottom, the second from the top
 frame1.bottom += fDelta;
 fFirstView->SetFrame(frame1, kRedraw);
 frame2.top += fDelta;
 fSecondView->SetFrame(frame2, kRedraw);
}

In the code above, after some preflighting to ensure that neither view becomes negative in size, the views’ frames are adjusted in the vertical dimension by the delta amount tracked by the tracker. Note that one view has its bottom adjusted, and the other has its top adjusted. We could just as easily have tracked in the horizontal direction, and consequently adjusted the right and left edges. Or, a truly generic tracker could have been written that could track in either direction, or both. A simple call to SetFrame() was all that was needed to resize the two views. If your view hierarchy is set up correctly, then all relevant subviews will resize as necessary. Additionally, any overrides to SuperViewChangedFrame() in your subviews will also be called, in case you need to do dynamic repositioning of objects not done automatically by MacApp.

The Final Word

As I stated at the outset, there is not a lot of code required to achieve the view splitting effect in MacApp. I was actually amazed that there was not already some sample code out there that I could mooch from. Equally amazing was that cries for help on MacApp3Tech$ from others looking for similar code went unanswered. Well, someone was listening, and I hope that this article helps.

Now, if someone can only help me cure my slice

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

LaunchBar 6.18.5 - Powerful file/URL/ema...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
Affinity Designer 2.3.0 - Vector graphic...
Affinity Designer is an incredibly accurate vector illustrator that feels fast and at home in the hands of creative professionals. It intuitively combines rock solid and crisp vector art with... Read more
Affinity Photo 2.3.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
WhatsApp 23.24.78 - Desktop client for W...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
Adobe Photoshop 25.2 - Professional imag...
You can download Adobe Photoshop as a part of Creative Cloud for only $54.99/month Adobe Photoshop is a recognized classic of photo-enhancing software. It offers a broad spectrum of tools that can... Read more
PDFKey Pro 4.5.1 - Edit and print passwo...
PDFKey Pro can unlock PDF documents protected for printing and copying when you've forgotten your password. It can now also protect your PDF files with a password to prevent unauthorized access and/... Read more
Skype 8.109.0.209 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
OnyX 4.5.3 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
CrossOver 23.7.0 - Run Windows apps on y...
CrossOver can get your Windows productivity applications and PC games up and running on your Mac quickly and easily. CrossOver runs the Windows software that you need on Mac at home, in the office,... Read more
Tower 10.2.1 - Version control with Git...
Tower is a Git client for OS X that makes using Git easy and more efficient. Users benefit from its elegant and comprehensive interface and a feature set that lets them enjoy the full power of Git.... Read more

Latest Forum Discussions

See All

Pour One Out for Black Friday – The Touc...
After taking Thanksgiving week off we’re back with another action-packed episode of The TouchArcade Show! Well, maybe not quite action-packed, but certainly discussion-packed! The topics might sound familiar to you: The new Steam Deck OLED, the... | Read more »
TouchArcade Game of the Week: ‘Hitman: B...
Nowadays, with where I’m at in my life with a family and plenty of responsibilities outside of gaming, I kind of appreciate the smaller-scale mobile games a bit more since more of my “serious" gaming is now done on a Steam Deck or Nintendo Switch.... | Read more »
SwitchArcade Round-Up: ‘Batman: Arkham T...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for December 1st, 2023. We’ve got a lot of big games hitting today, new DLC For Samba de Amigo, and this is probably going to be the last day this year with so many heavy hitters. I... | Read more »
Steam Deck Weekly: Tales of Arise Beyond...
Last week, there was a ton of Steam Deck coverage over here focused on the Steam Deck OLED. | Read more »
World of Tanks Blitz adds celebrity amba...
Wargaming is celebrating the season within World of Tanks Blitz with a new celebrity ambassador joining this year's Holiday Ops. In particular, British footballer and movie star Vinnie Jones will be brightening up the game with plenty of themed in-... | Read more »
KartRider Drift secures collaboration wi...
Nexon and Nitro Studios have kicked off the fifth Season of their platform racer, KartRider Dift, in quite a big way. As well as a bevvy of new tracks to take your skills to, and the new racing pass with its rewards, KartRider has also teamed up... | Read more »
‘SaGa Emerald Beyond’ From Square Enix G...
One of my most-anticipated releases of 2024 is Square Enix’s brand-new SaGa game which was announced during a Nintendo Direct. SaGa Emerald Beyond will launch next year for iOS, Android, Switch, Steam, PS5, and PS4 featuring 17 worlds that can be... | Read more »
Apple Arcade Weekly Round-Up: Updates fo...
This week, there is no new release for Apple Arcade, but many notable games have gotten updates ahead of next week’s holiday set of games. If you haven’t followed it, we are getting a brand-new 3D Sonic game exclusive to Apple Arcade on December... | Read more »
New ‘Honkai Star Rail’ Version 1.5 Phase...
The major Honkai Star Rail’s 1.5 update “The Crepuscule Zone" recently released on all platforms bringing in the Fyxestroll Garden new location in the Xianzhou Luofu which features many paranormal cases, players forming a ghost-hunting squad,... | Read more »
SwitchArcade Round-Up: ‘Arcadian Atlas’,...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for November 30th, 2023. It’s Thursday, and unlike last Thursday this is a regular-sized big-pants release day. If you like video games, and I have to believe you do, you’ll want to... | Read more »

Price Scanner via MacPrices.net

Deal Alert! Apple Smart Folio Keyboard for iP...
Apple iPad Smart Keyboard Folio prices are on Holiday sale for only $79 at Amazon, or 50% off MSRP: – iPad Smart Folio Keyboard for iPad (7th-9th gen)/iPad Air (3rd gen): $79 $79 (50%) off MSRP This... Read more
Apple Watch Series 9 models are now on Holida...
Walmart has Apple Watch Series 9 models now on Holiday sale for $70 off MSRP on their online store. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
Holiday sale this weekend at Xfinity Mobile:...
Switch to Xfinity Mobile (Mobile Virtual Network Operator..using Verizon’s network) and save $500 instantly on any iPhone 15, 14, or 13 and up to $800 off with eligible trade-in. The total is applied... Read more
13-inch M2 MacBook Airs with 512GB of storage...
Best Buy has the 13″ M2 MacBook Air with 512GB of storage on Holiday sale this weekend for $220 off MSRP on their online store. Sale price is $1179. Price valid for online orders only, in-store price... Read more
B&H Photo has Apple’s 14-inch M3/M3 Pro/M...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on Holiday sale this weekend for $100-$200 off MSRP, starting at only $1499. B&H offers free 1-2 day delivery to most... Read more
15-inch M2 MacBook Airs are $200 off MSRP on...
Best Buy has Apple 15″ MacBook Airs with M2 CPUs in stock and on Holiday sale for $200 off MSRP on their online store. Their prices are among the lowest currently available for new 15″ M2 MacBook... Read more
Get a 9th-generation Apple iPad for only $249...
Walmart has Apple’s 9th generation 10.2″ iPads on sale for $80 off MSRP on their online store as part of their Cyber Week Holiday sale, only $249. Their prices are the lowest new prices available for... Read more
Space Gray Apple AirPods Max headphones are o...
Amazon has Apple AirPods Max headphones in stock and on Holiday sale for $100 off MSRP. The sale price is valid for Space Gray at the time of this post. Shipping is free: – AirPods Max (Space Gray... Read more
Apple AirTags 4-Pack back on Holiday sale for...
Amazon has Apple AirTags 4 Pack back on Holiday sale for $79.99 including free shipping. That’s 19% ($20) off Apple’s MSRP. Their price is the lowest available for 4 Pack AirTags from any of the... Read more
New Holiday promo at Verizon: Buy one set of...
Looking for more than one set of Apple AirPods this Holiday shopping season? Verizon has a great deal for you. From today through December 31st, buy one set of AirPods on Verizon’s online store, and... Read more

Jobs Board

Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in 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
Housekeeper, *Apple* Valley Villa - Cassia...
Apple Valley Villa, part of a senior living community, is hiring entry-level Full-Time Housekeepers to join our team! We will train you for this position and offer a Read more
Senior Manager, Product Management - *Apple*...
…Responsibilities** We are seeking an ambitious, data-driven thinker to assist the Apple Product Development team as our Wireless Product division continues to grow Read more
Mobile Platform Engineer ( *Apple* /AirWatch)...
…systems, installing and maintaining certificates, navigating multiple network segments and Apple /IOS devices, Mobile Device Management systems such as AirWatch, and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.