Save Our Screens 101

How To Write A Mac OS X Screen Saver, Part 1

by David Hill

Introduction

Everybody out there who has used a computer for more than a few minutes knows what screen savers are and
there have been many screen savers written for the Macintosh and other computers. Some were single-purpose and
provided only one animation but did it very well. Many others took a different approach and provided a generic
engine that made use of plugin modules. With Mac OS X, Apple has included a Cocoa plugin based engine
controlled via a System Preferences pane (Figure 1). The engine provides screen locking, window management,
multiple screen support, and other features, freeing up the plugin developer to worry about the part that
differentiates their product, the animation. A minimal Mac OS X screen saver module needs to worry about
nothing more than drawing the next frame of its animation when requested to by the screen saver engine.

Figure 1. Screen shot of the
Panther Screen Saver Preferences pane

Writing screen savers is easier than ever with Mac OS X and in this article I'm going to start by showing
you how to write a simple module. We'll begin with the basics of screen saver construction in Xcode and work
our way up to handling events, providing a configuration sheet, and changing display resolution. Along the
way, we'll talk about different drawing APIs, debugging tips, random numbers, and user preferences. I'll also
cover some tips and tricks as well as point out some trouble spots you'll need to watch out for.

For the purposes of this article, I'm going to assume that you have Mac OS X and the developer tools
installed if you want to follow along. You'll need some development experience and a basic knowledge of C. The
interface for the screen saver plugins is in Objective-C but, since Objective-C is a close cousin of C, most
C/C++ and Java developers should be able to follow along without too much trouble. For those who would like to
learn more about Objective-C, Apple provides some excellent documentation on their web site at
http://developer.apple.com/documentation/Cocoa/ObjectiveCLanguage-date.html. I'll also give all of my
directions and screen shots with respect to Mac OS X version 10.3 (Panther) and Xcode so those of you running
different versions of Mac OS X will need to mentally map from 10.3 to your OS version and development
environment.

Basics

The ScreenSaver.framework provides two screen saver-specific classes that you'll need (ScreenSaverView and
ScreenSaverDefaults) as well as a few utility functions for generating random numbers and centering
rectangles. The most important of the two classes is ScreenSaverView, a subclass of NSView. The NSView class
is responsible for drawing to the screen and handling user input. The ScreenSaverView class derives from
NSView and adds support for animation plus a few other screen saver specific methods.

One part of screen saver development that can be confusing to developers is the question of where to do
their drawing. If you look at the ScreenSaverView header, you'll notice that the ScreenSaverView class
provides two promising methods: animateOneFrame and drawRect:. If you're familiar with Cocoa's view system,
you'll recognize drawRect: as the standard method in which views do their drawing and it turns out that this
is best place for your screen saver to do its drawing as well. This is particularly true for more advanced
screen savers that make use of subviews to draw with OpenGL or QuickTime and we'll cover subviews in a later
section. The reason to draw in drawRect: is that Cocoa will call drawRect: at various points in the life of
your screen saver and you must be ready to handle those requests. For that reason, the recommended coding
convention is to use animateOneFrame to update your animation state and then tell Cocoa that your view needs
redrawing. This redraw request will cause Cocoa to call drawRect: where your screen saver will completely
redraw the view to reflect its current state. In most screen savers, the drawRect: method erases the
background, filling it with black or a background image, and then draws the objects that appear in the view.

However, there is one type of screen saver that needs to handle drawing slightly differently. Some simple
screen savers accumulate content via repeated drawing into the view. By their very nature, they can't redraw
the current state of the view because they don't keep track of what they've already drawn. In order to
accumulate content, these simple screen savers must only erase the background of the view the first time
they're asked to draw. The basic screen saver example I'll be using for the first part of the article falls
into this stateless category so I'll cover the extra bits of code you'll need to write an accumulating screen
saver as we go along.

A typical screen saver will subclass ScreenSaverView, override a few important methods, add a few more of
its own, and let the screen saver framework and engine handle the rest. The Xcode screen saver template
provides stub implementations for 7 key methods but for a basic screen saver we'll only need to change the
-drawRect: and -animateOneFrame methods, override two other superclass methods, and declare a new member
variable. The rest of the stub code will suffice for now.

Figure 2. Initial screen saver project window

First, bring up Xcode and start a new screen saver project if you haven't already. You'll find the template
called Screen Saver in the Standard Apple Plug-ins list. Give the new project a creative name. I've called my
project projectName and so Xcode has created a few files for me with appropriate names. See Figure 2 for a
look at the initial project. The most important one is called projectNameView.m. From this point on, I'll
assume that your project is called projectName so open up your project and follow along as we add some simple
drawing code.

1. Declare a new member variable in the projectNameView.h file with this code:

- (void)viewDidMoveToWindow {
// this NSView method is called when our screen saver view is added to its window
// we'll use this signal to tell drawRect: to erase the background
mDrawBackground = YES;
}

3. Replace the drawRect: method in the projectNameView.m file with this code:

Build your screen saver and correct any errors that Xcode finds. Once your project has built successfully,
you'll find the built version of the screen saver in your project's build directory. Look for the file named
projectName.saver.

Now that you've built your screen saver, I need to take a moment to explain how to get the system to
recognize and display it. Screen savers must be installed into one of two places on your system in order for
the screen saver engine to load and run them. If you'd like to make your screen saver available to all users
on your system, use the Finder to copy it into /Library/Screen Savers/ but note that you'll need
administrative privileges for the copy operation. If, however, you only want the screen saver to be available
to the current user, copy the plugin into ~/Library/Screen Savers/. Once you've placed the screen saver into
one of the two directories, open System Preferences and choose the Screen Saver tab within the Desktop and
Screen Savers pane. Your new screen saver should show up in the list on the left-hand side. Select it and
click the Test button to take your plugin for a spin.

If everything went according to plan (does it ever?), the screen saver engine should take over the display,
load your module, and start calling -animateOneFrame periodically to update the screen. If that's not what
happened on your machine, here is a checklist of possible trouble spots.

1. Screen saver didn't show up in the list verify .saver extension and installation location, relaunch
System Preferences

6. Weird System Preferences pane behavior check for possible symbol name conflict with another Objective-C bundle

7. Screen saver repeatedly draws a single random rectangle over a pin-striped background make sure you
spelled isOpaque correctly

Did it work? Great! You'll notice that the end result isn't too bad for a few lines of code. The
frameworks do quite a bit of work for you. As a quick example of the extra power available to your screen
saver, add the following code right before the call to NSBezierPath at the end of drawRect: that fills the
random rectangle.

Build your saver, copy it over, and try it out. Did the screen saver behavior change? If not, you've
probably forgotten to copy the updated screen saver plugin into the Screen Savers folder. Clearly, having to
copy the updated build over every time you make a change will get old during development. The simplest way to
fix this is to add a Copy Files build phase to your project that copies the finished screen saver from the
build directory to /Library/Screen Savers/ or ~/Library/Screen Savers/ once the build is complete. Open your
project window, select your screen saver in the Targets list, and select New Build Phase -> New Copy Files
Build Phase from the Project menu. See Figure 3. Once you've added the new build phase, you must set two
additional parameters: the source files and the destination path.

Figure 3. Targets list with a Copy Files Build Phase

If the Copy Files Info window isn't already open, select the Copy Files build phase and hit CMD-I to open
the Copy Files Info window. Select Absolute Path from the Destination pop up menu and type the path to your
desired installation location into the Path edit field. Figure 4 shows the Copy Files Info window with the
correct settings. Note: there appears to be a bug (already filed) in the Copy Files build phase that prevents
it from resolving the ~ (tilde) character so you can't just type in ~/Library/Screen Savers/ to copy your
screen saver into the current user's folder. You'll need to type in the whole, explicit path to the user's
Screen Savers directory if you want to install the screen saver for just the current user. If, on the other
hand, you want the screen saver installed for all users on the machine, you can type /Library/Screen Savers/
into the Path box and the Copy Files build phase will work just fine. Coupled with a custom executable in
Xcode, you'll be able to run and debug your screen saver directly from Xcode. See the debugging section below
for more information on adding a custom executable to your project.

Figure 4. Copy Files Info window

To set the files to be copied, click the disclosure triangles to display the contents of both the Products
group and the projectName target and then drag the projectName.saver item from the Products group to the Copy
Files build phase. If you do it right, you should see a black horizontal line with a circle on the left end
that indicates where the dragged item will go when you drop it. Make sure that the line is just under the
Copy Files build phase item when you let go of the mouse button. See Figure 5 to see what I mean.

Figure 5. Setting up the Copy Files Build Phase

Another gotcha you may run into is that the Screen Savers preferences pane cannot unload your old saver and
load in a new version when you make changes while you have the Screen Saver pane open in the System
Preferences application. Either quit the System Preferences application before making changes to your screen
saver or, even better, add the Copy Files build phase and custom executable to your Xcode project which will
allow you to run your screen saver from Xcode instead of the System Preferences application. Don't worry if
you're still having trouble. I'll cover more debugging tips later on. In the next section, we'll take a
closer look at the ScreenSaverView class and its methods.

ScreenSaverView Class

As I mentioned earlier, the ScreenSaverView class adds a few screen saver specific methods to the NSView
class. Let's take a look at those new methods and see how they work together to save our screens. I've
divided the list into two parts: the methods that you'll need to override and the methods that you'll merely
need to call.

Methods to Override

-(id)initWithFrame:(NSRect)frame isPreview:(BOOL)isPreview

This is ScreenSaverView's designated initializer.

- subclass initializers must call this method (see references for more information)

The template calls [super initWithFrame:isPreview:] and sets the animation rate.

The default time interval is 1/30.0, corresponding to 30 frames per second.

Zero polls as fast as possible while a negative number turns animation off.

-(BOOL)isAnimating

Check if your screen saver is currently between startAnimation and stopAnimation.

Useful for pausing calculations you don't want to perform while the screen saver is idle.

-(BOOL)isPreview

Call this method to see if you're being asked to draw the small preview.

Utility Functions in ScreenSaverView.h

SSRandomIntBetween

Generates a random integer in the closed interval [a,b].

I.E. the value returned will be one of a,a+1,a+2,...,b-1,b.

SSRandomFloatBetween

Generates a random floating point value in the closed interval [a,b]

SSRandomPointForSizeWithinRect

Picks a point within the rectangle, leaving gaps on the right and bottom edges.

SSCenteredRectInRect

Returns a rectangle the size of the first rectangle but centered within the second rectangle.

Debugging Tips

Whether you're having trouble getting the basic screen saver up and running or you've moved on to more
advanced topics and are having problems, there are a number of debugging options and tricks available to help.

1. One of the best ways to improve your ability to debug a screen saver is to add the Copy Files build
phase I mentioned above. Not having to copy newly built versions over after every change will drastically
speed up your build-run-debug cycle. With the new build automatically available, you can build your screen
saver and then immediately invoke it. You'll also want to disable the password protection option on your
screen saver so that you don't have to type in your password every time. In Panther, that setting has moved
to the Security pane in the System Preferences application.

2. Another good way to debug screen savers is to add a custom executable to your project that invokes the
ScreenSaverEngine with the proper -debug and -module arguments. The -debug flag tells the ScreenSaverEngine
to draw your screen saver behind all other windows rather than taking over the screen. This will allow you to
run or debug your screen saver from within Xcode while still having access to your source files for debugging
purposes. Note that unhandled events will still wake up your screen saver so you'll need to override the
mouse and keyboard event methods in NSResponder.h and not call the implementation in the superclass. To add a
custom executable, bring up your project window and select Custom Executable from the Project menu. In the
subsequent Assistant dialog, name the custom executable anything you like and then set the path to
/System/Library/Frameworks/ScreenSaver.framework/Versions/A/Resources/ScreenSaverEngine.app. This will add a
new entry in the Executables group in your project. See Figure 6 for a look at the custom executable
Assistant.

Figure 6. The Custom Executable Assistant window

Select that new entry and open its editor pane (or double click the entry to open the editor in a separate
window). Click twice on the small round "plus" button directly below the Arguments section of the editor to
add two new entries. Type in -debug for the first value and -module "projectName" (note that there is no
".saver" extension needed) for the second. This will tell the ScreenSaverEngine to run your module in debug
mode regardless of the screen saver selected in System Preferences. Figure 7 shows the arguments in the custom
executable editor. Build and run your project. Xcode should bring up the Run window and launch the
ScreenSaverEngine application which will load and run your screen saver behind all of the other windows.

Figure 7. The Custom Executable editor

While this setup does make debugging much easier, I've run into a few trouble spots while writing this
article that you should know about.

First, as with any code, if Xcode doesn't stop at your breakpoints make sure you're building and debugging
your screen saver using the Development build style. The alternative, Deployment, strips the debugging
symbols that the debugger needs to find its way around your code.

Second, your screen saver will be fighting Xcode for events and this can cause some confusion. When the
screen saver first starts up, it will have the event focus and receive keyboard events. However, if you click
in any of Xcode's windows, the screen saver will lose focus and keyboard events will start going to Xcode
instead. If you were debugging a normal application, you'd simply click in one of its windows to restore
keyboard focus to the application but screen savers aren't normal applications. The screen saver engine uses
mouse and keyboard events as a signal to disengage the screen saver so even moving the mouse out of the
debugger window into the screen saver window will cause the screen saver engine to shut down the screen saver
and exit. The way around this problem is to override a few more event handlers from NSResponder.h. At a
minimum, you'll need to override mouseDown:, mouseUp:, mouseEntered:, and mouseExited: to do nothing so that
you can move the mouse into the screen saver window and click to restore the keyboard focus without waking the
screen saver. Don't forget to leave yourself some way of stopping the screen saver short of force quitting
Xcode.

Third, even with the above code in place, you can run into areas where your screen saver state will get out
of sync with the keyboard state. In particular, if you have breakpoints set on event handling methods like
mouseDown:, keyDown:, or flagsChanged: you're going to have a bit of trouble because the Xcode debugger will
eat the corresponding "up" events when you hit those breakpoints. If your screen saver uses these events to
toggle state like I'll show later on in the event handling example, you will need to either toggle the state
variable in the debugger or disable the breakpoint, switch the keyboard focus back over to the screen saver
window, and give it another down/up pair so that it catches the up event and restores the proper state.

4. In order to debug truly complicated event handling code, you may need to resort to debugging the screen
saver remotely using gdb or just logging state and calling sequence information to stdout using NSLog or
printf.

5. Cocoa has a rule that messages to nil do nothing and return nil. While this does help keep broken code
limping along, it can make debugging particularly frustrating, especially when compounded by the fact that
Cocoa lends itself to long lines of code with no intermediate variables. To see what I mean, take a look at
this snippet of code from a section later in this article.

Although you'll often see code like the latter snippet, code written in this style can be very difficult to
understand and debug. For your own sanity and that of anybody who has to read your code, please try to err
on the side of the first snippet. It will make code much easier to read and debug, and the compiler should
optimize out any intermediate variables so there's no penalty for using them.

6. Once you've got your screen saver up and running and you're just fine-tuning your graphics algorithms,
you can build debugging help directly into the screen saver. Instead of relying on symbolic debugging in
Xcode or postmortem debugging via NSLog and the console.log file, add some code at the end of your drawRect:
method to display the current state of your screen saver. Use NSString and the drawing functions in
NSStringDrawing.h to draw status messages over the top of your animated content.

Summary

Now that we've worked through the creation of a simple screen saver, taken a closer look at the
ScreenSaverView class and its methods, and covered some debugging tips, this is probably a good place to stop
and take a break. In the next article, we'll look into some more interesting topics such as adding a simple
configuration sheet, saving and loading those configuration options using ScreenSaverDefaults, and basic event
handling. We'll also see how to use other drawing APIs within a screen saver.

David Hill is a freelance writer living in College Station, Texas. In a former life, he worked
in Apple's Developer Technical Support group helping developers print, draw, and write games. In his free time
he dabbles in screen savers and other esoteric topics.

Community Search:

MacTech Search:

Software Updates via MacUpdate

Bookends 12.5.8 - Reference management a...

Bookends is a full-featured bibliography/reference and information-management system for students and professionals.
Access the power of Bookends directly from Mellel, Nisus Writer Pro, or MS Word (... Read more

Chromium 44.0.2403.125 - Fast and stable...

Chromium is an open-source browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web.
Version 44.0.2403.125:
This release contains a number... Read more

iMazing 1.2.2 - Complete iOS device mana...

iMazing (was DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can:
Copy music to and from... Read more

Audio Hijack 3.2.0 - Record and enhance...

Audio Hijack (was Audio Hijack Pro) drastically changes the way you use audio on your computer, giving you the freedom to listen to audio when you want and how you want. Record and enhance any audio... Read more

FontExplorer X Pro 5.0.1 - Font manageme...

FontExplorer X Pro is optimized for professional use; it's the solution that gives you the power you need to manage all your fonts.
Now you can more easily manage, activate and organize your... Read more

Calcbot 1.0.2 - Intelligent calculator a...

Calcbot is an intelligent calculator and unit converter for the rest of us. Featuring an easy-to-read history tape, expression view, intuitive conversion, and much more!
Features
History Tape -... Read more

MTR 5.0.0.1 - The Mac's oldest and...

MTR (was MacTheRipper)--the Mac's oldest and smartest DVD-backup app--is now updated to version 5.001
MTR -- the complete toolbox, not a one-trick, point-and-click extractor. MTR is intended for... Read more

LibreOffice 4.4.5.2 - Free, open-source...

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

Adobe Lightroom 6.1.1 - Import, develop,...

Adobe Lightroom is available as part of Adobe Creative Cloud for as little as $9.99/month bundled with Photoshop CC as part of the photography package. Lightroom 6 is also available for purchase as a... Read more

File Juicer 4.41 - Extract images, video...

File Juicer is a drag-and-drop can opener and data archaeologist. Its specialty is to find and extract images, video, audio, or text from files which are hard to open in other ways.
It finds and... Read more

Bandai Namco has released Pac-Man Championship Edition DX on iOS and Android, which features the classic arcade gameplay that we've all grown to love.
Pac-Man Championship Edition DX can be enjoyed in much shorter bursts than the arcade versions... | Read more »

Angel Stone is Fincon's follow up to the massively successful Hello Hero and is out now on iOS and Android.
You play as a member of The Resistance, a group of mighty human warriors who have risen up in defiance of the Demon horde threatening to... | Read more »

The not exactly rumors were true and the birds are back. Angry Birds 2 has come to the App Store and the world will... well I suppose it'll still be the same, but now we have more bird-flinging options!
[Read more]
| Read more »

You Could Design Your Own Card for Chain...

If you've ever wanted to create your own item, weapon, trap, or even monster for Chainsaw Warrior: Lords of the Night, this is your chance. Auroch Digital is currently holding a contest so that fans can fight to the death (not really) to see which... | Read more »

Bitcoin Billionaire is Going Back in Tim...

If you thought you managed to buy everything there is to buy in Bitcoin Billionaire and make all the money, well you though wrong. Those of you who made it far enough might remember investing in time travel - and it looks like that investment is... | Read more »

Domino Drop (Games)

Domino Drop 1.0
Device: iOS Universal
Category: Games
Price: $1.99, Version: 1.0 (iTunes)
Description:
Domino Drop is a delightful new puzzle game with dominos and gravity!Learn how to play it in a minute, master it day by day.Your... | Read more »

Best Buy has iPad Air 2s on sale for up to $100 off MSRP on their online store for a limited time. Choose free shipping or free local store pickup (if available). Sale prices available for online... Read more

B&H Photo has the 13″ 1.6GHz/128GB MacBook Air on sale for $899.99 including free shipping plus NY tax only. Their price is $100 off MSRP, and it’s the lowest price available for this model.... Read more

Worldwide Tablet Market Decline Continues, Ap...

The worldwide tablet market declined -7.0% year-over-year in the second quarter of 2015 (2Q15) with shipments totaling 44.7 million units according to preliminary data from the International Data... Read more

The Apple Store has Apple Certified Refurbished iPad Air 2s available for up to $140 off the price of new models. Apple’s one-year warranty is included with each model, and shipping is free:
- 128GB... Read more

Updated Apple iPad Price Trackers

We’ve updated our iPad Air Price Tracker and our iPad mini Price Tracker with the latest information on prices and availability from Apple and other resellers.
Read more

Apple refurbished 2014 13-inch 128GB MacBook...

The Apple Store has Apple Certified Refurbished 2014 13″ MacBook Airs available starting at $759. An Apple one-year warranty is included with each MacBook, and shipping is free:
- 13″ 1.4GHz/128GB... Read more

Apple’s Education discount saves up to $300 o...

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

MacTech is a registered trademark of Xplain Corporation. Xplain, "The journal of Apple technology", Apple Expo, Explain It, MacDev, MacDev-1, THINK Reference, NetProfessional, Apple Expo, MacTech Central, MacTech Domains, MacNews, MacForge, and the MacTutorMan are trademarks or service marks of Xplain Corporation. Sprocket is a registered trademark of eSprocket Corporation. Other trademarks and copyrights appearing in this printing or software remain the property of their respective holders. Not responsible for typographical errors.

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.