TweetFollow Us on Twitter

Multiple Monitors
Volume Number:10
Issue Number:7
Column Tag:There’s a right way...

Related Info: Window Manager Dialog Manager Standard File
Quickdraw

Multiple Monitors vs. Your Application

Assume one monitor, go to jail...

By Eric Shapiro, Rock Ridge Enterprises

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

About the author

Eric earned fame with his big-hit, glam-hack VideoBeep, first shown at MacHack as a prize-winning entry in the MacHax™ Best Hack contest. When he’s not busy writing his next hack for MacHack, Eric is president of Rock Ridge Enterprises, a Macintosh consulting firm. His other smash hits include Spectator, EzTape, Business Simulator, and (the now illegal) The Grouch.

Eric is currently working on course materials for Apple Developer University’s OpenDoc seminar. He has taught Macintosh Programming Fundamentals and Macintosh Device Drivers seminars for Apple as well. Eric has degrees in both Computer and Electrical Engineering from the University of Michigan and is a past president of MacTechnics Users Group.

You can reach Eric at Shapiro@aol.com

[Eric, otherwise way-too-busy-to-write-an-article, found a reason to sound off. The result? A stream-of-consciousness gripe piece with some useful information. If you’d like to see more of these kinds of articles, please let us know. Better yet, pick your favorite gripe about software done the wrong way, and write up your own “There’s a right way ” article. - Ed stb]

I am writing this article because I’ve recently come across 5 new Mac programs in the last few weeks that don’t support multiple monitors correctly. I’m getting sick of rebooting, and of explaining the various problems to the companies involved, so I’m going to send them a copy of this article instead.

Like many programmers, my main screen is a 2-page b&w display while my second screen is a 13” color display. Several of the programs I’ve been running have problems with all 2 monitor systems. Other programs run properly on some 2 monitor setups, but get confused when the main device has a lower depth than the second one.

Here’s a checklist for writing well-behaved Macintosh software:

Open windows on the proper screen

New document windows should be opened on the same screen as the parent window. If there is no parent window, use the main screen (or, if you want to be really cool, use whichever screen was most recently used for a document).

It is easiest to create windows invisibly, add controls and other items to the window, position and resize it, and then make it visible. A new version of one popular developer tool creates the window visibly first, and then quickly snaps it to its new size/location. This is very disconcerting (and somewhat reminiscent of HyperCard).

The Window Manager in System 7 makes it easy to properly place new windows, as long as they don’t need to be resized dynamically. Simply set the Auto-Position field in a WIND or DLOG resource to Parent window or Parent window’s screen.. If your application contains floating palette windows, you’ll have to hide them before calling GetNewWindow or GetNewDialog for this scheme to work.

The standard file box is a particularly nasty dialog, because it’s difficult to center on the proper monitor. The problem is that the size stored in the DLOG resource is unreliable, especially when using utilities like Norton’s “Directory Assistance”. Generally, though, everything works fine if you assume the standard size and place the dialog on the top portion of the designated screen. You will have to use the CustomGetFile call instead of the easier StandardGetFile call to position the dialog on an arbitrary device.

The color picker also needs to be special cased, because it should probably be placed on the deepest device (although this might not be true for all programs). Under recent System versions, this can be accomplished by passing (-1, -1) for the dialog location. Programs like PhotoShop have their own moveable color pickers that the user can drag to any screen.

Default document size

Don’t assume that new document windows should completely fill the main screen. This is very annoying to owners of large displays. Let the user specify a default document size or write a little code to make sure that the default document isn’t oversized.

Dragging

There are still some programs that don’t allow windows to be dragged to second monitors. While holding down the Cmd/Option keys often overrides this problem, the programs really should be updated. Many programs pass screenBits.bounds to DragWindow as the limit rectangle. This works on multiple monitor systems only because Apple put a kludge in the Window Manager to support old software [It may be a kludge, but Apple would be crazy to change it - Ed stb]. Don’t inset it, just pass screenBits.bounds to DragWindow or use the following “morally correct” code:


/* 1 */
 if ( gHasColorQuickDraw )
 limitR = (**GetGrayRgn()).rgnBBox;
 else
 limitR = screenBits.bounds;

 DragWindow( myWindow, theEvent->where, &limitR );

Reference screenBits.bounds as qd.screenBits.bounds when using either MPW or the universal header files.

Zooming

See develop Magazine #17 for a good article on proper zooming. Windows should zoom out to their current monitor and not the main monitor.

Remember window positions

Window positions should be stored within the document file for document windows or within the application’s “Preferences” file for non-document windows. When a document is opened, return the window to the saved location. Be sure to check that the window and its title bar still overlap the grayRgn, because the monitor setup may have changed. I’ve seen several programs (including some best sellers) that will open a window positioned completely off all monitors. Other programs will open windows with their title bars underneath the menu bar. The window’s size should never be larger than the device, because it may be impossible for the user to reach the growBox. Forcing the entire window onscreen is not unreasonable. Lastly, make sure your calculations don’t choke on negative window coordinates - this will be the case for monitors positioned to the left or above the main device.


/* 2 */
/*
 IsPositionOK
 
 Description:
 Checks to make sure the passed global rectangle is completely contained 
within the gray region. Pass the window’s portRect in global coordinates.

 Notes:
Depends on two regions, gSpareRgn1 and gSpareRgn2, having been allocated 
globally (using NewRgn).
  
 Your application might want to allow partially offscreen windows. 
 
Document windows are assumed to have title heights of 20 pixels. There 
are moredynamic ways of handling this, such as positioning the window 
way offscreen and checking its structure region. 
*/
Boolean IsPositionOK( Rect *globalR, Boolean isDocWindow )
{
 BooleanisOK = false;
 Rect   fullWindowR;
  
 #define kDocWindowHeight 20// pixels
 
 // put the window rect into gSpareRgn1
 fullWindowR = *globalR;
 if ( isDocWindow )
 fullWindowR.top -= kDocWindowHeight;
 RectRgn( gSpareRgn1, &fullWindowR );
 
 // see if the window completely intersects the grayRgn
 SectRgn( GetGrayRgn(), gSpareRgn1, gSpareRgn2 );
 if ( EqualRgn( gSpareRgn1, gSpareRgn2 ) )
 isOK = true;
 
 return( isOK );
}

Games

Games are notorious for not running properly on multiple monitor systems. With my particular setup (a b&w main screen and a color 2nd screen), many games look at the main device and put up an error message complaining about the screen depth.

A little extra checking solves this problem. Let’s say your game requires an 8-bit monitor. (Apple says that programs shouldn’t require specific screen depths, but they don’t write games, either [although there was an entire session and a show of support for games at WWDC this year - Ed stb]). If the main screen supports 8-bits, use it. Apple says you shouldn’t force the monitor to a particular depth, but for games it is probably ok. [You can always ask the user whether that’s ok - Ed stb] Use the HasDepth and SetDepth calls to do this and do not call the video drivers directly. If the main screen doesn’t support 8-bit graphics, scan the device list for a device that does. Using the first device you find that supports 8-bit graphics is reasonable, because very few users have 3 monitor systems. If you want to be really cool, though, let the user choose which monitor to play the game on (or play it across several monitors!).

Many games (and other programs a well) use screenBits.bounds to find the size of the monitor. On systems with Color QuickDraw, use the gdRect field of a GDevice instead.


/* 3 */
/*
 FindDeviceThatSupportsDepth
 
 Returns:
 The GDHandle for a device that supports the passed depth.
 Returns nil if no device found or no color quickdraw.
 
 Notes:
 Requires System 6.05 or later.
*/
GDHandle FindDeviceThatSupportsDepth( short theDepth )
{
 GDHandle aScreen;
 
 if ( !gHasColorQuickDraw )
 return( nil );

 // first check the main screen - it takes precedence
 aScreen = GetMainDevice();
 if ( DoesDeviceSupportDepth( aScreen, theDepth ) )
 return( aScreen );
 
 // step through all the screens
 aScreen = GetDeviceList();
 
 while ( aScreen )
 {
 if ( DoesDeviceSupportDepth( aScreen, theDepth ) )
 return( aScreen );
 aScreen = GetNextDevice( aScreen );
 }

 return( nil );
}

Boolean DoesDeviceSupportDepth( GDHandle theDevice, short theDepth )
{
 if (   IsDeviceActive( theDevice ) && 
 HasDepth( theDevice, theDepth, 0/*whichFlags*/, 0 ) )
 return( true );
 else 
 return( false );
}

Boolean IsDeviceActive( GDHandle theDevice )
{
 if ( !theDevice )
 return( false );

 /*
 sometimes newly installed video cards show the main device
 as inactive. we’ll make an extra check for this case.
 */
 if ( theDevice == GetMainDevice() )
 return( true ); // main device is always active
 
 if (   TestDeviceAttribute( theDevice, screenDevice ) &&
 TestDeviceAttribute( theDevice, screenActive ) )
 return( true );
 else
 return( false );
}

General drawing

Responding properly to update events on multiple monitor systems is a little tricky. The programs I’ve been using fall under one of the following categories:

1) Work properly on single monitor systems

2) Work properly on multiple monitor systems, as long as windows don’t span 2 screens of different depths

3) Work properly on all systems and window sizes

Your software should fall under category 3, or at least number 2.

Let’s say your program contains 2 versions of all its artwork - one for b&w monitors and one for color monitors (since dithering is so ugly, you don’t want to draw your color pictures on b&w devices). On a single device system, it is easy to choose which picture to display - just look at the main screen’s depth. On a multiple device system, the picture choice must be made by looking at the window’s size and position. If a window spans 2 monitors, you may have to load and draw both the b&w picture and the color picture in response to a single update event.

See develop #13 for an article on the DeviceLoop call and how it will help you handle this problem. For programmers supporting older System versions, it’s not too hard to write your own version of DeviceLoop.

As an example of improper drawing, look at these two screen dumps from America Online. The top one indicates how the b&w artwork should look. The bottom one shows what happens when the color artwork is displayed on a b&w screen.

Screen depth change

Except for games, programs should be able to run at any screen depth. Users can change the depth at will - you should check the monitor depth during update events to see if it has changed. If you keep offscreen buffers, you may have to change their size and depth as well. This can present a problem if the user increases the screen depth and you don’t have enough memory for your offscreen buffers. In that case, consider drawing the window contents without the buffers.

Even games shouldn’t crash if the user changes screen depths. I suggest pausing the game and opening a moveable error dialog explaining the situation.

Minimizing the amount of RAM required for update events is always a good idea. You can spool picture resources instead of loading them completely into RAM. Unfortunately, there’s no simple “DrawSpooledPictureResource” call, so you’ll have to write the spooling code yourself.

“This model’s so fast we had to put speedbumps on the hard drive!”

Use GWorlds and not offscreen CGrafPorts.

In order to draw properly offscreen, you should use either GWorlds or CGrafPort/GDevice combinations. Creating only a CGrafPort is not enough, because QuickDraw will use the current GDevice’s inverse table when drawing to the offscreen buffer. On my machine, the default GDevice is a 1-bit device, so its inverse table is pretty useless (it actually is filled with 0x01). If your graphics appear in a light yellow color on secondary screens, this is likely the cause.

Window PixMaps

Some sample code I recently looked at chose the depth of its offscreen buffers by looking at the portPixMap field within a CWindowRecord. This PixMap always represents the main device, even when a window is on another screen. Color QuickDraw “notices” this when drawing and special cases its drawing calls to work across multiple devices.

To find the desired depth and color table for an offscreen copy of a window’s contents, use a routine like:

 
/* 4 */
short FindWindowDepth( WindowPtr myWindow )
{
 Rect   r;
 GDHandle theDevice;
 short  theDepth;
 GrafPtroldPort;

 if ( !gHasColorQuickDraw )
 return( 1 );    // 1-bit if no color quickdraw

 GetPort( &oldPort );// save old port
 SetPort( myWindow );
 
 // get the window’s content rect in global coords
 r = myWindow->portRect;  
 LocalToGlobal( (Point*) &r );
 LocalToGlobal( 1 + (Point*) &r );

 // find the deepest device intersecting the window
 theDevice = GetMaxDevice( &r );
 theDepth = theDevice ? (**(**theDevice).gdPMap).pixelSize : 1;

 // color table is at: (**(**theDevice).gdPMap).pmTable

 SetPort( oldPort ); // restore port
 return( theDepth );
}

Hiding the menu bar

Most programs shouldn’t hide the menu bar, but it’s a necessary evil for games, slide shows, and multimedia demos. Be sure to hide the menu bar only if your presentation is running on the main device. Be sure to save/restore the menu bar area on switch events because it will be changed while you are in the background. Many programs incorrectly assume that users won’t be able to “switch out” of their applications because they create windows the same size as the screen. On multi-monitor systems, switching out is as easy as clicking on the desktop on the second monitor. (If you really must prevent switching out, your best bet is to never call GetNextEvent or WaitNextEvent).

Summary

If you follow these suggestions, your programs should be multi-monitor friendly. While it may not be trivial to support multiple monitors properly, annoying users is the only alternative. Remember that most PowerMacs have built-in support for 2 monitors, so this issue is more important now than ever.

Besides, this might just be the way to convince your boss to buy you a second screen.

 
AAPL
$99.59
Apple Inc.
-1.17
MSFT
$46.17
Microsoft Corpora
-0.20
GOOG
$569.92
Google Inc.
-7.44

MacTech Search:
Community Search:

Software Updates via MacUpdate

Cocktail 8.0 Beta 2 - General maintenanc...
Cocktail is a general purpose utility for OS X that lets you clean, repair and optimize your Mac. It is a powerful digital toolset that helps hundreds of thousands of Mac users around the world get... Read more
QuickBooks 2015 16.0.0.1352 R1 - Financi...
QuickBooks 2015 helps you manage your business easily and efficiently. Organize your finances all in one place, track money going in and out of your business, and spot areas where you can save.... Read more
Mac DVDRipper Pro 5.0.1 - Copy, backup,...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
Apple OS X bash Update 1.0 - Fix for sec...
The OS X bash Update fixes a security flaw in the bash UNIX shell on OS X 10.9.5 (also on OS X 10.8 and 10.7 [see Related Links below]). OS X 10.9.5 or later Downloads for OS X 10.8 and OS X 10.7 in... Read more
SyncTwoFolders 2.0.5 - Syncs two user-sp...
SyncTwoFolders simply synchronizes two folders. It supports synchronization across mounted network drives and it is a possibility to run a simulation showing in a log what will be done. Please visit... Read more
FinderPop 2.5.7 - Classic Mac utility, n...
FinderPop is a Universal preference pane that extends OS X's contextual menus using a FinderPop Items folder much as the Apple Menu Items folder used to do for the Apple menu. It has other features... Read more
VueScan 9.4.45 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
LibreOffice 4.3.2.2 - Free Open Source o...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
calibre 2.4 - Complete e-library managem...
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
Default Folder X 4.6.9b1 - Enhances Open...
Default Folder X attaches a toolbar to the right side of the Open and Save dialogs in any OS X-native application. The toolbar gives you fast access to various folders and commands. You just click... Read more

Latest Forum Discussions

See All

Nexticy Review
Nexticy Review By Jennifer Allen on October 1st, 2014 Our Rating: :: IDEAL FORM CREATIONiPad Only App - Designed for the iPad Nexticy allows you to make your own forms for research purposes or to organize your business better. It’s... | Read more »
HeroCraft Introduces Unlimited Sequel to...
HeroCraft Introduces Unlimited Sequel to WW2: Sandbox. Strategy & Tactics Posted by Jessica Fisher on October 1st, 2014 [ permalink ] | Read more »
RGB Express Review
RGB Express Review By Jennifer Allen on October 1st, 2014 Our Rating: :: DELIGHTFUL PUZZLINGUniversal App - Designed for iPhone and iPad Guide trucks along their delivery routes in RGB Express, a testing but charming puzzle game... | Read more »
The Sagas of Fire*Wolf (Games)
The Sagas of Fire*Wolf 1.0 Device: iOS Universal Category: Games Price: $9.99, Version: 1.0 (iTunes) Description: | Read more »
BuggyFun Review
BuggyFun Review By Amy Solomon on October 1st, 2014 Our Rating: iPad Only App - Designed for the iPad BuggyFun allows children to create their own tracks for bugs to interact with for a unique open-ended experience.   | Read more »
Fold the Adventure Review
Fold the Adventure Review By Jennifer Allen on October 1st, 2014 Our Rating: :: AWKWARD FOLDSUniversal App - Designed for iPhone and iPad Fold pieces of paper to create platforms for a princely rabbit in this puzzle game; something... | Read more »
WW2: Sandbox. Strategy & Tactics (G...
WW2: Sandbox. Strategy & Tactics 1.0.0 Device: iOS Universal Category: Games Price: $9.99, Version: 1.0.0 (iTunes) Description: Sandbox is the unlimited sequel to our Strategy & Tactics: World War II. We've abandoned... | Read more »
apeFilter (Music)
apeFilter 1.0 Device: iOS Universal Category: Music Price: $6.99, Version: 1.0 (iTunes) Description: | Read more »
Shred It! Review
Shred It! Review By Jennifer Allen on September 30th, 2014 Our Rating: :: GORGEOUS BUT BASICUniversal App - Designed for iPhone and iPad It might look lovely, but Shred It! is a pretty shallow endless runner/snowboarding game.   | Read more »
Check Out the New Teaser Trailer forGAME...
Check Out the New Teaser Trailer forGAMEVIL’s Darkness Reborn Posted by Jessica Fisher on September 30th, 2014 [ permalink ] Darkness Reborn, by GAMEVIL< | Read more »

Price Scanner via MacPrices.net

Apple resting On Its iPhone Laurels? – The ‘B...
Apple calls its new iPhone 6 and 6 Plus “The Biggest Advancements in iPhone History,” but does reality live up to the hype? “Seldom have so many waited so breathlessly for so little,” tweeted veteran... Read more
Roundup of Apple Mac and iPad Education disco...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
Apple Boycotts German Magazine Computer Bild...
Apple has revoked its PR accreditation of Germany’s Computer Bild, Europe’s best-selling PC magazine, in reaction to Bild’s posting of a “#Bentgate” YouTube video. Axel Telzerow, editor in chief of... Read more
iPhone 6 & iPhone 6 Plus Available in Chi...
Apple has announced that iPhone 6 and iPhone 6 Plus will be available in China beginning Friday, October 17 from the Apple Online Store (http://www.apple.com), Apple’s retail stores, and an expansive... Read more
MacBook Airs on sale for $100 off MSRP, start...
Best Buy has the new 2014 MacBook Airs on sale for $100 off MSRP on their online store. Choose free home shipping or free local store pickup (if available). Prices valid for online orders only, in-... Read more
Apple Releases OS X Mavericks bash Update 1.0...
Apple has released a patch update for OS X Mavericks users to address the recently-detected “Shellshock” security bug in BSD UNIX’s bash shell. Apple says only a few Mac users who had manually... Read more
Pivotal Payments Ready for Apple Pay – FlexPo...
Pivotal Payments, a provider of merchant services and global payment processing solutions, has announced its proprietary FlexPoint platform will support credit and debit transactions through Apple’s... Read more
iStabilizer Announces Tabarm — First Friction...
iStabilizer, a specialist in universal lightweight compact tripods, steady cams, dollies, mounts, and remotes for smartphones, tablets, and cameras, announced today the iStabilizer tabArm, the first... Read more
IStabilizer Flex Smartphone Tripod Wins Usa T...
iStabilizer, a specialist in universal lightweight compact tripods, steady cams, and other products for smartphones, tablets, and cameras, has announced today that its iStabilizer Flex smartphone... Read more
13-inch 2.8GHz Retina MacBook Pro on sale for...
B&H Photo has the new 2014 13″ 2.8GHz Retina MacBook Pro on sale for $1699.99 including free shipping plus NY sales tax only. They’ll also include free copies of Parallels Desktop and LoJack for... Read more

Jobs Board

*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
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, 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
*Apple* Solutions Consultant (ASC) - Apple (...
**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 / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.