System - Overview 06 - 02 PDF
System - Overview 06 - 02 PDF
System - Overview 06 - 02 PDF
System Overview
July 2002
Apple Computer, Inc. and TrueType are trademarks of THE WARRANTY AND REMEDIES SET
© 2000–2002 Apple Computer, Inc. Apple Computer, Inc., registered in FORTH ABOVE ARE EXCLUSIVE AND
All rights reserved. the United States and other countries. IN LIEU OF ALL OTHERS, ORAL OR
Carbon, Quartz, and Velocity Engine WRITTEN, EXPRESS OR IMPLIED. No
No part of this publication may be
are trademarks of Apple Computer, Apple dealer, agent, or employee is
reproduced, stored in a retrieval
Inc. authorized to make any modification,
system, or transmitted, in any form or
extension, or addition to this warranty.
by any means, mechanical, electronic, Enterprise Objects, Enterprise Objects
photocopying, recording, or Framework, NeXT, Objective-C, and Some states do not allow the exclusion or
otherwise, without prior written OpenStep are registered trademarks limitation of implied warranties or
permission of Apple Computer, Inc., of NeXT Software, Inc., registered in liability for incidental or consequential
with the following exceptions: Any the United States and other countries. damages, so the above limitation or
person is hereby authorized to store Java and all Java-based trademarks exclusion may not apply to you. This
documentation on a single computer are trademarks or registered warranty gives you specific legal rights,
for personal use only and to print trademarks of Sun Microsystems, and you may also have other rights which
copies of documentation for personal Inc., in the United States and other vary from state to state.
use provided that the documentation countries.
contains Apple’s copyright notice.
Netscape Navigator is a trademark of
The Apple logo is a trademark of Netscape Communications
Apple Computer, Inc. Corporation.
Use of the “keyboard” Apple logo
OpenGL is a registered trademark of
(Option-Shift-K) for commercial
Silicon Graphics, Inc.
purposes without the prior written
consent of Apple may constitute PostScript is a trademark of Adobe
trademark infringement and unfair Systems Incorporated.
competition in violation of federal PowerPC is a trademark of
and state laws. International Business Machines
No licenses, express or implied, are Corporation, used under license
granted with respect to any of the therefrom.
technology described in this book. Simultaneously published in the
Apple retains all intellectual property United States and Canada.
rights associated with the technology Even though Apple has reviewed this
described in this book. This book is manual, APPLE MAKES NO
intended to assist application WARRANTY OR REPRESENTATION,
developers to develop applications EITHER EXPRESS OR IMPLIED, WITH
only for Apple-labeled or RESPECT TO THIS MANUAL, ITS
Apple-licensed computers. QUALITY, ACCURACY,
Every effort has been made to ensure MERCHANTABILITY, OR FITNESS
that the information in this document FOR A PARTICULAR PURPOSE. AS A
is accurate. Apple is not responsible RESULT, THIS MANUAL IS SOLD “AS
for typographical errors. IS,” AND YOU, THE PURCHASER, ARE
ASSUMING THE ENTIRE RISK AS TO
Apple Computer, Inc.
ITS QUALITY AND ACCURACY.
1 Infinite Loop
Cupertino, CA 95014 IN NO EVENT WILL APPLE BE LIABLE
408-996-1010 FOR DIRECT, INDIRECT, SPECIAL,
Apple, the Apple logo, AirPort, INCIDENTAL, OR CONSEQUENTIAL
AppleScript, AppleShare, AppleTalk, DAMAGES RESULTING FROM ANY
Aqua, Cocoa, ColorSync,Finder, DEFECT OR INACCURACY IN THIS
FireWire, iBook, iMac, Mac, MANUAL, even if advised of the
Macintosh, Power Mac, QuickDraw, possibility of such damages.
QuickTime, PowerBook, Sherlock,
Contents
3
Apple Computer, Inc. July 2002
C O N T E N T S
4
Apple Computer, Inc. July 2002
C O N T E N T S
5
Apple Computer, Inc. July 2002
C O N T E N T S
6
Apple Computer, Inc. July 2002
C O N T E N T S
7
Apple Computer, Inc. July 2002
C O N T E N T S
8
Apple Computer, Inc. July 2002
C O N T E N T S
9
Apple Computer, Inc. July 2002
C O N T E N T S
10
Apple Computer, Inc. July 2002
C O N T E N T S
11
Apple Computer, Inc. July 2002
C O N T E N T S
Glossary 295
Index 309
12
Apple Computer, Inc. July 2002
Figures, Listings, and Tables
13
Apple Computer, Inc. July 2002
F I G U R E S , L I S T I N G S , A N D T A B L E S
14
Apple Computer, Inc. July 2002
F I G U R E S , L I S T I N G S , A N D T A B L E S
Listing 11-1 The Info.plist file for the Sketch demo application 202
Listing 11-2 The InfoPlist.strings file for the Sketch demo application 205
Table 11-1 Preference domains in search order 208
15
Apple Computer, Inc. July 2002
F I G U R E S , L I S T I N G S , A N D T A B L E S
16
Apple Computer, Inc. July 2002
C H A P T E R 1
Inside Mac OS X: System Overview is intended for anyone who wants to develop
software for Mac OS X. But it is also a resource for people who are just curious about
Mac OS X as a development and deployment platform. Whether your background
is software development for Mac OS 9, UNIX, Windows, Java, or any other
platform, you are likely to find something of value in this book.
This book describes the Mac OS X operating system from both a functional and
architectural perspective and explains some of the concepts, services, and
conventions common to the three primary development environments: Carbon,
Cocoa, and Java. The book attempts to be “API-agnostic,” avoiding as much as
possible details specific to a programming interface or application environment.
Further Investigations
This book serves as a starting point. It defines the broad conceptual terrain of
Mac OS X, and you must go elsewhere to learn about details mentioned or only
suggested by the “map.” For example, for information about creating a bundle, you
should see the documentation for Apple’s developer tools.
Further Investigations 19
Apple Computer, Inc. July 2002
C H A P T E R 1
You can access Apple’s developer documentation from Help Viewer and from
Project Builder. Both applications present the currently installed documentation in
a browser-like window for you to navigate. You navigate the documentation using
this window, clicking links to move from page to page. However, clicking the link
of an external URL opens that URL in your preferred Web browser.
To view documentation using Help Viewer, choose Mac Help from the Finder Help
menu and select the topic you want to view. The Developer Help Center is in the
Help Viewer drawer. This drawer contains the “books” that are currently installed.
You can search for topics in Help Viewer using the controls in the window toolbar.
The scope of a search in Help Viewer is determined by your current location within
the set of books. If you are browsing through a particular book—say, Core
Technologies—and you search for a term or API symbol, the Help Viewer first looks
at the Apple Help index for that book. If it cannot find the term or symbol, it
searches all books in the Developer Help Center.
You can also access the Developer Help Center directly from Project Builder. The
Help menu in Project Builder contains commands for viewing the Developer Help
Center top-level page or for viewing specific areas, such as Cocoa, Carbon, and the
Release Notes. Selecting one of these commands displays the corresponding help
within a Project Builder window.
To obtain your printed copy of an Inside Mac OS X book, use your Web browser to
access the page at http://www.vervante.com/apple. Then follow the directions.
20 Further Investigations
Apple Computer, Inc. July 2002
C H A P T E R 1
Information on BSD
Many developers who are new to Mac OS X are also new to BSD, an essential part
of the operating system’s kernel environment. BSD (for Berkeley Software
Distribution) is a variant of UNIX. Several excellent books on BSD and UNIX are
available in most technical bookstores (or bookstores with technical sections).
You can also use the World Wide Web as a resource for information on BSD. Several
organizations, which make available their own free versions of BSD, maintain
websites with manuals, FAQs, and other sources of information:
■ The Darwin project, http://developer.apple.com/darwin
■ The FreeBSD project, http://www.freebsd.org
■ The NetBSD project, http://www.netbsd.org
■ the OpenBSD project, http://www.openbsd.org
See the bibliography in Inside Mac OS X: Kernel Programming for more references.
Further Investigations 21
Apple Computer, Inc. July 2002
C H A P T E R 1
22 Further Investigations
Apple Computer, Inc. July 2002
C H A P T E R 2
2 System Technologies
But Mac OS X is more than a sophisticated core and a pretty face. With its multiple
application environments, virtually all Macintosh applications can run on it. And
with its support for many networking protocols and services, Mac OS X is the
ultimate platform for using and enjoying the Internet. It also offers a high degree of
interoperability with other operating systems because of its multiple volume
formats and its conformance with established and evolving standards.
23
Apple Computer, Inc. July 2002
C H A P T E R 2
System Technologies
Figure 2-1 depicts the general dependencies between these components. The rest of
this chapter describes what these and other technologies of Mac OS X have to offer.
Aqua
Application environments
Darwin
The user environment for Mac OS X is similar to that of earlier versions of the Mac
OS. But it is also different in important ways. There are differences in the design of
the user interface, in the infrastructure for localizing the interface, and in the way to
add application features. Mechanisms for exporting and accessing the services of
other applications have been enhanced.
And, of course, the user experience draws from the benefits obtained through the
core of the operating system (see “Darwin” (page 33)). A Macintosh computer
remains stable even when an application crashes, and no single application or task
can monopolize processing resources; applications can execute concurrently.
This section describes the experience that Mac OS X offers to users and the features
and applications that make the experience a productive and enjoyable one.
System Technologies
Aqua
When Apple designed Aqua, the graphical user interface for Mac OS X, it had one
goal in mind: to create a modern operating system that is not only easy to use, but
is more appealing than any Mac OS you’ve ever seen (see Figure 2-2 for a screen
shot). As “aqua” suggests, the properties of water infuse the lucid appearance of
Mac OS X. Aqua brings a computer to life with color, depth, clarity, translucence,
and motion. Buttons look like polished blue gems, active buttons pulse, windows
have drop shadows to give them depth, minimized windows swoop into their Dock
icon like a genie into its bottle.
System Technologies
One striking characteristic of Aqua is its icons. In earlier operating systems, icon
sizes were constrained by the limitations of screen resolution. With today’s
dramatically improved display sizes and resolution levels, Aqua sheds these
constraints. It offers richly colored and photo-quality icons that are adjustable up to
128-by-128 pixels. Its icons are more legible, enabling such features as in-place
document previews.
Aqua also improves the user’s experience by better management of screen real
estate. Operating systems are noted for cluttering up screens by spawning window
after window, especially when there are deeply structured file systems and multiple
control panels. Mac OS X eliminates the problem of proliferating windows by
focusing the activities of an application in a single window.
The Mac OS has long been admired for its ease of use. Aqua incorporates many of
the user-interface qualities and characteristics Macintosh users expect in their
computers. Ease of use is factored into just about every feature and capability in the
system.
Many of the effects of Aqua are made possible by Quartz, the 2D graphics and
windowing technology developed by Apple. See “Quartz” (page 38) for more on
this technology. For more information on the Aqua interface, see Inside Mac OS X:
Aqua Human Interface Guidelines.
The Finder
A big part of the Aqua experience for users is the design of the desktop and the
Finder, a system application that acts as the primary interface for file-system
interaction. Users are likely to notice two major innovations in this area: the Dock
and the way the Finder displays the elements of the file system.
System Technologies
The Dock reduces desktop clutter. This area of the screen holds just about anything
you want to keep handy for instant access: folders, applications, documents, storage
devices, minimized windows, QuickTime movies, links to websites. An icon
identifies each item stored in the Dock; these icons often provide useful feedback
about what they represent. For example, the icon for Mail tells you if you have any
new messages waiting to be read. If you store an image, the Dock shows it in
preview mode, so you can tell what it is without opening it. And because you can
minimize running applications into the Dock, a quick look at the bottom of the
screen tells you what applications you’re currently running. To switch between
tasks, simply click the application or document icon you want to start using, and it
becomes the new active task. If you don’t know what an icon represents, you can
move your mouse pointer over it and the title of the document, folder, or
application appears.
The Dock holds as many things as you want to keep there. As you add items, the
Dock expands until it reaches the edge of the screen. Once it reaches that point, the
icons in the Dock shrink proportionately to accommodate additional items. To
make the smaller icons more legible, however, Mac OS X includes a feature called
magnification: Just pass the cursor over the icons, and they magnify to your preset
level.
The Mac OS X Finder has a simple navigation interface that can be contained within
a single window. Intuitive controls in a configurable toolbar instantly transport you
to the most frequently accessed areas on your computer: your home directory, your
applications, your documents, even the people with whom you often communicate.
The items that the Finder displays are not only folders, applications, and
documents, but other commonly accessed items such as mounted network
volumes, external storage devices, CD-ROMs, and digital cameras.
In addition to the icon and list views, Macintosh users are familiar with, each Finder
window can be set to the viewing mode called column view. This mode is ideal for
navigating deep file systems; clicking a folder displays the contents of that folder in
the next column to the right. Column view also maintains a history of your
navigation forays so you can always find your way back.
When you double-click Finder items in icon or list view, the Finder by default does
not bring up a separate window. Instead, the Finder replaces the old folder view
within the single Finder window. (You can change this default behavior, however.)
By focusing the file system into a single window view, the Finder reduces the
proliferation of windows, a key design goal. Despite this default behavior, nothing
prevents you from opening as many Finder windows as you wish.
System Technologies
In Mac OS 9, the Finder identified files using the file type and creator codes stored
in the file. The Finder in Mac OS X is capable of recognizing files by their filename
extension as well as by their type and creator codes. Since many Mac OS 9 users are
used to files without file extensions, the Finder offers a way to hide those extensions
globally through the Finder preferences and on a per-file basis through the Show
Info window. For more information about files and filename extensions, see “How
the File System Is Organized” (page 165).
Application Support
Part of the Mac OS X user experience is the seamless interaction among different
components of the operating system. From BSD to QuickTime, Mac OS X consists
of technologies with widely different histories and based on different standards and
conventions. A single Mac OS X system hosts volumes of different formats,
supports different network file-sharing protocols, and can run applications based
on radically different APIs.
Mac OS X provides an easy transition for users and developers. To this end,
Mac OS X supports four application environments, each intended for a particular
type of application:
■ The Classic environment can run most Mac OS 9 applications. Because Classic is
a compatibility environment, it does not support some Mac OS X features, such
as Aqua or core architectural enhancements provided by Darwin.
■ The Carbon environment runs all Mac OS 9 applications whose code has been
optimized for Mac OS X. By converting their code to use the Carbon APIs,
application developers can ensure that applications take advantage of protected
memory, preemptive multitasking, and other features of Darwin.
■ The Cocoa environment offers an advanced object-oriented framework for
creating the best next-generation applications.
■ The Java environment runs 100% Pure Java and mixed-API Java applications
and applets.
Mac OS X makes it possible to copy (or cut) almost any piece of data and paste it
into an application executing in another environment. It also enables dragging of
Finder objects (and the data they represent) between most environments. Mac OS X
performs all necessary conversions when, for example, a file stored on a Mac OS
Extended (HFS+) volume is copied to a UFS volume.
System Technologies
Multiple Users
Users work on a Mac OS X system in a personally customized environment. They
can select a desktop pattern, their preferred language, the applications to start up at
boot-time, and a number of other preferences. Whenever they log in to their
account, all of their choices are restored.
More powerful than this single (local) machine/multiple users model is the
multiple machines/multiple users model—in other words, network accounts,
which Mac OS X makes possible through its NetInfo network management system.
People can use any Mac OS X system connected to their NetInfo network—which
can be a home computer, a portable computer, or a system in a friend’s house—to
log in to their account on a remote server. When logged in, they can work in an
environment that is exactly like it was when they last logged out, regardless of
which machine they last used to log in. And if a site is properly administered, their
information on that server is just as secure as any locally maintained data, perhaps
more secure if files on the server are backed up regularly.
System Technologies
Internationalization
Mac OS X makes it easy to internationalize software. And it does so in such a way
that a single binary can support localizations for multiple languages and regional
dialects. It also lets software developers dynamically add localized resources for
new languages or regions.
Localized resources such as image and strings files, as well as Mac OS 9–style
resources (.rsrc), can be put in bundle subdirectories whose names reflect a
particular language or regional dialect (for example, Canadian French). A properly
constructed Mac OS X application (or plug-in or shared library) does not hardwire
paths to the resource files in these directories. Instead, when the application needs
a resource, it uses a special system routine to obtain the localization that best
matches the user’s language preferences.
Accessibility
Millions of people have some type of disability or special need. Federal regulations
in the United States stipulate that computers used in government or educational
settings must provide reasonable access for people with disabilities. Mac OS X
includes built-in functionality designed to accommodate users with special needs.
It also provides software developers with the functions they need to support
accessibility in their own applications.
System Technologies
In addition to its built-in support, software developers can use Carbon and Cocoa
APIs to communicate accessibility information to other applications. Cocoa controls
implement the NSAccessibility protocol, which communicates accessibility
information to the system. In Carbon there are functions that provide similar
support.
For details, see Inside Mac OS X: Making Your Application Accessible to Users With
Disabilities.
AppleScript
Scripting in Mac OS X, as in Mac OS 9, employs AppleScript as the primary
scripting language and Apple events as the communication model. You can
program behavior into your applications so they act appropriately upon receiving
AppleScript commands. AppleScript is supported in all application environments
as well as in the Classic compatibility environment. Users can thus write scripts that
link together the services of multiple applications in different environments.
System Technologies
Applications do not have to know what services are offered in advance. A user
selects a piece of data in an application, such as a string of text, or an image, or an
icon representing a folder or file. Then user then selects a command from an
application listed in the Services menu and the command is executed on the
selection, invoking that second application.
The Services facility often works as though the user copies data from one
application, pastes it into another, modifies the data, then copies the result and
pastes it back into the original application. For example, a user might select a folder
in the Finder and choose a Services option that compresses the folder and puts it
into an archive format; the result of this operation is placed back in the same place
as the original folder. But the action can be one way as well; for instance, a user
might select a name in a word-processing document and choose a Services
command that looks up the name using an LDAP server, starts up an email
application, and opens a new message window with the found email address after
the To: line.
Mac OS X integrates the Internet into everyday computer use. It makes it easy for
users to access the Internet and to save the locations of favorite websites for later
access. It features Sherlock for searching the Internet or an intranet as well as for
System Technologies
searching the local file system (including searching by indexed content). Mac OS X
also includes a powerful, yet incredibly easy-to-use, email application based
completely on Internet standards.
Darwin
For more information about Darwin, see the books Inside Mac OS X: Kernel
Programming and Inside Mac OS X: I/O Kit Fundamentals. These books are available
on the Apple website: http://developer.apple.com/techpubs/macosx/Darwin.
Mach
Mach is at the heart of Darwin because it performs a number of the most critical
functions of an operating system. Much of what Mach provides is transparent to
applications. It manages processor resources such as CPU usage and memory,
handles scheduling, enforces memory protection, and implements a
messaging-centered infrastructure for untyped interprocess communication, both
local and remote. Mach brings many important advantages to Macintosh
computing:
■ Protected memory. The stability of an operating system should not depend on
all executing applications being good “citizens” by not writing data to each
others’s (or the system’s) address space; doing so can result in loss or corruption
of information and can even precipitate system crashes. Mach ensures that an
application cannot write on another application’s memory or on the operating
system’s memory. By walling off applications from each other and from system
processes, Mach makes it virtually impossible for a single poorly behaved
Darwin 33
Apple Computer, Inc. July 2002
C H A P T E R 2
System Technologies
application to hurt the rest of the system. And, perhaps best of all, if an
application crashes, it doesn’t affect the rest of the system and so you don’t need
to restart your computer.
■ Preemptive multitasking. In a modern operating system, processes share the
CPU efficiently. Mach watches over the computer’s processor, prioritizing tasks,
making sure activity levels are at the maximum, and ensuring that every task
gets the resources it needs. It uses certain criteria to decide how important a task
is, and therefore how much time to allocate to it before giving another task its
turn. Your process is not dependent on another process yielding its processing
time.
■ Advanced virtual memory. Like other virtual memory systems, Mach maintains
address maps that control the translation of a task’s virtual addresses into
physical memory. Typically only a portion of the data or code contained in a
task’s virtual address space is resident in physical memory at any given time. As
pages are needed, they are loaded into physical memory from storage. Mach
augments these semantics with the abstraction of memory objects. Named
memory objects enable one task (at a sufficiently low level) to map a range of
memory, unmap it, and send it to another task. This capability is essential for
implementing separate execution environments on the same system. In
Mac OS X, virtual memory is “on” all the time.
■ Real-time support. This feature guarantees low-latency access to processor
resources for time-sensitive media applications.
BSD
Integrated with Mach is a customized version of the BSD operating system
(currently 4.4BSD). Darwin’s implementation of BSD includes much of the POSIX
API and exports it to the application layers of the system. BSD serves as the basis for
the file systems and networking facilities of Mac OS X. In addition, it provides
several programming interfaces and services, including
■ the process model (process IDs, signals, and so on)
■ basic security policies such as user IDs and permissions
■ threading support (POSIX threads)
■ BSD sockets
34 Darwin
Apple Computer, Inc. July 2002
C H A P T E R 2
System Technologies
Device-Driver Support
For development of device drivers, Darwin offers an object-oriented framework
called the I/O Kit. The I/O Kit not only facilitates the creation of drivers for
Mac OS X, but provides much of the infrastructure those drivers need. It is written
in a restricted subset of C++. The framework, which is designed to support a range
of device families, is both modular and extensible.
Device drivers created with the I/O Kit easily acquire several important features:
■ true plug and play
■ dynamic device management (“hot plugging”)
■ power management (both desktops and portables)
For information on creating device drivers, see Inside Mac OS X: I/O Kit
Fundamentals. For descriptions of the device drivers developed by Apple, see
“Advanced Hardware Features” (page 50).
Networking Extensions
Darwin gives kernel developers a new technology for adding networking
capabilities to the operating system, Network Kernel Extensions (NKEs). The NKE
facility allows you to create networking modules and even entire protocol stacks
that can be dynamically loaded into the kernel and unloaded from it. NKEs also
make it possible to configure protocol stacks automatically.
NKE modules have built-in capabilities for monitoring and modifying network
traffic. At the data-link and network layers, they can also receive notifications of
asynchronous events from device drivers, such as when there is a change in the
status of a network interface.
For detailed information on developing networking extensions with NKE, see Inside
Mac OS X: Network Kernel Extensions. For descriptions of the networking services
and protocols natively implemented in Darwin, see “Networking and the Internet”
(page 46).
Darwin 35
Apple Computer, Inc. July 2002
C H A P T E R 2
System Technologies
File Systems
The file-system component of Darwin is based on extensions to BSD and an
enhanced Virtual File System (VFS) design. VFS enables a layered architecture in
which file systems are stackable. The file-system component introduces several new
general features:
■ Permissions on removable media. This feature is based on a globally unique ID
registered in a system for each connected removable device (including USB and
FireWire devices).
■ URL-based volume mount, which enables users (via a Finder command) to
mount such things as AppleShare and Web servers.
■ Unified buffer cache, which consolidates the buffer cache with the
virtual-memory cache.
■ Long filenames (255 characters or 755 bytes, based on UTF-8).
■ Support for hiding filename extensions on a per-file basis.
Because of its multiple application environments and the various kinds of devices
it supports, Mac OS X must be able to handle file data on many standard volume
formats. Table 2-1 lists the supported formats.
Mac OS Also called Hierarchical File System Plus, or HFS+. This is the default
Extended root and booting volume format in Mac OS X. This extended version
Format of HFS optimizes the storage capacity of large hard disks by
decreasing the minimum size of a single file. It is also the standard
volume format for Mac OS 9.
Mac OS Also called Hierarchical File System, or HFS. This is the volume
Standard format in Mac OS systems prior to Mac OS 8.1. HFS (as does HFS+)
Format stores resources and data in separate “forks” of a file and makes use of
various file attributes, including type and creator codes.
36 Darwin
Apple Computer, Inc. July 2002
C H A P T E R 2
System Technologies
UFS A “flat” (that is, single-fork) disk volume format, based on the 4.4BSD
FFS (Fast File System) that is similar to the standard volume format of
most UNIX operating systems; it supports POSIX file-system
semantics, which are important for many server applications.
UDF The Universal Disk Format for DVD volumes.
ISO 9660 The standard format for CD-ROM volumes.
HFS and HFS+ volumes support aliases and UFS volumes support symbolic links
(HFS+ and UFS both support hard links). Although an alias and a symbolic link are
both lightweight references to a file or directory elsewhere in the file system—they
are semantically different in significant ways. See the chapter “The File System”
(page 165) for descriptions of these and other differences.
AFP client Apple File Protocol, the principal file-sharing protocol in Mac OS 9
systems (available only over TCP/IP transport).
NFS client Network File System, the dominant file-sharing protocol in the UNIX
world.
WebDAV Web-based Distributed Authoring and Versioning, an HTTP extension
that allows collaborative file management on the web.
Samba SMB/CIFS, a file-sharing protocol used on Windows and UNIX
systems.
Darwin 37
Apple Computer, Inc. July 2002
C H A P T E R 2
System Technologies
Quartz
Quartz is a powerful graphics system that delivers a rich imaging model, on-the-fly
rendering, anti-aliasing, and compositing of PostScript graphics. Quartz also
implements the windowing system for Mac OS X and provides low-level services
such as event handling and cursor management. It also offers facilities for rendering
and printing that use PDF as an internal model for graphics representation.
System Technologies
Table 2-3 describes some of Quartz’s rendering capabilities and other features.
Bit depth A minimum bit depth of 16 bits for typical users. An 8-bit
depth in full-screen mode is available for games and other
multimedia applications.
Minimum Supports 800 pixels by 600 pixels as the minimum screen
resolution resolution for typical users. A resolution of 640 x 480 is
available for the iBook as well as games and other multimedia
applications.
Anti-aliasing All graphics and text are anti-aliased.
Frame buffer Includes a mechanism that lets graphics applications (such as
access games) gain direct access to the video frame buffer.
Velocity Engine Quartz and QuickDraw both take advantage of the Velocity
Engine to boost performance.
Quartz Extreme Quartz Extreme leverages OpenGL for the entire Mac OS X
desktop. Graphics calls now render in supported video
hardware, freeing up the CPU for other tasks.
2D graphics Supports two-dimensional graphics acceleration, improving
acceleration what is currently available in QuickDraw. (Acceleration is
currently limited to system software and Classic applications;
other applications must draw into backing store in DRAM.)
ColorSync color Quartz uses ColorSync to manage pixel data when drawing
management data on the screen, respecting ICC profiles, or applying the
system’s monitor profile as source color space. ColorSync can
also be called when printing occurs.
Quartz has two components, Quartz Compositor and Quartz 2D. The first of these,
Quartz Compositor, is essentially the window server for the system. The window
server provides the fundamental windowing and event-routing services for all
application environments. This high-performance server is lightweight in that it
performs no rendering itself, yet it provides essential services to all graphics
rendering libraries that are clients of it, including Quartz 2D and QuickDraw.
Quartz Compositor features such advanced capabilities as device-independent
System Technologies
color and pixel depth, layered compositing, and buffered windows for the
automatic repair of window damage. Quartz Compositor also includes transparent
support for accelerated graphics hardware using Quartz Extreme.
See “The Graphics and Windowing Environment” (page 67) in the chapter “System
Architecture” for more information on Quartz.
QuickDraw
Carbon developers should use the Quartz API whenever possible to render content.
However, QuickDraw is also available as a legacy technology for the construction,
manipulation, and display of two-dimensional graphical shapes, pictures, and text.
System Technologies
OpenGL
Mac OS X includes Apple’s highly optimized implementation of OpenGL as the
system API and library for three-dimensional (3D) graphics. OpenGL is an
industry-wide standard for developing portable 3D graphics applications. OpenGL
is one of the most widely adopted graphics API standards today, which makes code
written to OpenGL portable and the generated visual effects very consistent. It is
specifically designed for games, animation, CAD/CAM, medical imaging, and
other applications that need a rich, robust framework for visualizing shapes in two
and three dimensions. The Mac OS X version of OpenGL produces consistently
high-quality graphical images at a consistently high level of performance.
OpenGL offers a broad and powerful set of imaging functions, including texture
mapping, hidden surface removal, alpha blending (transparency), anti-aliasing,
pixel operations, viewing and modeling transformations, atmospheric effects (fog,
smoke, and haze), and other special effects. Each OpenGL command directs a
drawing action or causes special effects, and developers can create lists of these
commands for repetitive effects. Although OpenGL is largely independent of the
windowing characteristics of each operating system, special “glue” routines are
implemented to enable OpenGL to work in an operating system’s windowing
environment.
QuickTime
Mac OS X comes packaged with the latest version of QuickTime. QuickTime is a
powerful multimedia technology for manipulating, enhancing, and storing video,
sound, animation, graphics, text, music, and even 360-degree virtual reality. It also
allows you to stream digital video where the data stream can be either live or stored.
QuickTime is cross-platform technology; besides Mac OS X, it is available in Mac OS
9, Windows 95, Windows 98, Windows NT, and Windows 2000.
QuickTime supports every major file format for images, including PICT, BMP, GIF,
JPEG, TIFF, and PNG. It also supports every significant professional file format for
video, including AVI, AVR, DV, M-JPEG, MPEG-1, MPEG-2, MPEG-4, AAC, and
OpenDML. For Web streaming, it includes support for HTTP as well as RTP and
RTSP.
System Technologies
QuickTime streaming allows users to view live and video-on-demand movies using
the industry-standard protocols RTP (Real-Time Transport Protocol) and RTSP
(Real-Time Streaming Protocol). Users can view streaming live broadcasts,
previously recorded movies, or a mixture of both. Broadcasts can be either unicast
(one-to-one) or multicast (one-to-many).
Printing
The printing system for Mac OS X is based on an architecture completely different
from that of earlier versions of the Mac OS. It is a service available for all application
environments. Drawing upon the capabilities of Quartz, the printing system
delivers a consistent human interface and makes possible shorter development
cycles for printer vendors. It allows applications to draw in “virtual pages” and map
those pages to physical pages at print time, breaking the connection between the
drawing page and the printing page. The printing system also provides
applications with a high degree of control over the user-interface elements in
printing dialogs. Table 2-4 describes some additional features.
System Technologies
For more information on the printing features in Mac OS X, see “The Printing
System” (page 72).
Application Technologies
Application Technologies 43
Apple Computer, Inc. July 2002
C H A P T E R 2
System Technologies
Application Extensibility
Plug-ins are modules of code and resources that developers and users can
dynamically add to an application to extend its capabilities. The host application
structures its code so that well-defined areas of functionality can be provided by
external plug-ins. The host does not have to be aware of the implementation details
of the plug-in. When the application is launched, it uses mechanisms provided by
the plug-in architecture to locate its plug-ins and load them. An application can let
users add plug-ins at any time while it is running, and it can also give users the
means for removing its plug-ins.
Plug-ins offer a range of benefits for both users and developers. Users can customize
the features of an application to suit their requirements, and as new or upgraded
functionality (as encapsulated by a new or replacement plug-in) becomes available,
users can “plug” these features into the application.
Important
Developers should always be careful when deciding how to
factor their application to support plug-ins. Despite the
benefits of plug-ins, loading a large number of plug-ins can
incur noticeable performance penalties. If an application
relies too heavily on plug-ins, its appearance may seem
sluggish to the user.
For details, see the conceptual and reference documentation for Core Foundation
Bundle Services and Plug-in Services.
44 Application Technologies
Apple Computer, Inc. July 2002
C H A P T E R 2
System Technologies
Disc Recording
Mac OS X 10.2 introduces a new framework that gives applications the ability to
burn and erase CDs and DVDs. The Disc Recording framework was built to satisfy
the simple needs of a general application, making it easy to add basic audio and
data burning capabilities to any application. At the same time, the framework is
flexible enough to support professional CD and DVD mastering applications.
The Disc Recording framework supports applications built using Carbon and
Cocoa. The Disc Recording UI framework currently provides user interface
elements for Cocoa applications only.
Contact Database
Mac OS X 10.2 introduces a centralized database for sharing information about
contacts and groups. The database contains information such as user names, street
addresses, email addresses, phone numbers, and distribution lists. Applications can
use this data as is or extend it to include application-specific information.
The Address Book framework provides a way to access user records and create new
ones. Applications that support this framework gain the ability to share contact
information with other applications. The API also provides the concept of a “Me”
record for the current user. This record contains information about the currently
logged in user and can be used by programs such as Web browsers to automatically
fill in Web forms with appropriate data.
Application Technologies 45
Apple Computer, Inc. July 2002
C H A P T E R 2
System Technologies
The Mac OS X network protocol stack is based on BSD. The extensible architecture
provided by Network Kernel Extensions, summarized in “Networking Extensions”
(page 35), facilitates the creation of modules implementing new or existing
protocols that can be added to this stack.
Media Types
Mac OS X supports the network media types listed in Table 2-5.
Ethernet For the Ethernet ports built into every new Macintosh.
10/100Base-T
Ethernet Also known as Gigabit Ethernet. For data transmission over
1000Base-T fiber-optic cable and standardized copper wiring.
Jumbo Frame This Ethernet format is a technology that uses 9 KB frames for
interserver links rather than the standard 1.5 KB frame. Jumbo
Frame decreases network overhead and increases the flow of
server-to-server and server-to-application data.
Serial Supports modem, DSL, and ISDN capabilities.
Wireless See “AirPort” (page 51).
System Technologies
Standard Protocols
Mac OS X supports a number of protocols that are standard in the computing
industry. Table 2-6 summarizes these protocols.
System Technologies
Apple also implements a number of file-sharing protocols; see Table 2-2 (page 37)
for a summary of these protocols.
Existing applications can continue to use these technologies. However, if you are
developing new applications, you should use the new networking technologies
provided by Cocoa and Carbon.
System Technologies
Rendezvous
Mac OS X 10.2 and later include support for Rendezvous, Apple’s implementation
of zero-configuration networking. Rendezvous makes the dynamic discovery of file
servers and printers much simpler and truly more plug-and-play. Using
Rendezvous, computers can create ad-hoc networks over Ethernet or Airport
connections.
System Technologies
Right out of the box, Mac OS X supplies drivers for most standards-based hard
drives and add-on devices in common use today. For example, it provides support
and drivers for IDE and SCSI disk drives and supports a wide range of Apple
monitors. Mac OS X also includes features such as power management for both
desktop and portable systems.
The rest of this section discusses some of the advanced hardware features of
Mac OS X. For hardware-related information in this book, see “Media Types”
(page 46), “File Systems” (page 36), and “Networking Extensions” (page 35). For
detailed information on hardware support, see the installation guide that comes
with Mac OS X.
USB
USB (Universal Serial Bus) is a high-speed plug-and-play interface between a
computer and add-on devices such as audio players, joysticks, keyboards,
telephones, scanners, and printers. It supports a data speed of 12 megabits per
second. USB permits users to add a new device to their computer without having to
add an adapter card or even having to turn the computer off. Mac OS X includes
USB drivers for the following classes of devices:
■ input devices (HID class)
■ printers
■ modems and other communication devices
■ mass storage (Zip and Jaz drives, for instance, and external hard drives)
■ imaging
■ display
■ audio
System Technologies
FireWire
FireWire is Apple’s implementation of the IEEE 1394 standard (High Performance
Serial Bus) for peripheral devices. It enables a single plug-and-socket serial
connection on which up to 63 devices can be attached. Because it supports a data
transfer rate up to 400 megabits per second, FireWire is ideal for devices such as
digital cameras, DVDs, digital video tapes, digital camcorders, and music
synthesizers. With FireWire, users can chain devices together in different ways
without the need for terminators or complicated set-up requirements. And devices
can be plugged in and used without the need for a system restart. Because IEEE 1394
is a peer-to-peer interface, you can connect one FireWire-capable device to another
and use both without connecting either to a computer; for example, one camcorder
can dub to another.
Velocity Engine
Support for the Velocity Engine is another important feature of Mac OS X. The
Velocity Engine boosts the performance of any application exploiting data
parallelism, such as those performing 3D graphic imaging, image processing, video
processing, audio compression, and software-based cell telephony. Quartz,
QuickTime, and QuickDraw now incorporate Velocity Engine capabilities; thus any
application using these APIs can tap into the Velocity Engine without making any
changes. The Mac OS X SDK includes a C/C++ compiler with Velocity Engine
support so you can also create new applications that take full advantage of the
Velocity Engine.
AirPort
AirPort is Apple’s wireless network technology that delivers fast and reliable
communications between multiple computers in a local area network and between
that network and the Internet. With AirPort, several users can be online at the same
time—simultaneously surfing the Web, accessing email, competing in games, and
swapping files—all through a single Internet service account. AirPort also lets you
wirelessly transfer files from your computer to another AirPort-equipped iBook,
iMac, PowerBook, or Power Mac G4 from up to 150 feet away.
System Technologies
The wireless data rate for AirPort is 11 megabits per second for up to 10
simultaneous users per base station. Because it is based on the IEEE 802.11 Direct
Sequence Spread Spectrum (DSSS) worldwide industry standard, AirPort permits
interoperability with other 802.11-based equipment. And because AirPort uses
radio signals, it can communicate through solid objects.
Video Features
The Quartz Compositor in Mac OS X includes a hardware acceleration layer called
Quartz Extreme. This transparent layer supports the rendering of video, 2D, and 3D
graphics using OpenGL-based video hardware. Support for this acceleration is
automatic and does not require any special coding.
Mac OS X also supports the ability to “hot-swap” monitors, that is, to change
monitors without shutting down the host computer first. This feature provides
users with more flexibility in setting up and using their computer. However,
applications that rely on the current video settings need to be aware that those
settings can now change at runtime. The Core Graphics framework
(CoreGraphics.framework) defines an API that allow applications to register for
notifications when the video settings change.
For more information on graphics and rendering, see “The Graphics and
Windowing Environment” (page 67).
3 System Architecture
A key consideration in the design of Mac OS X was the need to integrate a diverse
collection of technologies—some with greatly different histories—and base this
unified set of technologies on an advanced kernel environment. This chapter
explores the general outlines of the architecture that made this possible.
53
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
For further information, see the section “A Layered Perspective” (page 54) and
the book Inside Mac OS X: Kernel Programming.
The Core Services and Application Services layers and the Carbon and Cocoa
application environments are packaged in umbrella frameworks (described in the
chapter “Umbrella Frameworks” (page 155)). Many public APIs of the kernel
environment are exported through headers found in /usr/include.
The first part of this chapter, as summarized in the foregoing paragraphs, presents
the architecture of Mac OS X as layers of system software. Following this static
perspective of Mac OS X is a more dynamic view that traces the progress of a user
event through the system. A typical event in Mac OS X originates when the user
manipulates an input device such as a mouse or a keyboard. The device driver
associated with that device, through the I/O Kit, creates a low-level event, puts it in
the window server’s event queue, and notifies the window server. The window
server dispatches the event to the appropriate run-loop port of the target process.
There the event is picked up by the Carbon Event Manager and forwarded to the
event-handling mechanism appropriate to the application environment. Events can
also be asynchronous, such as a network packet containing configuration changes.
A Layered Perspective
A common way to look at complex software is to separate out parts of that software
into “layers.” Visually depicted, one layer sits on top of another, with the most
fundamental layer on the bottom. This kind of diagram suggests the general
interfaces and dependencies between the layers of software. The higher layers of
software, which are the closest to actual application code, depend on the layer
immediately under them, and that intermediate layer depends on an even lower
layer.
54 A Layered Perspective
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
Application Java
Classic Carbon Cocoa BSD
BSD
environment (JDK)
Core Services
Kernel environment
Although this diagram does help clarify the overall architecture, there are dangers
in the necessarily over-simplified view it presents. The Mac OS X services and
subsystems that one application uses—and how it uses them—can be very different
from those used by another application, even one of a similar type. Dependencies
and interfaces at the different levels can vary from program to program depending
on individual requirements and realities.
With that caveat aside, let’s take a guided tour through the layers depicted in this
diagram.
The boxes in the top row of the diagram of Figure 3-1 represent the different
application (or execution) environments of Mac OS X. There are five such
environments. The Classic and the BSD Commands environments are unique in the
way they interact with the underlying layers of the system:
■ The Classic “compatibility” environment is where users can run their Mac OS 8
or Mac OS 9 applications. Instead of sitting on top of the Application Services,
the Classic environment in this diagram has lines connecting it to each layer.
These connections indicate that the Classic environment is “hard-wired” into
Mac OS X; it is not an environment for which developers can specifically
compile code in Mac OS X. In other words, there are no public non-Carbon Mac
OS 8 or Mac OS 9 APIs on a Mac OS X system that can be compiled. For further
A Layered Perspective 55
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
The kernel environment exports BSD services to the upper layers of the system
through the System library in /usr/lib (the headers are located in /usr/include).
BSD commands are also available to developers; however, BSD commands
might not be included in certain Mac OS X installations. Because the BSD
Commands environment is a special optional environment, it is not described
further in this document.
Carbon, Cocoa, and Java are the three principal application environments for
Mac OS X developers:
■ Carbon is an adaptation of the Mac OS 9 APIs and libraries for Mac OS X. It
carries over most of the prior APIs (70 percent of the functions) and includes
some APIs and services specifically developed for Mac OS X. See “Carbon”
(page 60) for a discussion of Carbon.
■ Cocoa is a collection of advanced object-oriented APIs for developing
applications written in Java and Objective-C. See “Cocoa” (page 63) for more
information on Cocoa.
■ The Java environment is for the development and deployment of 100% Pure Java
and mixed-API Java applications and applets. See “Java” (page 64) for an
overview of this application environment.
Directly supporting the Carbon, Cocoa, and Java environments are the layers of
system software that offer services for all application environments. These layers
are stacked in decreasing widths to suggest that application code can access lower
layers directly—that is, without the mediation of intervening layers. (However, see
the warning about linking outside of umbrella frameworks in “Restrictions on
Subframework Linking” (page 162) in the chapter ““Umbrella Frameworks”
(page 155).”)
56 A Layered Perspective
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
The first of these layers is the Application Services layer. It contains the graphics
and windowing environment of Mac OS X, principally implemented by Quartz and
QuickDraw. This environment is responsible for screen rendering, printing, event
handling, and low-level window and cursor management. It also holds libraries,
frameworks, and background servers useful in the implementation of graphical
user interfaces. See “The Graphics and Windowing Environment” (page 67) and
“Other Application Services” (page 77) for details.
The Application Services layer sits on top of Core Services. In the Core Services
layer are the common services that are not directly a part of a graphical user
interface. Here you find cross-environment implementations of basic programmatic
abstractions such as strings, run loops, and collections. There are also APIs in Core
Services for managing processes, threads, resources, and virtual memory, and for
interacting with the file system. “Core Services” (page 79) discusses this layer of
system software.
The kernel environment is the lowest stratum of system software, just below the
Core Services layer. The kernel environment provides essential operating-system
functionality to the layers above it, such as
■ preemptive multitasking
■ advanced virtual memory with memory protection and dynamic memory
allocation
■ symmetric multiprocessing
■ multi-user access
■ file systems based on VFS (Virtual File System)
■ device drivers
■ networking
■ basic threading packages
A Layered Perspective 57
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
58 A Layered Perspective
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
the file system on an HFS+ volume as the one to mount first). By using the
Virtual File System (VFS) infrastructure, developers can write kernel extensions
that add support for other file systems and extend file system functionality—
adding file-level compression, for instance. VFS is a set of standard internal
file-system interfaces and utilities for building such extensions. For summaries
of the supported formats, see “File Systems” (page 36) in the chapter ““System
Technologies” (page 23).”
As described in “Darwin and Open Source Development” (page 38) in the chapter
““System Technologies” (page 23),” the kernel environment is a subset of Darwin,
Apple’s Open Source technology. Darwin combines the Mac OS X kernel
environment and the BSD commands and libraries essential to the BSD Commands
environment. For more on the Mac OS X kernel environment and its relation to
Darwin, see the document Inside Mac OS X: Kernel Programming.
Application Environments
Application Environments 59
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
Carbon
Carbon is a set of programming interfaces derived from earlier Mac OS APIs that
have been modified to work with Mac OS X, especially its kernel environment.
Carbon carries forward most of the existing Mac OS managers and APIs;
specifically, this entails about 70 percent of the total functions and 95 percent of
functions used by typical applications.
The Carbon APIs are too large and complex to summarize adequately here.
However, some of the major differences between Carbon and its Mac OS
predecessors are worth noting.
60 Application Environments
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
Required Replacement Managers. The Carbon technologies listed in Table 3-1 now
take the place of their predecessors. Use of the new libraries is required.
Application Environments 61
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
General Changes. Many functions in the various managers have been changed or
removed throughout Carbon. (See the Carbon Specification for complete details.)
■ Data structures. To ensure the integrity of system data and to support access to
all system services through preemptive threads, Carbon restricts direct access to
data structures. Instead of functions that return pointers or handles to structures
that can be dereferenced, Carbon now supplies accessor functions for getting
and setting field data. In addition, it includes functions for creating and
disposing of data structures.
■ Definition procedures. The Window Manager, Menu Manager, Control
Manager, and List Manager in Carbon still permit you to create and use
standard and custom definition procedures (WDEFs, MDEFs, CDEFs, and
LDEFs), but you must be sure to compile them as PowerPC code. Additionally,
these managers provide new routines for creating and packaging them.
■ 68K code. Mac OS X does not support 68K code (except in the Classic
environment). For this reason the Trap Manager (and the trap table), the Mixed
Mode Manager, and the Patch Manager are unavailable or greatly reduced in
scope in Carbon. For the same reason, many other functions have been dropped
from Carbon.
Many of the commonly used parts of Mac OS X are Carbon managers or are
daemons, applications, or frameworks created with Carbon APIs. For example, the
system processes that handle events and manage application processes in Mac OS
X are Carbon managers, many of the managers in the Core Services layer are
Carbon-based (see “Core Services” (page 79)), and the Finder is a Carbon
application.
62 Application Environments
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
Cocoa
The Cocoa application environment is based on two object-oriented frameworks:
Foundation (Foundation.framework) and the Application Kit (AppKit.framework).
These frameworks offer both Java and Objective-C APIs (with most Java classes
simply “bridging” to their Objective-C implementation).
Foundation and the Application Kit are similar in some respects to the Core Services
and Application Services layers, respectively. The classes in the Foundation
framework provide objects and functionality that have no impact on the user
interface; Foundation is directly based on Core Foundation. The classes of the
Application Kit furnish all the objects and behavior that affect what users see in the
user interface, such as windows and buttons, and responsiveness to their mouse
clicks and key presses. The Application Kit directly depends on Foundation.
Application Environments 63
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
Many of the Application Kit’s classes, as might be expected, are designed for the
creation and management of objects that appear in a graphical user interface.
Among these are classes for windows, dialogs, buttons, tables, text fields, sliders,
pop-up menus, scroll views, application (pull-down) menus, and even a movie
view for QuickTime streaming.
However, the Application Kit has features and functionality that make it far more
useful than just a collection of classes for user-interface objects.
■ It has sophisticated mechanisms for event handling and application and
document management.
■ It gives applications ways to integrate and manage colors, fonts, and printing
(even providing the dialogs for these features).
■ It allows you to composite images in many different graphical formats and it
offers a framework for drawing, including the application of vector
transformations.
■ It includes facilities for spell checking, dragging, and copy-and-paste
operations.
Other Cocoa frameworks are also available for scripting, network management, and
other purposes.
For more information about Cocoa, see the Cocoa documentation on the Apple
website: http://developer.apple.com/techpubs/macosx/Cocoa/
CocoaTopics.html.
Java
The Java application environment allows you to develop and execute Java
programs on Mac OS X, including 100% Pure Java applications and applets. This
environment is implemented in conformance with an industry standard—that is, a
recent version of the Java Development Kit (JDK) including the Java virtual
machine (VM). Because of this, a Java application created with this environment is
very portable. You can copy it to a computer that has entirely different hardware
64 Application Environments
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
and a different operating system and, as long as that system includes a compatible
version of the Java VM, your application should run on it. A Java applet should run
in any Internet browser with the proper capabilities.
The more significant of these packages are java.awt and javax.swing, commonly
known as AWT (Abstract Windowing Toolkit) and Swing. The AWT package
implements standard user-interface components (such as buttons and text
fields), basic drawing capabilities, a layout manager, and the event-handling
mechanism. The Swing package provides a greatly extended set of user interface
Application Environments 65
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
components. These components automatically take on the look and feel of the
host platform. Swing includes versions of the existing AWT component set plus
a rich set of higher-level components, such as tree view, list box, and tabbed
panes.The AWT and Swing package are in a jar archive located at
JavaVM.framework/Classes/classes.jar.
Swing
AWT
Java Carbon
command
environment Application Services
Kernel environment
The Java virtual machine along with the basic Java packages—java.lang, java.util,
and java.io—are equivalent to the Core Services layer of system software for the
Carbon and Cocoa environments. They draw on the resources of the kernel
environment to implement low-level services such as process management,
threading, and input/output. They do not need to access anything in the Core
Services layer of system software (Open Transport, Core Foundation, and so on).
All other parts of Java in Mac OS X are layered on top of the VM and the basic
packages. If a Java program does not have a user interface (say, a tool or an
application server), all it needs is this foundation to execute. But a 100% Pure Java
application or applet (which, by definition, has a graphical user interface) must use
AWT or Swing, both of which bind with many of the frameworks and libraries in
66 Application Environments
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
The preeminent application services of Mac OS X are those that make up the
graphics and windowing environment. An application, by its very nature, must
display its windows in a graphical user interface and allow users to manipulate its
controls. A graphics and windowing environment confers these basic capabilities
on applications “for free,” relieving them of the burden of implementing them on
their own. In addition to rendering text and images in windows on a screen (as well
as printing them), this environment also provides essential low-level facilities such
as initial event routing and cursor management.
The core portion of the Mac OS X graphics and windowing environment is called
Quartz. As depicted in Figure 3-3, Quartz has two parts: Quartz 2D and Quartz
Compositor. (The Quartz Extreme layer is integrated into Quartz Compositor.)
System Architecture
QuickTime
Quartz 2D QuickDraw (streaming, OpenGL
(2D) (3D)
multimedia)
Quartz Compositor
(window server)
Quartz Extreme
(hardware acceleration)
The Quartz 2D part of Quartz is one of several graphics libraries that provide
graphics-rendering services. It is designed for the display of two-dimensional text
and graphics. Peer graphics and multimedia libraries include
■ QuickDraw for rendering two-dimensional images
■ OpenGL for rendering both two- and three-dimensional images
■ QuickTime for rendering streaming digital video and other multimedia
All of the rendering libraries have direct dependencies on the other part of Quartz,
the Quartz Compositor layer. However, QuickTime and OpenGL have fewer
dependencies because they implement their own versions of certain windowing
capabilities.
Quartz Compositor consists of the Mac OS X window server and the (currently
private) system programming interfaces (SPIs) it implements. The window server
has overall responsibility for displays and windows, including their composition,
positioning, and basic management. It also performs low-level cursor management
and event routing.
System Architecture
The Cocoa and Java environments provide their own programming interfaces to
Quartz 2D and, to some extent, the other rendering libraries. You may use either the
Cocoa and Java interfaces, or you may use the programming interfaces in the
Application Services layer.
The remainder of this section discusses the role of Quartz in the graphics and
windowing environment. For conceptual information on QuickDraw, QuickTime,
and OpenGL, consult the relevant Apple developer documentation
(developer.apple.com).
Applications and
application environments
Quartz Compositor
The Quartz Compositor layer of Mac OS X comprises the window server and the
(private) system programming interfaces (SPI) implemented by the window server.
In this layer are the facilities responsible for rudimentary screen displays, window
compositing and management, event routing, and cursor management.
System Architecture
The window server has few dependencies on other system services and libraries. It
relies on the kernel environment’s I/O Kit (specifically, device drivers built with the
I/O Kit) in order to communicate with the frame buffer, the input infrastructure,
and input and output devices. It also links with certain frameworks in Core Services
to acquire process-management services such as basic process activation.
For the role of the window server in event handling, see “Tracking a User Event”
(page 85).
Quartz 2D
The Quartz 2D part of Quartz is a graphics library with a vector flavor. Its APIs
allow you to create text and images by specifying a sequence of commands and
mathematical statements that place lines, shapes, color, shading, translucency, and
other graphical attributes in two-dimensional space. You do not need to specify the
attributes of individual pixels. As a result, a shape can be efficiently defined as a
series of paths and attributes rather than as a bitmap.
System Architecture
By using vectors, Quartz 2D can also use a coordinate system for drawing based on,
say, inches or centimeters rather than a pixel grid. The coordinate system is flexible,
permitting various measurement standards, and it enables some degree of display
independence since it is not bound to any screen resolution. It also uses
floating-point coordinates. Prior to compositing by Quartz Compositor, Quartz 2D
translates the vector information of an image, which is described in terms of the
coordinate system, to pixel values.
The Quartz 2D API is device independent—that is, the final destination of the
drawing operation may be a window’s bitmap, but it may also be a Portable
Document Format (PDF) file, a PostScript file, or another output format. An
application may call the API directly or it may call it indirectly when displaying a
PDF file, when using QuickDraw, or when using other input mechanisms. Figure
3-5 illustrates this relationship.
Quartz 2D
The primary inputs for Quartz 2D are the drawing commands and statements made
with QuickDraw and the native C APIs. (Future APIs in the front-end may be
supported.) Applications using QuickDraw can call into Quartz 2D through a
CGContextRef interface and thereby get its capabilities. QuickDraw enables them to
obtain the CGContextRef from a GrafPort interface.
The commands and statements from QuickDraw or the native APIs are immediately
converted to the required output format, whether that be bitmap data for screen
rendering, PostScript (for PostScript printers), or raster data for other types of
printers. The PDF can also be published “as is”; this happens automatically for print
preview. Future back-end converters, such as for plotters, may be supported.
System Architecture
Quartz 2D, as the foregoing paragraph suggests, is the underlying engine for the
Mac OS X printing system. Printing is often a two-pass affair. Quartz 2D interprets
the text and images constructed with the native C or QuickDraw APIs and stores
them in PDF form (the primary spooling format). Then this PDF is fed through
Quartz 2D again to convert it to the appropriate output format.
The Mac OS X printing system provides a flexible and powerful new printing
environment for Macintosh developers. The architecture makes it much easier for
application developers to support printing in their applications and for printer
vendors to write printer drivers and extend printing dialogs. The Mac OS X printing
system has a number of advantages over the printing system used in Mac OS 8 and
9, including the following:
■ The printing system uses Quartz 2D for rendering and conversion services.
Quartz 2D supports a resolution-independent PDF drawing model that allows
applications to print high-quality, color-managed output on all classes of raster
and PostScript printers.
■ Sheets allow you to open more than one printing dialog at the same time and to
send more than one print job to a printer queue.
■ Printing dialogs can be customized with printing dialog extensions. This means
you do not need to completely replace the standard printing dialogs to provide
users with application-specific or printer-specific features. The Page Setup
dialog can be extended by application developers, while both printer vendors
and application developers can extend the Print dialog.
■ Printer modules replace printer drivers. Printer modules are easier to write than
printer drives, as much of the code that has to be in a driver is now taken care of
for you in Apple-supplied I/O modules and other parts of the printing system.
■ The printing application programming interface (API) includes robust support
for Carbon applications. Carbon developers can write one application that can
run in Mac OS X as well as in Mac OS 8 and 9. Cocoa developers support printing
by using Cocoa objects and methods. Cocoa methods call through to the Carbon
Printing Manager API.
System Architecture
A key aspect of the new printing system’s design is its robust support for Carbon
applications. Because the Carbon Printing Manager is supported in Mac OS 8 and 9
as well as Mac OS X, a Carbon application is able to print as expected in both
environments. For example, when running Mac OS 8 or Mac OS 9, the application
utilizes the traditional user interface and drivers. On Mac OS X, the application
automatically takes advantage of the new printing system’s more consistent set of
printing dialogs and flexible printing architecture.
For more information about printing, see Inside Mac OS X: About the Mac OS X
Printing System.
System Architecture
Printer
browser
module
Print
Center
Application
PDF Job
spool ticket
file
Print server
Application
Carbon
Services framework
framework PDF Job
spool ticket
file
Print job
manager
System Architecture
System Architecture
Printer Discovery
Before a user can choose a printer, Print Center must first compile a list of available
printers. The process by which Print Center locates available printers is called
“printer discovery.”
During printer discovery, Print Center enumerates all of the I/O and printer
browser modules installed in /System/Library/Printers and /Library/Printers.
The print server retrieves string representations of the various connection types
from the printer browser modules and passes them to Print Center. Print Center
populates the connection pop-up menu with these strings.
When the user selects a connection type, Print Center enumerates all the printer
modules installed in /System/Library/Printers and /Library/Printers and asks
each printer module if it supports the chosen connection type. If so, Print Center
retrieves icon and lookup information from it. The printer browser modules use this
information as search criteria when searching for printers that support a connection
type and as user interface elements in their display.
When the user clicks a printer to add it to the list of printers, Print Center gets the
selected printer address, icon, and printer model information from the printer
browser module. Print Center then uses this information to create a new print queue
and add the printer to the list.
At printing time, the application displays the Page Setup and Print dialogs in
response to user requests. The application displays both of these dialogs using
functions from the Carbon framework. Carbon application can extend a dialog
using a printer dialog extension (PDE). Printer dialog extensions let the Carbon
application define options specific to the application’s drawing environment—
custom page layouts, for example.
System Architecture
When the user dismisses the Print dialog, the Application Services framework
accepts drawing commands (QuickDraw, Core Graphics, or a PDF file) from the
application and puts them into a spool file. The application passes the spool file,
along with any printer objects, to the printing system. Upon receiving the
application data, the printing system creates a job ticket to manage the print-job
settings and status and then passes the job ticket along with the spool file to the print
server. The print server passes the data to the print job manager, which is
responsible for managing the rest of the printing process. Upon sending the job to
the print server, the application is done with its portion of printing. All errors
related to the print job are now routed asynchronously back to the Print Center for
display to the user.
The print job manager first consults the job ticket to determine the destination
printer and queries the destination printer’s associated printer module to find out
what data format it requires. If necessary, the print job manager uses a converter to
transform the incoming data into a format that the destination printer module can
accept. Next, the print job manager passes the data to the printer module, which is
responsible for converting the incoming data into the raw commands the printer
will use to render the data. Finally the print job manager receives the
printer-specific data from the printer module and uses the I/O module appropriate
to the printer’s connection type to send the data to the printer.
The other system services in the Application Services layer support all application
environments by supplying objects and behavior that affect the graphical user
interface. This section discusses some of the more prominent of these services.
Because of the evolving nature of Mac OS X, the composition of the Application
Services layer will change over time. Check the subframeworks of the Application
Services umbrella framework (ApplicationServices.framework) to learn what is
currently included.
System Architecture
Process Manager
The Process Manager manages all processes in Mac OS X. It controls access to
shared resources and manages the scheduling and execution of applications,
allowing multiple applications to share CPU time and other resources. The Finder
uses the Process Manager to launch applications when the user double-clicks an
application or a document icon. The Process Manager also provides a number of
routines that allow you to control the execution of processes, to launch processes,
and to get information about processes.
For related information on the Process Manager, see “Tasks and Processes”
(page 259) in the chapter ““Issues and Options With Multiple Environments”
(page 259).”
For more on event handling in Mac OS X, see “Tracking a User Event” (page 85).
Apple Events
An Apple event is a high-level event that applications can send to other applications
on the same computer, on a remote computer, or even to themselves. Apple events
are the primary mechanism for interapplication communication in Mac OS X.
Applications typically use them to request services and information from other
applications, or to provide services and information in response to such requests.
System Architecture
See “Interprocess Communication” (page 263) in the chapter ““Issues and Options
With Multiple Environments” (page 259)” for further discussion of Apple events.
The Clipboard
The Mac OS X Clipboard (also known as the “pasteboard”) is a background server
that allows you to transfer data between applications. It is similar in some respects
to the Mac OS 9 Clipboard, but different in others. The Mac OS X Clipboard can hold
multiple representations of the same data. It is shared by all executing applications
and contains data that the user has cut or copied, as well as other data that one
application wants to transfer to another. It is used in copy-cut-paste operations and
as the data-transfer mechanism in drag-and-drop operations. It is also used by
Services to transfer data between applications.
Core Services
The Core Services layer contains the system services that do not have any effect on
an application’s graphical user interface. This level includes Core Foundation,
Carbon Core, CFNetwork, web services, and Open Transport. The Core Services
layer comprised primarily of two frameworks—the Core Services umbrella
framework (CoreServices.framework) and the Core Foundation framework
(CoreFoundation.framework). This section talks about the more prominent
technologies in these frameworks; others (for example, core security services) are
not discussed.
Core Foundation
Core Foundation is a framework (CoreFoundation.framework) that provides
fundamental software services useful to application services, the application
environments, and to applications themselves. Among the benefits of using
Core Foundation is the increased capability for sharing code and data among
frameworks, libraries, and applications in different environments and layers. Core
Foundation also enables easy internationalization through Unicode strings and
provides abstractions that contribute to operating-system independence.
Core Services 79
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
Core Foundation uses the paradigm of opaque types; using these types, you can
create “objects,” each with its own individual identity and value (or set of values).
It offers special facilities for allocating memory when these objects are created, and
it has generic base types and polymorphic functions to facilitate intertype
operations.
Table 3-3 lists the Core Foundation services and their associated opaque types.
80 Core Services
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
Core Services 81
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
Carbon Core
The Carbon Core is a part of CoreServices.framework that includes a number of
Carbon managers and offers low-level services to all application environments.
These services include cooperative and preemptive threading, resource
management, memory management, and file-system operations. Table 3-4
summarizes these managers.
Manager Description
Alias Manager Helps locate specified files, directories, or volumes using
aliases. It provides routines for creating and resolving
file-system alias records.
Collection Provides an abstract data type for storing collections of
Manager information.
Component Enables your application to find and use various software
Manager objects (components) at runtime. Also allows your application
to create and manage components.
Date, Time, and Allows applications to obtain and manipulate information on
Measurement dates, times, geographic location, time zone, and units of
Utilities measurement.
File Manager Gives programs the ability to access files stored on physical
volumes, including hard disks, CDs, and Zip disks. It handles
Mac OS Extended (HFS+), Mac OS Standard (HFS), UFS, NFS,
and other supported file formats. The File Manager routines
create, open, update, save, and close files; search for specific
files or directories; obtain information about files or
directories; and perform other advanced file-related
operations. The File Manager supports Unicode and its APIs
are thread-safe.
Folder Manager Allows programs to find and search folders, create new ones,
and control how files are routed between folders. It includes
new support for domains.
Memory Provides specialized routines useful for examining or
Management controlling certain aspects of the memory environment.
Utilities
82 Core Services
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
Manager Description
Memory Controls the dynamic allocation of memory within an
Manager application’s protected address space. It includes new
routines for allocating shared and persistent memory as
well as functions related to the virtual memory system in
Mac OS X.
Multiprocessing Enables programs to create and manage separate
Services preemptively scheduled threads. It also includes
synchronization services and atomic instructions.
Resource Provides routines for creating, deleting, opening, reading,
Manager modifying, writing, and getting information about resource
files. It includes support for data-fork based resources.
Text Encoding Provides two facilities—the Text Encoding Converter and the
Conversion Unicode Converter—that applications can use to perform text
Manager conversions.
Text Utilities Offers an integrated set of routines for performing a variety of
operations on text, ranging from sorting strings to finding
word boundaries.
Thread Manager Enables programs to create and manage cooperatively
scheduled threads.
Time Manager Gives programs a way to schedule the execution of routines at
a specified time, either once or repetitively. This mechanism
for performing time-related tasks is hardware-independent.
Unicode Utilities Performs various operations on Unicode text, including
Unicode key translation.
CFNetwork
CFNetwork is a part of CoreServices.framework and is the preferred API to use for
user-level networking and communications. CFNetwork provides a suite of
functions for creating, serializing, deserializing, and managing protocol messages
that are commonly exchanged between clients and servers. CFNetwork makes it
unnecessary for you to have to learn and implement the details of a protocol in
order to exchange protocol messages.
Core Services 83
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
Web Services
Web services is a part of CoreServices.framework that lets you take advantage of
remote programs on the Internet or a local intranet. Web services use standard
protocols such as the Simple Object Access Protocol (SOAP) and XML-RPC to
communicate service requests over HTTP. These standard protocols permit
communication between otherwise disparate computing platforms and permit the
creation of distributed services. The WebServicesCore framework defines an API
for sending requests to remote servers using these protocols and for handling
responses.
Application developers can also incorporate web service functionality into their
applications using the Apple Event Manager and AppleScript. For more
information, see Inside Mac OS X: Making XML-RPC and SOAP Requests With
AppleScript.
Open Transport
Open Transport is a Carbon compatibility API in CoreServices.framework that
provides legacy networking and communications support. Open Transport enables
applications to use more than one networking system at once (for example,
AppleTalk to communicate with network printers and TCP/IP to connect to the
Internet). With Open Transport, users can save and modify different networking
configurations and switch easily among them.
The version of Open Transport in Mac OS X supports the most commonly used
interfaces in Mac OS 8 and Mac OS 9. For example, it supports the Open Transport
endpoint routines for IP protocols. However, it does not include the
connection-oriented transaction-based endpoint feature (which should affect only
users of AppleTalk protocols such as ASP). Neither does it support the native XTI
(X/Open Transport Interface) interfaces or BSD stream interfaces.
84 Core Services
Apple Computer, Inc. July 2002
C H A P T E R 3
System Architecture
An important change from prior versions of Open Transport is the addition of client
context parameters to a number of functions. Each client of Open Transport now has
its own context so that Open Transport can track resources it allocates on behalf of
the client. A client in this case is an application or a shared library, and resources are
objects like endpoints, timer tasks, and blocks of memory.
The perspective that Figure 3-1 (page 55) gives of Mac OS X as layers of system
software suffices to illustrate the general interfaces and dependencies among parts
of the system. But it does not adequately convey the dynamism of the operating
system—in other words, how Mac OS X typically “works.” An alternative approach
to this static view of Mac OS X is one that follows a hypothetical user event through
the system, from the click of a mouse to the handling of the event by the appropriate
function or method in the appropriate application environment. It then traces,
through the layers of the system, a hypothetical chain of events set off by the
invocation of the function, resulting, in this case, in the drawing of a new object on
the screen (say, a dialog).
Figure 3-7 depicts the environments and subsystems that generate, repackage, and
forward an event along to its destination.
System Architecture
Application processes
Carbon Cocoa
DefProc EventRef Callbacks Target/action, NSEvent,
handler NSApp, etc.
Core and
Application Services
Event Manager
Per process
Run loop
Window server
Darwin
Driver Driver
A low-level event originates when the device driver that controls an input device
such as the mouse or the keyboard detects a user action. The I/O Kit, which forms
the foundation of all device drivers in Mac OS X, creates the event and puts it in
the window server’s event queue (see “Quartz Compositor” (page 69) for a
discussion of the window server). This queue is in a block of memory shared by the
I/O Kit and the window server. Once the I/O Kit puts an event in the queue,
it notifies the window server via the Mach interprocess communication
mechanism (IPC).
The window server then takes the event off the queue and consults a database of
currently open windows. It sends the event to the event port of the run loop
belonging to the process that owns the window where the event occurred. The
Carbon Event Manager gets the event from the run-loop port, packages the event in
an appropriate form, and passes it to the event-handling mechanism specific to the
System Architecture
application environment of the process. This mechanism ensures that the event is
handled by the function or method associated with the control that is clicked (or key
that is pressed).
For more information on how events between Carbon and Cocoa environments are
handled, see Inside Mac OS X: Integrating Carbon and Cocoa in Your Application.
System Architecture
This chapter describes what happens when a Mac OS X system boots up and when
a user logs into the system. “Booting up” refers to the series of actions the system
performs to prepare itself for use. This boot sequence includes a number of different
tasks, including initializing hardware, starting system daemons, and displaying the
login window. After a user logs in, the system completes an additional series of
actions that sets up the computing environment for that user.
This chapter explains the aspects of the boot sequence that developers might
encounter when trying to write their software. This chapter also explains how to use
the various “hooks” available for customizing the booting procedures.
Note: Man pages, a form of online documentation, are available for most of the
daemons and utilities mentioned in this chapter. You can consult these man
pages for further information. To display a man page from the Terminal
application, enter man on the command line followed by the name; for example,
> man getty (where > is the prompt). You can also access man pages from the Help
menu in Project Builder.
From the moment a user turns on a Mac OS X system to the moment the login
window appears, Mac OS X executes a boot sequence that readies the system for
use. This section summarizes the events that happen during this sequence.
BootROM
When the power to a Macintosh computer is turned on, the BootROM firmware is
the first code activated. BootROM (which is part of the computer’s hardware) has
two primary responsibilities: to initialize system hardware and to select an
operating system to boot. BootROM has two components to help it carry out these
functions:
■ POST (Power-On Self Test) initializes some hardware interfaces and verifies that
sufficient RAM memory is available and is in a good state.
■ Open Firmware initializes the rest of the hardware, builds the initial device tree
(a hierarchical representation of devices associated with the computer), and
selects the operating system to use.
BootX
When BootROM (or the user) selects Mac OS X as the operating system to boot,
control passes to the BootX booter (located in /System/Library/CoreServices).
BootX’s principal duty is to load the kernel environment. As it does this, BootX
draws the “booting” image on the screen.
When loading the kernel environment, BootX first attempts to load a previously
cached set of device drivers (called an mkext cache) for hardware that is involved
in the boot process. If this cache is missing or corrupt, BootX searches
/System/Library/Extensions for drivers and other kernel extensions whose
OSBundleRequired property is set to a value appropriate to the type of boot (for
example, local or network boot). See the kernel developer documentation for more
on the OSBundleRequired key and the loading of device drivers during booting.
Once the kernel and all drivers necessary for booting are loaded, BootX starts the
kernel’s initialization procedure. At this point, enough drivers are loaded for the
kernel to find the root device. Also from this point, Open Firmware is no longer
accessible.
The kernel initializes the Mach and BSD data structures and then initializes the I/O
Kit. The I/O Kit links the loaded drivers into the kernel, using the device tree to
determine which drivers to link. Once the kernel finds the root device, it roots BSD
off of it.
Finally, the kernel starts the mach_init process. The mach_init process is the Mach
bootstrap port server, which enables Mach messaging.
After the root file system is mounted, system initialization proceeds to run the
system startup items and launch any system daemons (see “System Initialization”
(page 91)).
System Initialization
The mach_init process starts the BSD init process. This latter process, which has a
process ID (PID) of 1, “owns” every other process on the system. Despite its
centrality, the init process is simple. It performs four principal tasks:
Although the init process owns every other process on the system, a distinction can
still be made between user and system processes. Startup items and any
applications run prior to the loginwindow application form the group of system
processes. These applications provide services to all users of the system and are
usually children of the init process. Processes created after the launching of
loginwindow form the group of user processes. User processes are always
associated with a particular user session and are usually children of the Window
Manager process of the user’s session.
Note: Not all user processes are children of the Window Manager process. Processes
launched as root and some special system processes are owned by the user but
are children of the init process. You can use the Process Viewer application to
determine the owner and parent of any process on the system.
When a user logs out of a session, the loginwindow application terminates all
processes running in the scope of that user session. This is a requirement for closing
out the session cleanly. System processes are not affected by a user logout. System
processes are terminated only when the system itself is shutdown or restarted. For
more information on what happens during a logout, restart, or shutdown sequence,
see “Logging Out” (page 102).
Because the rc scripts are simple Bourne shell scripts, you can read the source to see
exactly what takes place. For more information on the daemons started during
system installation, see “System Daemons” (page 96).
Startup Items
Startup items are procedures that run during the last phase of booting to prepare a
Mac OS X system for normal operation. They consist of programs (including shell
scripts) that perform tasks such as clearing away temporary files and starting
system daemons.
The SystemStarter program, which is the last thing run by the rc script, coordinates
the execution of all startup items. To understand what SystemStarter does, it helps
to understand what a startup item is. A startup item is a folder containing at least
two files:
■ a program (typically a shell script) whose name matches the folder name
■ a configuration property-list file
Table 4-1 lists the core startup items provided with Mac OS X, along with a brief
description of what they do. Other startup items may be installed by third-party
applications or by system components such as QuickTime. The order given in the
table is the general order in which the items are executed. The exact order is
determined by the SystemStarter program at boot time.
The section “System Daemons” (page 96) briefly describes some of the daemons
and services mentioned in this table.
System Daemons
By the time a user logs in to a Mac OS X system, a number of processes are already
running. Most of these processes are daemons or servers created by the system and
running in the background. A handful are created on behalf of the user by the
loginwindow application and the Window Manager daemon. Launching the Process
Viewer (located in /Applications/Utilities) immediately after login results in a
window similar to the one shown in Figure 4-1.
Table 4-2 describes some of the standard daemons and servers. Depending on the
system configuration and user preferences, some of these daemons may be disabled
or set up to launch on demand (see “Launching Daemons on Demand” (page 99)).
Conversely, your system may have other daemons running because of additional
installed services.
Daemon Description
ATSServer The Apple Type Solution server, enabling system-wide font
management.
autodiskmount Automatically mounts all devices, including hard disks, and
removable media.
automount Automatically mounts NFS file systems when they are first
accessed and later unmounts them when they are idle. A
mount point for a virtual file system first appears as a symbolic
link on a local file system. Reading this symbolic link triggers
automount to mount the associated remote file system.
Daemon Description
mach_init The Mach bootstrap port server, through which Mach
messaging is enabled. It also starts the init process.
mDNSResponder The multicast-DNS responder daemon.
netinfod NetInfo servers, one for each domain served.
nfsiod Services asynchronous requests to an NFS server. Most systems
have multiple instances of this daemon running.
nibindd Finds, creates, and destroys NetInfo servers (see netinfod).
pbs The pasteboard server (similar to the Clipboard in Mac OS 9)
enables the exchange of data between applications. It is also the
data-transfer mechanism used in dragging operations. See
“The Clipboard” (page 79) for more information.
portmap Converts RPC program numbers into Internet (DARPA
protocol) port numbers. It must be running before RPC calls
can be made.
syslogd Logs system error and status messages.
update Periodically flushes the file-system cache to help prevent data
loss in the event of a crash.
Window Manager The window server. See “Quartz Compositor” (page 69) for
more information. This process is the parent for most user
processes.
For further information consult the man pages available for most of these daemons.
On-demand launching is transparent to clients of the services that support it. When
a client sends a message to a daemon that is currently shut down, mach_init
automatically loads any services required by the daemon and then launches the
daemon. Once the daemon is up and running, it checks in with mach_init and asks
for the receive rights to its Mach ports. Once it has the receive rights for its ports, the
daemon can respond to messages on those ports normally.
How to create an on-demand daemon is beyond the scope of this book because it
involves interactions with the kernel. For more information on the kernel and
Mach-port messaging, see Inside Mac OS X: Kernel Programming.
During the system initialization cycle, the init process launches the loginwindow
application to manage user sessions. The loginwindow application displays the
login window and provides several services on behalf of the user. This section
discusses those services and the user environment provided by loginwindow.
Logging In
The loginwindow application coordinates the login process and user session,
calling on other system services as needed. Depending on the user’s login
preferences, loginwindow may prompt the user for a valid login name and
password or use cached values to log the user in automatically. When the user’s
login name and password have been authenticated (see “Authenticating Users”
(page 101)), loginwindow proceeds to load the user environment.
When all of the specified applications are launched and running, the login
procedure is complete.
If the Finder or Dock processes die for some reason, loginwindow automatically
launches them again. In the same vein, if the loginwindow application dies, the init
process automatically restarts it.
Once the user session is up and running, loginwindow monitors the session and
user applications in the following ways:
■ Manages the logout, restart, and shutdown procedures. See “Logging Out”
(page 102) for more information.
■ Manages the Force Quit window, which includes monitoring the currently
active applications and responding to user requests to force-quit applications
and relaunch the Finder. (Users open this window from the Apple menu or by
pressing Command-Option-Escape.)
■ Displays alert dialogs upon receiving notifications from hidden applications
(that is, applications with no visible user interface).
■ Writes any standard-error (stderr) output to a log file (/var/tmp/console.log),
which is then used as input by the Console application.
Authenticating Users
Mac OS X requires user authentication prior to accessing the system. Although the
loginwindow application manages the user authentication process, it does not
authenticate the user itself. The loginwindow application takes the user information
specified in the login screen and passes it to Directory Services for authentication.
As soon as Directory Services authenticates the user, loginwindow initiates the user
session.
The loginwindow application does not prompt the user for login information if the
“Enable automatic log in” option is selected. Only one user at a time may enable this
option from the Users pane of the Accounts System Preferences. From this same
pane, the user must also enter a valid password by clicking the Set Auto Login
control.
1. Secures the login session from unauthorized remote access. Applications that
are launched remotely are not registered with the pasteboard server’s (that is,
the Clipboard’s) port. As a result, some standard features are blocked for these
processes, including copy, cut, paste, Apple events, window minimization, and
other services.
2. Records the login in the system’s utmp database.
3. Sets owner and permissions for the console terminal.
4. Resets the user’s preferences to include global system defaults
(NSRegistrationDomain).
5. Registers the pasteboard server (pbs) with the bootstrap port and launches pbs.
6. Configures the mouse, the keyboard, and system sound using the user’s
preferences.
7. Sets the user’s group permissions (gid).
8. Retrieves the user record from Directory Services and applies that information
to the session.
Logging Out
The procedures for logging out, restarting the system, or shutting down the system
have similar semantics. The foreground process usually initiates these procedures
in response to the user choosing an item from the Apple menu; however, a process
can also initiate the procedure programmatically by sending an appropriate Apple
event to the loginwindow application. The loginwindow application carries out the
procedure, posting alerts and notifying applications to give them a chance to clean
up before closing.
1. The user selects Log Out, Restart, or Shut Down from the Apple menu.
2. The foreground application initiates the user request by sending an Apple event
to the loginwindow application. (See “Application Responsibilities” (page 103)
for a list of events.)
3. The loginwindow application displays an alert to the user asking for
confirmation of the action.
4. If the user confirms the action, loginwindow sends a Quit Application Apple
event (kAEQuitApplication) to every foreground and background user process.
5. The loginwindow application closes out the user session and continues with the
action.
Application Responsibilities
To initiate a logout, restart, or shutdown sequence, the foreground application must
send an appropriate Apple event to the loginwindow application. Upon receipt of
the event, the loginwindow application begins the process of shutting down the
user session. Depending on the Apple event sent by the process, loginwindow may
or may not notify the user with an alert and give the user a chance to abort the
sequence.
The following list shows the preferred Apple events for logout, restart, and
shutdown procedures. These events have no required parameters.
■ kAELogOut
■ kAEShowRestartDialog
■ kAEShowShutdownDialog
Upon receipt of one of these events, loginwindow posts an alert notifying the user
of the impending action. At this point, the user may continue with the action or
abort it. If the user continues with the action, loginwindow sends an Apple event to
each application asking it to quit. See “Terminating Processes” (page 104).
In addition to the preferred Apple events, there are two additional events that tell
loginwindow to proceed immediately with a restart or shutdown sequence. The
kAERestart and kAEShutDown Apple events proceed with a polite restart or shutdown
of the system. However, these events should be used judiciously because neither of
them posts a message to the user or allows the user to abort the sequence.
Important
Note that if a logout, restart, or shutdown event originates
from an application in the Classic environment, the event
affects only the Classic environment and its applications.
The rest of the user session continues running.
Terminating Processes
Prior to carrying out a log out, restart, or shutdown sequence, the loginwindow
application attempts to terminate all foreground and background user processes.
The loginwindow application sends each process a kAEQuitApplication Apple event
to give it a chance to shut down gracefully. For foreground processes, loginwindow
then waits for a reply. For background processes, loginwindow terminates the
process, by sending a kill command, regardless of any reply.
For user background processes that link with Carbon, Cocoa, or Java, the procedure
is a little different. Loginwindow notifies the process that it is about to be
terminated by sending it a Quit Application Apple event (kAEQuitApplication).
However, it does not wait for a reply from the process. Loginwindow proceeds to
terminate any open background processes, regardless of any returned errors.
The loginwindow application does not terminate processes residing in the system
context. This rule applies to all daemons and system startup items that are launched
by the system at boot time. These processes reside outside the context of the user
session and are terminated only during a restart or shutdown sequence.
Loginwindow also does not kill background processes that are independent of
Carbon, Cocoa, or Java, even if they are launched from the user context. (Though
launched from a user context, these processes are taken over by the system when
the user logs out.) Mac OS X does not send any notifications to system processes
before terminating them.
Customization Techniques
The Mac OS X boot process includes several entry points that developers can use to
customize the process. Developers can create new system daemons and services to
be launched at boot time. Developers and system administrators can also create
initialization scripts to be run when a user logs in to the system.
Startup items are run (through the SystemStarter program) as the final phase of the
booting sequence. At that time, SystemStarter looks for startup items in the
/System/Library/StartupItems and /Library/StartupItems directories. It gathers
information from the property list of each startup item and uses that information to
determine the execution order for the items. It then executes the startup items in
groups based on the dependencies of the items.
To create a new startup item, you must create a program or script to execute your
code, and you must create a property list file to contain information about your
startup item. The following sections describe these techniques in more detail.
Note: Although a single startup item can perform multiple tasks and launch
multiple daemons, it is recommended that you limit your startup items to one
task. Implementing one task per item makes it easier to isolate dependencies and
to speed up the loading of startup items.
1. Create a directory for your startup item. The directory name should correspond
to the behavior you’re providing.
Example: MyDBServer
2. Add your executable to the directory. The name of your executable should be
exactly the same as the directory name.
Example: MyDBServer/MyDBServer
3. Create the property list with the name StartupParameters.plist and add it to the
directory. See “Specifying the Startup Item Properties” (page 107).
Example: MyDBServer/StartupParameters.plist
4. Create an installer to place your startup item in the /Library/StartupItems
directory of the target system. (Your installer may need to create this directory
first.)
Mac OS X provides some shell script code to simplify the process of creating startup
items. The file /etc/rc.common defines some routines that are useful for processing
command-line arguments and for gathering system settings. To use these routines,
source the rc.common file in a shell script and call the RunService routine, passing it
the first command-line argument, as shown in the following example:
#!/bin/sh
. /etc/rc.common
#
# Your startup item code
#
RunService "$1"
If your startup item executable contains code that might take a while to complete,
you should consider running that code as a daemon or a background process.
Executing lengthy startup tasks directly from your scripts delays system startup.
Your startup item script should execute as quickly as possible and then exit.
Table 4-3 lists the key-value pairs to include in the StartupParameters.plist file of
your startup item. All arrays and dictionaries contain string values. You can use the
Property List Editor application in /Developer/Applications to create this property
list.
The values you specify for the Requires and Uses properties correspond to the
service name on which your startup item is dependent. Service names may not
always correspond directly to the name of the startup item that provides that
service. The Provides property specifies the names of the services provided by a
startup item, and while this name usually matches the name of the startup item, it
is not required to do so. In particular, startup items that launch multiple services can
have at most one service whose name matches the name of the startup item.
If two startup items provide a service with the same name, SystemStarter runs only
the first startup item it finds with that name. For this reason, it is recommended that
your startup items do not provide multiple services unless absolutely required by
codependencies in your startup code.
The values of the Requires, Uses, and OrderPreference keys do not guarantee a
particular launch order.
If you want to start, restart, or stop startup items from your own scripts, you can do
so using the SystemStarter program. To use SystemStarter, you must execute it with
two parameters: the desired action and the full path to the target startup item
directory. For example, to restart the Apache Web server, you would type the
following at the command prompt:
Important
You must have root authority to start, restart, or stop startup
items.
Startup items should always respect the arguments passed in by SystemStarter.
However, the response to those arguments is dependent on the startup item. The
stop and restart options may not make sense in all cases. Your startup item could
also support the restart option using the existing code for stopping and starting its
service.
Applications that need to manipulate startup items at runtime can also do so using
the SystemConfiguration framework. This framework supports getting references
to a desired startup item and starting it.
For more information about startup items, see “Creating Custom Startup Items”
(page 105).
To use the loginwindow hooks, you must modify the code for launching
loginwindow found in /etc/ttys. In this file is the following line:
This line tells the init program to launch loginwindow on the console terminal and
to use WindowServer (which is a symbolic link to the Window Manager process) as the
windowing-system process. Into this line, you can insert additional parameters for
loginwindow to process. Table 4-4 lists the parameters currently supported by
loginwindow.
The -LoginHook and -LogoutHook parameters are particularly useful because they
permit custom administrative, accounting, or security programs to run as part of
the login and logout procedures. For example, your modified console definition in
/etc/ttys might look similar to the following:
console "/System/Library/CoreServices/loginwindow.app/loginwindow
-PowerOffDisabled YES -LoginHook
/Users/Administrator/Scripts/mailLoginToAdmin" vt100 on secure
window=/System/Library/CoreServices/WindowServer
onoption="/usr/libexec/getty std.9600"
~/.MacOSX/environment.plist
If an environment.plist file exists, loginwindow reads the keys from the file and
registers them as user environment variables. This file supports only the definition
of environment variables. You cannot use this file to execute other forms of script
code. The format of the file is the same XML format as other property list files, with
each key in the file containing a string value.
To replace the Finder system application, use the defaults utility to modify the
loginwindow preferences. The loginwindow preferences are stored in
com.apple.loginwindow. The key you want to modify is the Finder key. Use the
following syntax to write a new value for this key, specifying the full path to the
replacement application:
Users can execute this command from the Terminal application to change their own
default settings. To change this setting for all users, you must execute this command
from Terminal as root. You could also modify the /etc/ttys script or create your
own login hook to execute the hook at each user login.
Using this command does not prevent users from launching the Finder manually
once they have logged in. It does prevent loginwindow from automatically
relaunching the Finder in the event of a crash or the user killing it from the Force
Quit window.
For more information on the defaults utility, see “The defaults Utility” (page 208)
in the chapter “Software Configuration” and consult the defaults man page.
5 Bundles
A bundle is a directory in the file system that stores executable code and the
software resources related to that code. (It can contain only executable code or only
software resources, but that is unusual). The bundle directory, in essence,
“bundles” a set of resources in a discrete package. The resources include such things
as images, sounds, and localized character strings that are used by some piece of
software. Because code and associated resources are in one place in the file system,
installation, uninstallation, and other forms of software management are easier.
Bundles can contain multiple sets of resources, each set of which groups resources
by language, locale, and platform. By combining these sets of resources and
executable images into a single package, you can create one version of your
application, framework, or plug-in that executes properly on any supported
platform. Using this model, you can automatically localize an application’s human
interface according to the user’s language preferences.
115
Apple Computer, Inc. July 2002
C H A P T E R 5
Bundles
Bundles
Anatomy of a Bundle
Bundles contain executable code and can contain a variety of resources such as
■ images
■ sounds
■ localized character strings
■ Resource Manager–style resource files
■ libraries and frameworks
■ plug-ins and other loadable bundles
■ archived user-interface definitions
Mac OS X supports two different layouts for bundle directories, “new-style” and
versioned. The directory layout for versioned bundles is inherited from Mac OS X’s
predecessor operating systems. The following example depicts this layout:
MyBundle.bundle/
MyBundle (executable code)
Resources/
Pretty.tiff (nonlocalized resource)
English.lproj/ (localized resources)
Stop.eps
MyBundle.nib
MyBundle.strings
French.lproj/ (localized resources)
Stop.eps
MyBundle.nib
MyBundle.strings
Bundles
Although the newest development tools on Mac OS X create only new-style bundles
(with the exception of frameworks), the system bundle routines can read and
manipulate both styles of bundles.
The remainder of this section describes the layout of new-style bundles, explaining
where the executable code and resources go within a bundle. On disk, a bundle
exists as a directory hierarchy. Minimally, a bundle has the structure shown in
Listing 5-1:
- MyBundle/
Contents/
Info.plist
In other words, the Contents directory and, inside it, the Info.plist file must be
present in a bundle. These files are important to how the bundle is treated by Finder
and other parts of the operating system. They describe the bundle’s various
attributes.
Note: Use of the PkgInfo file is deprecated and is no longer required for bundles.
You may still include this file in your bundles, but type and creator information
should also be stored in the bundle’s Info.plist file.
The information property list, Info.plist, contains key-value pairs stored in XML
format. These pairs specify attributes such as the name of the bundle, the name of
the bundle executable, version information, type and creator codes, application and
document icons, and other metadata. System routines allow the bundle executable
to read these attributes at runtime. In addition to the default bundle attributes,
subsystems may place their own attribute information in the Info.plist file for easy
access at runtime. You are free to store any application-defined data in the
information property list as well. See “Information Property Lists” (page 200) in the
chapter ““Software Configuration” (page 199)” for more on information property
lists, including an example of one.
A special localized resource file named InfoPlist.strings goes with the Info.plist
file. The former file contains keys for the information property list that need to be
localized such as the CFBundleName key. For more information on localizing
bundle names, see “Localizing Bundle Names” (page 179).
Bundles
From the minimal bundle layout, a bundle directory can expand to a fully
fleshed-out bundle such as you might find in a complex application. Listing 5-2
shows what might go into such a bundle.
- MyBundle/
MyApp /* alias to Contents/MacOSClassic/MyApp */
Contents/
MacOSClassic/
MyApp
Helper Tool
MacOS/
MyApp
Helper Tool
Info.plist
Resources/
MyBundle.icns
Hand.tiff
Horse.jpg
WaterSounds/
en_US.lproj/
MyApp.nib
bird.tiff
Bye.txt
house.jpg
house-macos.jpg
house-macosclassic.jpg
InfoPlist.strings
Localizable.strings
CitySounds/
en_GB.lproj
MyApp.nib
bird.tiff
Bye.txt
house.jpg
house-macos.jpg
house-macosclassic.jpg
InfoPlist.strings
Localizable.strings
CitySounds/
Bundles
Japanese.lproj/
MyApp.nib
bird.tiff
Bye.txt
house.jpg
house-macos.jpg
house-macosclassic.jpg
InfoPlist.strings
Localizable.strings
CitySounds/
Frameworks/
PlugIns/
SharedFrameworks/
SharedSupport/
Although there are different types of bundles, they all share certain features. At the
top level of the bundle there is always a Contents directory. The Resources,
Frameworks, SharedFrameworks, SharedSupport and PlugIns directories are optional
and appear only as necessary.
Important
You should avoid hard-coding directory paths to items
within bundles because the internal structure of bundles
could change. Instead, use the appropriate bundle APIs
provided by Apple.
Several directories contain, as their names suggest, executable code for specific
platforms. When a bundle’s code is requested, the system searches for code in the
format appropriate to the underlying operating system. The names of the
platform-specific executable directories are MacOSClassic and MacOS. The name of
the executable file inside these directories is typically the same name as the bundle
name (minus the extension).
Bundles
if it’s an application bundle). By convention, this file takes the name of the bundle
and an extension of .icns; the image format can be any supported type, but if no
extension is specified, the system assumes .icns. See “Localized Resources”
(page 125) for more on bundle resources.
A bundle often stores each resource in its own file instead of grouping them in a
single file, as does the Resource Manager. Localizable strings, however, are stored
together in a “strings” file (so called because it has an extension of .strings). The
reason for storing localizable strings in one file is that the contents can then be easily
cached for better performance.
For more information on bundle resources, including localized strings, see the
chapter “Internationalization” (page 211).
Important
Apple recommends that you do not package resources in the
resource fork of the bundle’s executable files.
The Frameworks directory contains frameworks that are inextricably bound to the
application. These dynamic shared libraries of these frameworks are
revision-locked and will not be superseded by any other, even newer, versions that
may be available to the operating system.
The SharedFrameworks directory contains frameworks that are also part of the
application package; but the versions of these frameworks are checked against the
system registry to see if there are more recent versions available. If a more recent
version is found in the system, the version in the SharedFrameworks directory is
ignored. The inclusion of versioned frameworks in the application package makes
it possible for an application to be completely self-contained. An application can be
installed, relocated, and removed simply by dragging.
Bundles
When you create a bundle, the build system can set a Finder attribute called a
“bundle bit” in the bundle folder. Before the Mac OS X Finder displays a bundle in
one of its windows, it reads this attribute. If the bundle bit is turned on, the bundle
appears as a file package. A file package is a folder that the Finder presents to users
as if it were a file (see Figure 5-1). In other words, the Finder hides the contents of
the folder from users. This opacity discourages users from inadvertently (or
intentionally) altering the contents of the bundle.
Some bundles might not have the bundle bit set; this is the case with
Apple-provided bundles. Yet the Finder can still handle them appropriately. As
explained in the next section (“Types of Bundles” (page 123)), bundle folders
should have extensions indicating their type—.app, .framework, .bundle, and so on.
When the Finder encounters one of these folder extensions and determines that the
folder is indeed a bundle, it does the proper things:
■ Except for frameworks, it displays the bundle as a file package.
Frameworks are displayed as folders so that you can browse their header files.
■ If the bundle is an application (also known as an application package), Finder
hides the .app extension.
■ It extracts or computes the runtime information it needs from the bundle (type
and creator codes, for instance) and updates its databases with it.
Bundles
For more information on the Finder and how it handles bundles and documents, see
the chapter “The Finder” (page 189).
Types of Bundles
Bundles
Although bundles can have any extension, there are some conventions. For
example, applications typically use the .app extension. You can use other extensions
for applications, as long as the application’s Info.plist file has a
CFBundlePackageType key with the value “APPL”. The traditional extension for
frameworks is .framework. Plug-ins and other loadable bundles can have any
extension, but it should be an extension claimed by an application that knows how
to load the bundle. The generic extension for loadable bundles is .bundle.
Framework Bundles
Frameworks are bundles that package dynamic shared libraries,
interface-definition files, images, and other resources that support the executable
code along with the header files and documentation that describe the associated
programming interfaces. As long as your applications are dynamically linked with
frameworks, you should have little need to do anything explicitly with those
frameworks thereafter; in a running application, the framework code is
automatically loaded and linked, as needed. Frameworks should have an extension
of .framework.
Bundles
Localized Resources
If a bundle is to be used in more than one part of the world, its resources may need
to be customized, or localized, for language, country, or cultural region. For
example, an application may need to have separate Japanese, English, French, and
Swedish versions of the character strings that label menu commands. An
application may also need to accommodate regional language variation—British
and American English, for example.
Bundles solve this problem by grouping resources together into directories named
for their region and language with the extension.lproj. Region-specific resource
directories should take their names from the ISO 3166 standard for country codes,
and the ISO 639 standard for language codes (see http://www.iso.ch). You would
place resources specific to the dialect of French spoken in France in a directory
named fr_FR.lproj, whereas you would place resources specific to Canadian
French in a directory named fr_CA.lproj. Localized resources that need not be
region specific should be placed in directories named simply for the language, such
as English.lproj or Japanese.lproj. These localized resource directories are then
placed in a directory named Resources within the bundle’s Contents directory.
Nonlocalized (global) resources are kept in the top level of the Resources directory.
See the section “Anatomy of a Bundle” (page 117) for an example of a complex
bundle’s file system layout.
Bundles
The user determines which set of localized resources are actually used by the
bundle at runtime. Bundle-related system routines rely on the language preferences
set by the user in the Preferences application. Preferences lets users create an
ordered list of available regions so that the most preferred region is first, the second
most preferred region is next, and so on. When a bundle is asked for a resource file,
it returns the file-system location of the resource that best matches the user’s region
preferences. See the section “Search Algorithm” (page 127) for details on the exact
process Mac OS X uses to locate a bundle resource. See the section “Localizing File
System Names” (page 178) for information on localizing bundle names. Also see the
chapter “Internationalization” (page 211) for more detailed information about the
naming of .lproj directories.
One very common resource type is a strings file (which, by convention, has an
extension of .strings). Strings files are used for character strings that must be
localized. They are essentially dictionaries that map a string in the development
language to the localized version of the string. The key is not required to be the
development language version of the string, but this convention is usually used.
System routines know how to locate and load the strings file (like any other
resource) and then look up the string you want all in one step. They also provide
caching so multiple lookups from the same table do not require locating and
loading the strings file again.
Bundles
Search Algorithm
The Figure 5-2 details the steps a system routine uses to locate a resource.
Bundles
Search
Search for
for aa
global resource
Global Resource
Resource
Resource Search for a resource matching
Yes found
Found No preferred region's language
Resource
Resource Search for a resource in
Yes found
Found No bundle's development region
Resource
Resource Search for a resource in
Yes found
Found No bundle's development language
Search
Search for
for aa
platform-specific
Platform Specific
resource
Resource
Return
Return the
the Return
Return the
the
platform-specific
Platform-Specific Resource
Resource platform-generic
Platform-Generic
resource
Resource Yes found
Found No resource
Resource
Bundles
Notice that global resources take precedence over localized resources. In fact, there
should never be both a global and localized version of a given resource. If there is a
global version of a given resource, localized versions of that same resource will
never be found. The reason for this precedence is performance. If the localizable
resources were searched first, the bundle routines might search needlessly in
several localized resource folders before discovering the global resource. Also
notice that in order to find a platform-specific resource, the platform-generic
version must exist. Again, the reason is performance. You should generally make
one platform’s version of the resource generic and provide platform-specific
versions for any other platforms.
Bundles
Localized.rsrc. This file is stored in the appropriate .lproj directory, one version
for each language or region. Be sure that the resources are stored in the file’s data
fork, not the resource fork.
If for some reason you are unable to convert your Carbon application to the bundle
scheme, you can include the information property list (Info.plist) in your
single-file application as a resource of type 'plst', id 0. See “CFM Executables”
(page 231) for more information.
6 Application Packaging
A typical application in Mac OS X is not a single executable file but a package of files
that includes one or more executable binaries. An application is a type of bundle—
a directory in the system that contains, in a hierarchical organization, the
application executable and the resources to support that code. An application is also
a file package, a directory that the Finder presents to users as a file.
The design of application packages arises from the recognition that a running
application is more than just the executable code that gets launched. Several
advantages come with this internal organization, among them ease of installation
and uninstallation, the inclusion of multiple localizations, support for multiple
architectures and volume formats, and the capability for a single application to run,
without modification, on Mac OS 9 and Mac OS X.
An Application Is a Bundle
Application Packaging
loadable bundles (such as plug-ins) are file packages, directories that the Finder
presents to users as a single file. The major distinguishing characteristic between the
types of bundles—applications, frameworks, plug-ins, and other dynamically
loadable packages of code and resources—is the nature of the executable.
Application executables are generally self-sufficient binaries that users can launch
from the Finder, usually by double-clicking. Applications may or may not contain
secondary bundles, such as plug-ins, but they always contain their main bundle.
Bundles bring a number of benefits that are either specific to applications or that
apply mostly to them:
■ The same (Carbon) application bundle can run, without modification, on Mac
OS 9 and Mac OS X.
■ Applications can include different localizations. Applications can automatically
display the set of localized resources (including the application name itself) that
matches a user’s language preference. Moreover, you can add a new localization
to the application package, and it displays those resources (if they are for a
preferred language) after the user relaunches the application.
■ Client computers can run applications on a server.
■ Customers can easily download applications from a website or obtain them
through email.
■ Applications are easy to install and uninstall; all the user must do is drag the
application package onto a volume or, for uninstall, drag it to the Trash. (This
feature does not preclude more complicated installations from taking place.)
■ Because applications are file packages, users cannot “break” them by removing
or changing essential parts of them. Users can, however, change the names of
applications without affecting them.
■ Applications can support multiple architectures as well as multiple volume
formats.
Application Packaging
As they do with other bundles, Apple’s development tools support the creation of
application packages.
For additional general information about bundles, see the chapter “Bundles”
(page 115). For further information about the Finder and its role in relation to
applications, see the chapter “The Finder” (page 189).
Applications sometimes have supplementary code modules—that is, code that isn’t
compiled into the application executable. This supplementary code may take the
form of a framework, a shared library (CFM or otherwise), a plug-in, a helper
application, or some other type of software.
There are various reasons for this compartmentalizing of application code. One is
efficiency; for example, a software developer might have a suite of applications that
all rely on the same framework or that make use of the same helper application,
such as a custom document viewer. Another reason is performance; an application
may decide to defer loading a module such as a plug-in until the user requests it. Or
an application may be designed from the outset to be extensible.
The frameworks and shared libraries in the application package are those needed
for the application to run, or at least to be complete. However, the application
package does not include the Apple-supplied frameworks to which the application
links. These are installed in the standard system location /System/Library/
Frameworks. Installers should not delete frameworks in an application package
or move them somewhere else; this includes frameworks that are shared (see
“Shared Frameworks and the Central Directory” (page 135) for the handling
of shared frameworks).
The application bundle has four directories for the various types of supplementary
code:
Application Packaging
Frameworks/
SharedFrameworks/
SharedSupport/
PlugIns/
The remainder of this section explains the purposes and issues related to the first
three of these directories. For a description of the PlugIns directory, see
“Applications and Loadable Bundles” (page 137).
Private Frameworks
The Frameworks directory contains frameworks (or shared libraries) that are
inextricably bound to the application. These frameworks are private to the
application. Only the application itself uses the frameworks in this directory, and
no other application does, including applications in the same “suite” or from the
same developer. The dynamic shared libraries of these private frameworks are
revision-locked and will not be superseded by any other, even newer, versions that
may be available to the operating system.
An application always uses the code in Frameworks whereas it may or may not use
the code in SharedFrameworks. If a framework or shared library is missing from
Frameworks, the application cannot launch.
Listing 6-1 illustrates how a typical private framework might be stored in the
application bundle.
FantasticApp.app/
Contents/
Info-macos.plist
MacOS/
Resources/
Frameworks/
GoodStuff.framework/
SharedFrameworks/
SharedSupport/
PlugIns/
Application Packaging
The inclusion of shared frameworks and other shareable software in the application
package contributes to application self-sufficiency. To install, relocate, or remove an
application, users simply drag the application icon and drop it in the appropriate
place. An application so installed might not use the most recent version of a shared
framework, but at least it should be able to execute with the frameworks packaged
with it. By keeping track of versioned frameworks within all application packages,
the central directory ensures that an application remains “read-only” and that
pieces of it are not duplicated all over a system. At the same time, the central
directory makes it possible for related applications to use the latest shared
frameworks installed on a system.
FantasticApp.app/
Contents/
Info-macos.plist
MacOS/
Resources/
Frameworks/
Application Packaging
SharedFrameworks/
GreatStuff.framework/
SharedSupport/
PlugIns/
FantasticSpreadsheet.app/
Contents/
Info-macos.plist
MacOS/
Resources/
Frameworks/
SharedFrameworks/
SharedSupport/
FantasticGrapher
PlugIns/
Application Packaging
Loadable bundles contain code and programming resources that an application can
dynamically load at runtime. The most common type of loadable bundle is a
plug-in, but there can be others, such as Interface Builder palettes. Loadable bundles
are somewhat different from frameworks and can have a slightly different relation
with applications.
Loadable bundles are bundles just as much as application packages. They can thus
contain all the things an application can, such as private frameworks, shared
frameworks, and other supplementary code, including other plug-ins and other
loadable bundles. (Frameworks, on the other hand, are “versioned” bundles with a
different internal organization, among other differences. See the chapter
“Frameworks” (page 141) for more information on frameworks.)
Plug-ins and other loadable modules are divided into three categories based on how
essential they are to an application:
■ those that an application requires to run
■ those that are not essential to execution but that are considered part of an
application because users generally want to use them (a tools palette, for
example)
■ those that meet neither of the above criteria but offer some additional
functionality (often provided by third-party developers)
Plug-ins and other loadable bundles that meet the first two criteria should be
packaged in the PlugIns directory of the application bundle. They should always be
packaged with the application so they come along if the user moves the application
to another location. If a loadable bundle is in the third category, the convention for
users is to install it in the Library/Application Support directory of the logged-in
user’s home directory (local or remote). System administrators or expert users can
install such a loadable bundle in the Library/Application Support directory of the
system-local or network domains to make it more widely available.
Application Packaging
An application can come packaged with a variety of resources. These resource can
range from those that are closely tied to the application’s executable, such as sound
files and localized strings, to more “external” resources such as application help,
preferences, and clip art. Resources are typically stored in the Resources directory
of the application bundle.
However, application resources might not be stored in the application package for
a variety of reasons. One reason for this separation is to make it possible for
applications to run in a net-booted environment. Other reasons are to make the
resources accessible in the file system and to separate resources provided by
third-party contributors from those provided by the application’s developer. The
following sections give information about the preferred locations for several types
of resources.
Application Help
On Mac OS X, the Help Viewer application displays help information for
applications as well as more general help. (Help Viewer is part of the Apple Help
product.) You should store application help files in the appropriate location in the
application’s Resource directory. You put the files in a help book, which is also the
standard format for help in Mac OS 9. You internationalize help books by localizing
their contents (text and images) and putting them in .lproj directories in the
application bundle’s Resource directory. The text files must be HTML 3.2-compliant
and otherwise conform to the specification for Apple Help books. See Inside Carbon:
Providing User Assistance With Apple Help for instructions on preparing and indexing
help files.
Application Packaging
Although Apple strongly recommends that you put help for an application in an
application bundle, you can also put application help as well as more general help
outside the application package. Such help should go in one of the standard
locations for third-party help, including /Library/Documentation/Help and Library/
Documentation/Help in a user’s home directory. When the user launches the Help
Center from the Finder, Help Viewer scans these locations and displays a link to the
application help. If your application help is installed in one of the standard locations
for help, you do not need to specify any special key-value pairs in the application’s
information property list for Help Viewer to handle it.
Application Preferences
Applications typically are installed with a default set of preferences that users can
then change to suit their working habits. Part of any application’s code is devoted
to displaying the range of preference options, accepting user choices, and writing
these choices to the preferences system (see “The Preferences System” (page 205) in
the chapter ““Software Configuration” (page 199)”).
Your application should never write user-preference data inside the application
package. Preferences are stored in the Library/Preferences directory of the
logged-in user’s account (local or network) or in the same location in the
machine-local or network domains. You should never write preferences data
directly to these locations; instead use the APIs offered by Core Foundation
Preference Services (CFPreferences) or, for Cocoa applications, NSUserDefaults.
Part of the reason for the separation of user preferences from the application
package is to make it possible for applications to run in a net-booted environment.
Application Packaging
Document Resources
Applications that are document-centric—word processors, spreadsheets, drawing
applications, to name a few—often include resources such as templates, clip art,
tutorials, and assistants. These items can either be packaged in the application
bundle or in a location external to the application package. The rule of thumb for
deciding where such a resource goes is similar to that for plug-ins and other
loadable bundles (see “Applications and Loadable Bundles” (page 137):
■ If the resource is provided by the application developer, it should go in the
SharedSupport directory of the application bundle.
■ If the resource is from a third party, it should go in one of the standard directory
locations for application resources, such as in the user’s Library/Application
Support folder.
As with loadable bundles, the application should provide some kind of resource
browser that displays application resources (both internal and external to the
package) and allows the user to select from them. The browser, however, should not
divulge the inner structure of the application package.
7 Frameworks
A framework bundle has an extension of .framework. Inside the bundle there can be
multiple major versions of the framework. A network of symbolic links at the top
level of the framework folder points to the most recent versions of library code and
resources. The dynamic link editor writes the directory location in which to install
a framework into the framework executable. When a program is launched, if the
dynamic link editor cannot find a framework in this location, it looks in the
standard directory locations for the framework. System and third-party
frameworks are often installed in standard directory locations. Third-party
frameworks can also be included in application packages that need those
frameworks.
Frameworks can have major (or incompatible) versions and minor (or compatible)
versions. The major versioning scheme provides for backward compatibility.
Frameworks that are incompatible with programs linked with a previous version of
the library are given a new major version. Those programs must link with an earlier
141
Apple Computer, Inc. July 2002
C H A P T E R 7
Frameworks
version, which is kept inside the framework bundle. The minor versioning scheme
provides for forward compatibility. A major version of a framework can
incorporate a number of minor versions. A minor version denotes the framework
compatibility of programs linked with later builds of the framework.
When libraries are installed in some computing environments, they are put in one
location in the file system and resources related to that code are installed elsewhere.
These related resources include header files as well as things such as images and
localized strings. This scattering of code and resources can contribute to several
problems:
■ It complicates uninstallation of the library and its resources.
■ It leads to a greater risk of mismatches between libraries and header files.
■ It can make it more difficult for library code to locate resources.
Frameworks solve this problem by bundling a dynamic shared library with the
resources used by the library or otherwise related to it. Indeed, “bundling” is an apt
term because frameworks are bundles as much as applications and plug-ins are.
However, frameworks differ in some significant ways from other types of bundles:
■ Frameworks include a unique type of resource—header files. They can also
contain as a resource anything else that is appropriate, such as private static
libraries.
■ The bundle bit is not set when a framework is built. As a result, the Finder does
not treat the framework as a file package—a directory presented as a file—and
thus developers can browse the packaged header files.
■ Frameworks are versioned bundles, which are described in “The Internal
Structure of Frameworks” (page 143).
Frameworks
Versioned bundles have an internal structure derived from Mac OS X Server (and
prior) bundles. Apple will eventually convert frameworks to the new internal
structure. Until then, Mac OS X will support both styles of bundles; the system
routines for bundles can deal with both versioned bundles and the more recent type
of bundles.
GreatSoftware.framework/
GreatSoftware
Headers/
PrivateHeaders/
Resources/
Versions/
The GreatSoftware item is, in this example, the dynamic shared library. Headers and
PrivateHeaders are subdirectories that store the framework’s public and private
header files. The framework’s resources—items such as interface definition files,
images, sounds, and localized strings—go in the Resources subdirectory.
The Versions subdirectory is the only one at this level that is a “real” directory.
GreatSoftware, Headers, PrivateHeaders, and Resources are all symbolic links
(similar to aliases) to the library and directories of the current major version of the
framework. Figure 7-1 illustrates how this linking is done.
Frameworks
Links to contents
of Current
Links to
most recent
Frameworks
French.lproj. The .lproj directories hold strings, images, sounds, and interface
definitions localized to that language and locale. An important way in which
frameworks differ from new-style bundles is that nonlocalized resources in
frameworks do not go in a Nonlocalized Resources subdirectory of Resources;
instead, they are put in the top level of the Resources directory.
■ If they are to be used by all users of a particular Mac OS X system, they should
be installed in /Library/Frameworks.
■ If they are to be used across a local area network, they should be installed in
/Network/Library/Frameworks.
When you build an application or other executable, the compiler looks for imported
frameworks in/System/Library/Frameworks as well as any other location specified to
the compiler. The paths where required frameworks are expected to be installed are
written into the executable itself, along with version information.
When an application is run, the dynamic link editor first tries to link with the
frameworks whose installation paths are written into the executable. If it cannot
find a framework in a specified location (perhaps it has been moved or deleted), it
looks for frameworks in these standard fallback locations, in this order:
~/Library/Frameworks
/Library/Frameworks
/Network/Library/Frameworks
/System/Library/Frameworks
If the dynamic link editor cannot locate a required framework, it generates a link
edit error and the application will not launch.
Frameworks
Note: Although you can create dynamic shared libraries that reside outside a
framework, this is an uncommon approach. Stand-alone dynamic shared
libraries take, by convention, the extension .dylib and typically are installed in
the standard file-system locations for libraries.
Dynamic shared libraries have characteristics that set them apart from statically
linked shared libraries. With dynamic shared libraries, the binding of undefined
symbols in a program is delayed until the execution of that program. In other
words, the dynamic link editor not only attempts to resolve all undefined symbols
at runtime, but attempts to do so only when those symbols are referenced during
program execution. If an undefined symbol is not referenced, the binding is not
needed for that particular execution of the program.
This dynamic behavior derives from the composition of dynamic shared libraries.
The object-code modules from which a dynamic shared library is built retain their
individual boundaries; that is, the code from the source modules is not merged into
a single code base. When a program linked with a dynamic shared library is
launched, the dynamic link editor automatically loads and links modules in the
library, but it links them only as they are needed; in other words, a module is linked
only if a symbol is referenced or a function is invoked that is defined in that module.
If code in a module is not referenced or invoked, the module is not linked. Figure
7-2 illustrates this “lazy linking” behavior. In this example, module a.o is linked in
the program’s main routine when library function a is called; module b.o is linked
when library function b in program function doThat is invoked; module c.o is never
linked because its function is never called.
Frameworks
MyApp.app Boffo.framework
main.c
......
#include <Boffo/Boffo.h>; a.o ........ #include "a.h";
#include "main.h";
#include "doThat.h";
void a() {
...
int main() { links ........ }
a(); ......
doThat(1);
return 0;
......
} b.o ........ #include "b.h";
...
void b() {
doThat.c ...
........ }
......
#include <Boffo/Boffo.h>;
#include "doThat.h";
......
void doThat (int n) { links
c.o ........ #include "c.h";
b();
if (!n); void c() {
c(); ...
} ........ }
......
As a framework developer, you should design your dynamic shared library with
this as-needed linking of separate modules in mind. Because the dynamic link
editor always attempts to bind unresolved symbols within the same module before
going on to other modules and other libraries, you should ensure that
interdependent code is put in its own module. For example, custom allocation and
deallocation routines should go in the same module. This technique prevents the
wrong symbol definitions from being used. This problem can occur when
definitions of a symbol exist in more than one dynamic shared library and those
other symbol definitions override the correct one.
When you create a framework, you must ensure that each symbol is defined only
once in a library. In addition, “common” symbols are not allowed in the library; you
must use a single true definition and precede all other definitions with the extern
keyword in C code.
Frameworks
When you build a program, linking it against a dynamic shared library, the
installation path of the library is recorded in the program. For the system
frameworks supplied by Apple, the path is absolute. For third-party frameworks,
the path is relative to the application package that contains the framework. This
capture of the library path improves launching performance for the program.
Instead of having to search the file system, the dynamic link editor goes directly to
the dynamic shared library and links it into the program. This means, obviously,
that for a program to run, any required library must be installed where the recorded
path indicates it can be found, or it must be installed in one of the standard fallback
locations for frameworks and libraries.
Dynamic shared libraries can have dependencies on other dynamic shared libraries
and these dependencies are recorded in the library executable. When the dynamic
link editor links a program against the first dynamic shared library, it can obtain the
paths of these dependent libraries and link against those as well. Thus the users of
a dynamic shared library do not have to be aware of any dependencies when
linking their programs against it.
Framework Versioning
You can create different versions of frameworks based on the type of changes made
to their dynamic shared libraries. There are two types of versions: major (or
incompatible) and minor (or compatible) versions.
Major Versions
A major version of a framework, also known as an incompatible version, is
incompatible with programs linked with a previous version of the framework’s
dynamic shared library. If any such program tries to run against the newer version
of the framework, it will probably experience runtime errors.
Frameworks
Because all major versions of a framework are typically kept within the framework
bundle, a program that is incompatible with the current version can still run against
the version it is compatible with. The path of each major version of a framework
encodes the version (see “The Internal Structure of Frameworks” (page 143)). For
example, the letter “A” in the path below indicates the major version of a
hypothetical framework:
/System/Library/Frameworks/Boffo.framework/Versions/A/Boffo
When the program is built, this path is recorded in the program executable itself.
When the program is run, the dynamic link editor uses this path to find the
compatible version of the framework’s library. Thus the major versioning scheme
enables backward compatibility of a framework by including all major versions and
recording the major version for each executable to run against.
You should make a new major version of a framework when any of the following
changes renders the dynamic shared library incompatible with programs linked
with previous versions of the library:
■ removing public API, such as a class, function, method, or structure
■ renaming public API
■ changing the data layout of a structure or adding to, changing, or reordering the
instance variables of a class
■ adding methods to a C++ class
■ changing the programmatic interfaces of public API
An example of the last sort of change would be changing the order of parameters in
a function.
The most recently built major version of a framework is typically made the
“current” version. Unless you specify otherwise, each program you build is linked
against the current version of a library; older programs that you rebuild are
linked against the current version as well. When frameworks are built, the build
system automatically generates a network of symbolic links that point to the current
major version of a framework. See “The Internal Structure of Frameworks”
(page 143) for details.
When you create a new major version of a framework, your integrated development
environment takes care of most of the implementation details for you. All you need
to do is specify the major-version designator. A popular convention for this
Frameworks
designator is the letters of the alphabet, with each new version designator
“incremented” from the previous one. However, you can use whatever convention
is suitable for your needs, for example “2.0” or “Two”.
You can also make major incompatible versions of stand-alone dynamic shared
libraries (that is, libraries not contained within a framework bundle). The major
version of this type of library is encoded in the filename itself, for example:
libMyLib.B.dylib
Then, assuming that this library is the most recent major version, the symbolic link
libMyLib.dylib is created to point to it. This creates the current major version of the
dynamic shared library.
Minor Versions
Within a major version of a framework there can be a series of minor, or compatible,
versions. The minor versioning of a framework determines its compatibility with
programs linked with later builds of the framework within the same major version.
The minor versioning scheme thus helps to establish forward compatibility. If
programming interfaces have been introduced to a recent version of a framework,
programs that are built against this framework may not work with earlier minor
versions of the framework. The program might have references to those new APIs
and thus, if it is launched, it would probably crash with link-edit errors. Minor
versioning gives framework developers control over how old a version of the
framework can be used with an executable linked with a more recent version.
The relationship between two version numbers—the current version and the
compatibility version—specifies a framework’s minor-version status in relation to
a particular program. The current version of a framework is a number that is
incremented each time a framework is rebuilt after a compatible change is made to
it (that is, a change not requiring a new major version).
The type of change introduced in a framework affects the value of the second minor
version number, the compatibility version. If the change is merely a bug fix or an
enhancement that does not affect any public API, the compatibility version is left
unchanged from its current value. If, however, you have added classes, methods,
functions, structures, or any other public API to the framework, the compatibility
version number should be set to the same value as the current version number.
Frameworks
Important
The addition of instance variables to Objective-C or C++
classes or the addition of C++ methods constitutes a major
incompatible change, not a minor compatible change.
When a framework is built or rebuilt, its current version number and its
compatibility version number are recorded in the framework’s dynamic shared
library. When you build a program that links against this framework, these same
numbers are encoded in the program executable, along with the path of the
framework (which contains the major version designator). When you try to run the
program, the dynamic link editor compares the program’s compatibility version
number and the framework’s compatibility version number; if the program’s
compatibility version is greater than the framework’s compatibility version, the
program does not launch.
Frameworks
Table 7-1 summarizes the salient facts about each type of version.
The otool command-line program displays output that can give you an idea of how
versioning information is recorded in a program executable. To use this program,
change directories to any Mac OS X application and enter the following in a
Terminal shell: otool -L appName where appName is the name of the application.
If you don’t change the framework’s major version number when you need to,
programs linked with it will fail in unpredictable ways. If you change the major
version number and you don’t need to, you’re cluttering up the system with
unnecessary frameworks.
Frameworks
The main trick is to avoid having to change the version number in the first place.
Here are some ways to do this:
■ Pad classes and structures with reserved fields. Whenever you add an instance
variable to a public class, you must change the major version number because
subclasses depend on a superclass’s size. However, you can pad a class and a
structure by defining unused (“reserved”) instance variables and fields. Then, if
you need to add instance variables to the class, you can instead define a whole
new class containing the storage you need and have your reserved instance
variable point to it.
Keep in mind that padding the instance variables of frequently instantiated
classes or the fields of frequently allocated structures has a cost in memory.
■ Don’t publish API unless you want your users to use it. You can freely change
private API because you can be sure no programs are using it. Declare any API
in danger of changing in a private header.
■ Don’t delete things. If a method or function no longer has any useful work to
perform, leave it in the API for compatibility purposes. Make sure it returns
some reasonable value. Even if you add additional arguments to a method or
function, leave the old form around if at all possible.
■ Remember that if you add API rather than change or delete it, you don't have to
change the major version number because the old API still exists. The exception
to this rule is instance variables. (You do have to change the compatibility
version number, however.)
When you do a “make clean” with your integrated development environment, you
delete the entire framework bundle in the project directory, which means it deletes
the old binaries in addition to the current binary. The subsequent build creates only
the current version. You have no way of retrieving the earlier versions. If you must
perform a make clean, you’ll need to create multiple copies of the project: one that
builds the current version and one for each of the previous versions.
Frameworks
8 Umbrella Frameworks
An umbrella framework is a public system framework that includes and links with
constituent subframeworks and other public frameworks provided by Apple. A
subframework is a public but restricted system framework that typically packages
a specific Apple technology such as Open Transport or QuickDraw.
This chapter describes the various kinds of private and public frameworks,
defines umbrella frameworks and subframeworks, illustrates the internal structure
of umbrella frameworks, and offers guidelines for linking with umbrella
frameworks.
155
Apple Computer, Inc. July 2002
C H A P T E R 8
Umbrella Frameworks
Kinds of Frameworks
Third, the public frameworks that Apple ships with Mac OS X come in three
varieties: the simple kind of public framework, the subframework, and the umbrella
framework. These frameworks are installed on the installation hard disk in /System/
Library/Frameworks. Public frameworks in this directory may be of the simple
sort—that is, neither umbrella framework or subframework—only if they have
been widely used in prior versions of the operating system, such as Mac OS X
Server. The Cocoa application environment’s Foundation and Application Kit
frameworks fall into this category.
Umbrella Frameworks
Umbrella Frameworks
Figure 8-1 The relationship between an umbrella framework and its subframeworks
Subframeworks
Subframework1
Subframework2
Umbrella framework
...
Carbon
Core Services Umbrella framework
#includes
Subframeworks
Carbon application
Core Foundation
OSStatus err;
err =
InitOpenTransport(void); dynamically loads Open Transport
...
The value of an umbrella framework is that, by linking with it and only it, you can
be assured that you have access to all the APIs necessary for programming in a
particular application environment or layer of system software. Umbrella
frameworks hide the complex cross-dependencies among the many different pieces
of system software. Thus you do not need to know what set of frameworks and
libraries you must import to accomplish a particular task. Umbrella frameworks
also make faster builds possible because a precompiled header is included along
with any umbrella header file or framework header file.
Umbrella Frameworks
For Mac OS X software developers the guideline for including header files and
linking with system software is fairly straightforward: Include only the umbrella
header file and link only with the umbrella framework appropriate to the program
you are creating.
An umbrella header file includes the framework header files of its subframeworks.
A framework header file (such as in a subframework) includes all the header files
of the framework. You should never directly include the header files from
subframeworks or link directly with them (and, in fact, you are prevented from
doing so).
The general syntax of the command for including framework header files in
Mac OS X is
#include <Framework/Header.h>
Where Framework is the name of the framework and Header is the name of a header
file.
Note: For Objective-C projects, the #import directive may be used instead of
#include; this directive is identical to #include, except that it makes sure that the
same file is never included more than once.
To specify umbrella frameworks when developing software for Mac OS X, use the
same #include syntax that is used for framework header files. In other words, to
specify the Carbon umbrella framework, use the following command:
#include <Carbon/Carbon.h>
However, Apple provides an interim solution for Carbon developers porting their
source code from Mac OS 9 to Mac OS X or otherwise writing code to be built on
both operating systems. This “flat header” alternative allows them to continue
using their present #include commands. In /Developer/Headers/FlatCarbon are stub
files for all public Mac OS 9 header files. These stub files redirect the compiler to the
Umbrella Frameworks
appropriate umbrella header file or contain warnings if the API is not valid on
Mac OS X. To make use of the stub files, you must use the compiler’s -I flag (that is
capital “I”, not lowercase “l”) to include the files in the FlatCarbon folder:
-I/Developer/Headers/FlatCarbon
Once you are only compiling code for Mac OS X, you should start using the native
syntax for including umbrella frameworks. (As a side effect of doing this, build time
will decrease.) You can also conditionalize your #include commands so that they
include umbrella frameworks directly (for example, #include <Carbon/Carbon.h>)
when you are building on Mac OS X and include flat headers (for example, #include
<Dialogs.h>) when you are building on Mac OS 9. This conditional approach
obviates the need for the -I flag.
The book Inside Carbon: Carbon Porting Guide contains a more detailed discussion of
the flat-header #include technique. Also see “The Structure of an Umbrella
Framework” (page 160) for more information about umbrella header files.
Do not worry about bloating your program’s memory footprint by linking it with
an umbrella framework and including its (potentially) dozens of header files.
Because the executable code of a framework is a dynamic shared library, a
subframework’s code is loaded into memory only when one of its functions or
methods is first called. If your program does not use a subframework, it is not
loaded. See “Dynamic Shared Libraries” (page 146) in the chapter ““Frameworks”
(page 141)” for more on this subject.
Two things determine the structure of an umbrella framework. The first is the
manner in which it includes header files. The second is how it, as a bundle directory,
organizes its subframeworks.
The #include examples in the previous section suggests how umbrella header files
and framework header files are used to accomplish the level of abstraction afforded
by umbrella frameworks. To reiterate, the general syntax of the #include command
for including framework header files and umbrella header files is
Umbrella Frameworks
#include <Framework/Header.h>
In this convention, the framework and the umbrella header file have the same name.
An umbrella header file includes the framework header files of its subframeworks.
For example, the umbrella header for the Core Services umbrella framework,
CoreServices.h, has contents similar to the following:
#include <CoreFoundation/CoreFoundation.h>
#include <OT/OT.h>
#include ...
The framework header file includes all the header files defining the public interface
of a particular technology. CoreFoundation.h, for example, is the framework header
for the Core Foundation subframework (CoreFoundation.framework). Its contents
are similar to the following:
#include <CoreFoundation/CFBase.h>
#include <CoreFoundation/CFArray.h>
#include <CoreFoundation/CFBag.h>
#include ...
Umbrella.framework/
Headers@ -> Versions/Current/Headers/
PrivateHeaders@ - > Versions/Current/PrivateHeaders/
Resources@ -> Versions/Current/Resources/
Umbrella@ -> Versions/Current/Umbrella
Versions/
Frameworks/
SubFW1.framework/
SubFW1@ -> Versions/Current/SubFW1
Headers@ -> Versions/Current/Headers/
PrivateHeaders@ -> /Versions/Current/PrivateHeaders/
Resources@ -> Versions/Current/Resources/
Versions/
Umbrella Frameworks
SubFW2.framework/
SubFW2@ -> Versions/Current/SubFW2
Headers@ -> Versions/Current/Headers/
PrivateHeaders@ -> /Versions/Current/PrivateHeaders/
Resources@ -> Versions/Current/Resources/
Versions/
There are a couple of things to note about the structure of frameworks in general:
■ The PrivateHeaders directory contains header files used in internal development
and is not shipped to customers.
■ Aside from the umbrella framework’s Frameworks directory, the Versions
subdirectory of a framework is the only “real” one—that is, the only directory at
that level that isn’t a symbolic link. It contains the major versions of a
framework. The Current directory is a symbolic link that typically points to the
most recent version. For more on the general structure of frameworks, see “The
Framework as a Library Package” (page 142) in the chapter ““Frameworks”
(page 141).”
Mac OS X includes two mechanisms for ensuring that developers link only with
umbrella frameworks. One mechanism is triggered when you attempt to include
subframework header files. The other mechanism prevents linking with
subframeworks.
If, as an external developer, you try to link with a subframework, the linker causes
the link to fail and displays a message explaining why. For example, if you try to
link directly with the Open Transport framework (OT.framework), the link fails and
the linker prints the following message: “OT.framework is a subframework. Link
against the umbrella framework CoreServices.framework instead.”
Umbrella Frameworks
If you try to include a header file that is in a subframework, you get a compile-time
error message. The umbrella header files and the subframework header files
contain preprocessor variables and checks to guard against the inclusion of
subframework header files. If you compile your project with an improper #include
statement, the compiler generates an error message.
Umbrella Frameworks
This chapter looks at file systems from both perspectives and discusses topics that
are of interest to software developers. First it describes the standard directory
layout in Mac OS X—where things like applications, documents, frameworks, and
resources go in a multiuser, networked computing environment. Then it describes
differences and issues of interoperability between the various file systems,
particularly the dominant ones: HFS+ and UFS. It also explains the implementation
of HFS resource forks and the policies related to this implementation.
In Mac OS X almost every file in the file system has its proper place—a standard
directory location for files of that type. For users, this doesn’t mean they must put
their applications and application resources in the recommended locations.
Applications, after all, are packaged so they can be self-sufficient wherever they’re
installed. But if users do not put certain things where system software expects them,
they lose some advantages of Mac OS X. For example, the Finder first populates an
application database by looking in the standard locations for applications
(“Collecting Application Information” (page 192)). As a result, a document
belonging to an application that is not in one of those locations might not
immediately open when double-clicked.
Before exploring the rationale behind the file-system organization, consider what
the Finder displays at the top level of the file system. Listing 9-1 illustrates a
hypothetical installation.
/Mac OS X/
/Network/
/OtherVolumes/
The layout of a file system is often represented as a hierarchical tree structure that
begins at a “root.” At the root of a typical Mac OS X file system (root indicated by
an initial /) are the following items:
■ /Mac OS X/—The volume from which the operating system boots and on which
system software and resources are installed. This volume is typically a hard disk
formatted to be a Mac OS Extended (HFS+) volume (although it can be a UFS
volume). The name “Mac OS X” is the default volume name, which users can
change.
■ /Network/—The root of the local area network, as mounted on the user’s system.
The /Network/ directory (whose icon is a globe) always appears whether the user
is connected to a network or not.
■ /OtherVolumes/—Represents one or more externally connected devices or
internal devices that are not the boot volume. This includes items such as Zip
drives, CD-ROM drives, digital cameras, and mounted network servers as well
as hard disks and their partitions. (The name “OtherVolumes” is only
representative; the actual name of each connected volume will be different.)
All non-boot volumes appear as they are mounted and disappear when they are
unmounted. An exception to this is the user’s iDisk volume, which appears even
when it is unmounted.
The physical organization of volumes is somewhat different than what the Finder
presents to the user. If you were to look at the directory structure using the Terminal
application, you would see that the boot volume is mounted at the root level (/) and
non-boot volumes are located in /Volumes/. The Finder provides this abstraction to
provide a more traditional Mac OS interface on top of the underlying UNIX system.
Also at the root level, but hidden from users by the Finder, are the standard BSD
directories such as /usr, /bin, and /etc.
File-System Domains
On a multi-user system, controlling access to system resources is important for
maintaining the stability of the system. Mac OS X defines several file system
domains, each of which provides storage for resources in an established set of
directories. Access to resources in each domain is determined by the permissions for
the current user.
There are four file system domains, each of which is described in the following list:
■ User. The user domain contains resources specific to the user who is logged into
the system. This domain is defined by the user’s home directory, which can
either be on the boot volume (/Mac OS X/) or on the network. The user has
complete control of what goes into this domain.
■ Local. The local domain contains resources such as applications and documents
that are shared among all users of a particular system, but which are not needed
for that system to run. The Local domain does not correspond to a single
physical directory, but instead consists of several directories on the local boot
(and root) volume. Users with system administrator privileges can add, remove,
and modify items in this domain.
■ Network. The network domain contains resources such as applications and
documents that are shared among all users of a local area network. Items in this
domain are typically located on network file servers and are under the control
of a network administrator.
■ System. The system domain contains the system software installed by Apple.
The resources in the system domain are required by the system to run. Items in
this domain are located on the local boot (and root) volume. Users cannot add,
remove, or alter items in this domain.
The domain for a given resource determines its applicability or accessibility to the
users of the system. For example, a font installed in the user’s home directory is only
available to that user. If an administrator were to install the same font in the
network domain, all network users would have access it.
Within each domain Mac OS X provides a set of initial directories for organizing the
contained resources. Mac OS X uses identical directory names across domains to
store the same types of resources. This consistency simplifies the process of finding
resources both for the user and for the system methods that use those resources.
When the system needs to find a resource, it searches the domains sequentially until
it finds the resource. Searches start in the User domain and proceed through the
Local, Network, and System domains in that order.
Your code should never assume the path to a resource within a file-system domain,
as those paths could change in the future. Apple provides public APIs for accessing
standard file system paths. You should always use these APIs to locate system
resources. See “Searching Within the File-System Domains” (page 177) for more on
searching for items within the domains.
The following sections describe each of the file system domains in more detail,
including some of the standard directories available in that domain.
The user domain makes a customized working environment possible for each user.
When a user logs in, the Finder restores the user’s working environment and
settings to their previous state using the preferences in the user domain. Similarly,
programs and other system software use information in the user domain to restore
application preferences, network settings, email settings, font sets, ColorSync
profiles, and other settings.
The location of the user’s home directory—user domain—is dependent on the user
account. If the user account is local to the computer, the user’s home directory is in
the Users directory on the boot volume. If the user account is a network account, the
home directory is on a network server. Regardless of the physical location of the
home directory, Mac OS X uses the UNIX convention of a ~ (tilde) character in some
situations to indicate a user’s home directory. The tilde character can be used in
combination with other directory or user names to specify specific user directories.
Table 9-1 illustrates this concept.
The home directory for each new user comes with some default directories and
resources in place. The directories in a user’s home directory mirror those found in
iDisk accounts. (For more information on iDisk, see the iTools section of http://
www.apple.com.) The default directories in a user’s home directory are the same
regardless of where the home directory is created. Table 9-2 (page 169) lists the
standard subdirectories of a user’s home directory:
The system protects the files and directories in the user’s home directory from
outside interference by a set of default permissions, which the user may change at
any time. Any new folders created by the user inherit the privileges of the parent
directory.
In addition to the individual home directories, the Users directory contains a Shared
subdirectory. This directory is accessible to any user of the local computer system.
Any user can write documents to, retrieve documents from, and read documents in
this directory. Although this directory is not really associated with the user domain,
it provides a convenient means for users to exchange documents and other files.
Administrators of a computer can install resources into the local domain if they
want those resources to be shared by all users of the system. Apple ships its
applications in the /Applications and /Applications/Utilities directories. Third
party applications and utilities should also be placed in these directories. Other
system resources, such as fonts, ColorSync profiles, preferences, and plug-ins
should be placed in the appropriate subdirectory of the Library directory. For more
on the Library directory, see “The Library Directory” (page 172).
Table 9-3 lists the standard directories available in the Network domain, along with
a description of the directory contents.
Location Description
/Network/Applications Contains applications that can be run by all users on
the local area network.
/Network/Library Contains resources—such as plug-ins, sound files,
documentation, frameworks, colors, and fonts—
available to all users of a local area network. For more
on the Library directory, see “The Library Directory”
(page 172).
/Network/Servers Contains the mount points for NFS file servers that
make up the local area network.
/Network/Users/ Contains the home folders for all local-area network
users. This is the default location for home folders. User
home folders may also be stored on other servers.
Table 9-4 lists some of the directories that can appear in a Library directory. This list
is not complete, but it lists some of the most relevant directories for developers.
Directories that do not appear in all domains are noted appropriately.
Directory Contents
Applications Applications used to manage and build software projects
(Project Builder), to create user interfaces (Interface
Builder), and to performance-tune programs.
Documentation Developer documentation.
Examples Example projects organized by general type (Carbon,
Java, and so on).
Headers Special header files, such as the stub “flat” Carbon
headers.
Java Files needed for Java bridging in the Cocoa application
environment.
Makefiles Makefiles and jamfiles for building and converting
projects.
Palettes Apple-supplied Interface Builder palettes.
PBBundles Loadable bundles used by Project Builder.
ProjectBuilder Project Builder templates and plug-ins.
Extras
Project Builder defines a set of makefile variables that your projects should use
when specifying locations within file-system domains. You should use these
variables instead of hard-coding directory paths because those locations are subject
to change. For a complete list of build settings (including the makefile variables), see
the Project Builder Help.
When you install Mac OS 9.1 (or later) on a volume, the installer creates several
directories to store the system files. Table 9-6 lists the directories created by the
installer along with a description of the contents. If you already have a version of
Mac OS X or Mac OS 9.1 (or later) installed, the Mac OS 9 installer may not create all
of these directories.
Table 9-6 Directories created by the Mac OS 9.1 (or later) installer
Directory Description
Applications (Mac OS 9) Contains the Mac OS 9 (Classic) applications and
utilities.
Documents Contains application-specific information. This
directory should be used only by Classic
applications. Mac OS X applications should store
preferences and other application files in the
appropriate /Library directory. Users should store
their documents in their home directory.
System Folder Contains the Classic environment system files.
When you install Mac OS X on a system with Mac OS 9 already installed, the
installer performs some additional tasks to support the Classic environment. In
particular, the Mac OS X installer creates an alias to the Mac OS 9 desktop folder and
puts it on the desktop of the administrative user who ran the installer. This alias
contains links to any files that were on the Mac OS 9 desktop prior to the Mac OS X
installation.
Both APIs help you search through all file-system domains for a particular item. By
convention, searches typically begin with the most specific domain and end with
the most general. This domain order is as follows:
1. User
2. Local
3. Network
4. System
Most system software follows this order when it searches for items through all
file-system domains. However, you may search in any domain order that is
appropriate to your application’s needs.
Each file in the file system now has a special flag identifying whether the file’s
extension is hidden or shown. This setting affects only the way the file is displayed;
it does not physically change the name of the file in the file system. Users can change
this setting for individual files from the Info panel of the file. Users can also hide all
filename extensions by modifying the Finder preferences.
Applications that display filenames as part of their user interface must use special
routines for getting the display name of a file. The Launch Services methods
LSCopyDisplayNameForRef and LSCopyDisplayNameForURL take the file extension flag
into account when returning a file name, as does the NSFileManager method
displayNameAtPath. Your application should use these methods only when
displaying the file in your user interface. Any other internal file manipulations
made by your application should always use the full file name.
Both Carbon and Cocoa enable filename extension hiding in the corresponding Save
dialogs. In Carbon, you can set the kNavPreserveSaveFileExtension dialog option
for the Navigation Services save dialog. For Cocoa, you can use the
setCanSelectHiddenExtension: method of NSSavePanel to enable this feature. For
more information, see the Carbon and Cocoa references.
retain their default names. Now, select file system names change to match the
currently selected language. The result allows users to navigate more of the file
system hierarchy in their native language.
Important
Mac OS X does not support localized bundle and directory
names in the Darwin and Classic environments, nor does
Mac OS X support the localization of flat files.
Mac OS X provides several functions for obtaining the localized name of a path.
Your application should always use one of these functions to convert a path to its
localized name immediately prior to display. In addition to localizing appropriate
directory and bundle names, these methods also hide file extensions when called for
by the current file and Finder settings. The Launch Services methods
LSCopyDisplayNameForRef and LSCopyDisplayNameForURL convert paths to their
localized formats, as does the NSFileManager method displayNameAtPath.
file, which stores localized values for special keys. To specify a localized name for
your bundle, include the CFBundleDisplayName key in this file and set the value
to the localized name of the bundle.
The rules for supporting localized bundle names applies to all bundles, including
applications and frameworks. For more information on bundles, see “Bundles”
(page 115).
To localize a directory name, you must add the extension .localized to the
directory name and mark the extension as hidden by default. Inside your directory,
you then create a subdirectory called .localized. Inside of this subdirectory, create
a strings file for each localization you wish to support. The strings file contains a
single entry with the localized version of the directory name. For example, a
localized Release Notes directory with English, Japanese, and German localizations
would have the following structure:
Release Notes.localized/
.localized/
en.strings
de.strings
ja.strings
Inside each of the strings files, you would map the non-localized directory name to
the localized name. For example, to map the name “Release Notes” to a localized
directory name, each strings file would have an entry similar to the following:
There are many significant differences between the two major file systems on
Mac OS X: HFS+ and UFS. In many cases, these differences have some bearing on
programs developed for Mac OS X. The following list summarizes the major
differences between these file systems (many of these statements apply to HFS as
well as HFS+):
■ Case sensitivity. UFS is sensitive to case; although HFS+ is case-insensitive it is
case-preserving.
■ Multiple forks. HFS+ supports multiple forks (and additional metadata)
whereas UFS supports only a single fork. (Carbon simulates multiple forks on
file systems that do not support them, such as UFS.)
■ Path separators. HFS+ uses colons as path separators whereas UFS follows the
convention of forward slashes. The system translates between these separators.
■ Modification dates. HFS+ supports both creation and modification dates as file
metadata; UFS supports modification dates but not creation dates. If you copy a
file with a command that understands modification dates but not creation dates,
the command might reset the modification date as it creates a new file for the
copy. Because of this behavior, it is possible to have a file with a creation date
later than its modification date.
■ Sparse files and zero filling. UFS supports sparse files, which are a way for the
file system to store the data in files without storing unused space allocated for
those files. HFS+ does not support sparse files and, in fact, zero-fills all bytes
allocated for a file until end-of-file.
■ Lightweight references to file-system items. See “Aliases and Symbolic Links”
(page 182).
In addition, the APIs historically associated with each file system sometimes have
different behaviors. For example, a program using BSD (or BSD-derived) APIs can
delete a file that is open; on the other hand, a Carbon program may only delete a file
that is closed.
Aliases and symbolic links are lightweight references to files and folders. Aliases are
associated with Mac OS Standard (HFS) and Mac OS Extended (HFS+) volume
formats; symbolic links are a feature of UFS file systems. Both aliases and symbolic
links allow multiple references to files and folders without requiring multiple
copies of these items. Prior to Mac OS X 10.2, aliases and symbolic behaved very
differently when a referenced file or folder moved or changed.
Originally, aliases located a file or folder using its unique identity first and its
pathname second. If you moved a file on the same volume, any aliases pointing to
that file would still point to the original file. If you deleted a file and replaced it with
an identically-named file, aliases would still work because they could locate the file
by its pathname. Beginning with Mac OS X 10.2, aliases now reverse this search
order by using the pathname first and unique identity second.
Because aliases and symbolic links both use a file system path to resolve a file’s
location, they now offer a similar initial behavior. If you replace a file with an
identically-named file, moving the old file to a new location, both aliases and
symbolic links point to the new file. However, if you move a file without replacing
it, symbolic links to the file break while aliases do not.
On HFS and HFS+ file systems, each file and folder has a unique, persistent identity.
Aliases store this unique identity along with the pathname information. If the file
cannot be found by its pathname, the alias attempts to locate the file using its unique
identity. If it finds the file, the alias updates its internal record with the new path
information. Similarly, if the pathname is correct, but the unique identity is wrong,
the alias updates its internal record with the unique identity of the new file.
The Finder and other system applications now use aliases with this pathname-first
behavior. However, applications can still resolve aliases by unique identity first
using the methods of the Alias Manager.
Resource Forks
Before Mac OS X and Carbon, application resources were put in the resource fork of
the application executable. That policy has now changed. In Mac OS X and for
Carbon applications generally, resources should be put in the data fork of a separate
resource file, not the resource fork of the executable.
The Carbon APIs now read and process resources in a resource file’s data fork as if
they were in the resource fork. (In fact, the system routines that read resources—
which are primarily Resource Manager functions—now do most of the work for
you.) If application resources are stored in the resource fork, you can use these APIs
to access them, but now you must explicitly specify the resource fork in order for
this to happen.
The primary reason for moving application resources out of resource forks is to
enable applications to be seamlessly moved around different file systems without
loss of their resources; this would include methods such as BSD commands, FTP,
email, and Windows and DOS copy commands. Most other computing
environments, including the Web, recognize single-fork files only, and tend to
delete the resource fork of HFS and HFS+ files.
Even though Apple now recommends storing resources in the data fork of a
resource file, this—by itself—is an incomplete solution. For example, application
resources stored in a single file are much harder to localize. In addition to moving
application resources out of resource forks, you should use the application
packaging scheme (see “Application Packaging” (page 131)) and do either of the
following:
■ In the localized (or nonlocalized) areas of the application bundle, put a file that
contains the application resources for that locale (or for all locales). By
convention, this file has an extension of .rsrc, although it can have any
extension or no extension.
■ Instead of putting all localized resources in a single .rsrc file, put each resource
(or groups of related resources) in its own file.
Figure 9-1 depicts how resources can be stored in Mac OS X in contrast to the way
they are stored on earlier Mac OS systems.
1000110100010111011000101101
0001010011010001011100101110 data fork
1010001010010010001010100010
MyApp
resource fork
MyApp.app/
data Contents/
Info.plist
MyApp.rsrc PkgInfo
empty resource MacOS/
MyApp
or Resources/
MyApp.rsrc
AnImage.pict
data AnIcon.icns
AnImage.pict English.lproj/
empty resource Localized.rsrc
MyApp.strings
ASound.snd
data
AnIcon.icns
empty resource
data
MyApp.strings
empty resource
data
ASound.snd
resource
Files residing on HFS and HFS+ file systems have their Finder attributes stored in a
private fork separate from both resource and data forks. These attributes include
type and creator codes. Mac OS X maintains these attributes because they enable the
Finder to enhance the user’s experience. At the same time, however, Apple strongly
encourages developers to use file extensions as alternative means for identifying
document types. Mac OS X does a very good job of recognizing and handling
document extensions. And, as “Copy and Move Operations” (page 197) in the
chapter ““The Finder” (page 189)” makes clear, if you copy an HFS or HFS+
document to a different platform (including Web servers), file extensions help
ensure that the document’s type information is preserved.
Although Unicode is considered the native encoding for Mac OS X, there is no file
encoding that is the default for all situations. The file encoding that is (or should be)
used depends on what you want to do, on the API you use, and on the underlying
file system.
For example, the encoding used for filenames differs among the various file
systems. Mac OS Extended (HFS+) uses one particular form of Unicode for
filenames: canonically decomposed Unicode 2.1 in UTF-16 format (a sequence of
16-bit codes). The UFS file system uses a different form of Unicode for filenames; it
allows any character from Unicode 2.1 or later, but uses UTF-8 format (a sequence
of 8-bit codes). And Mac OS Standard (HFS) uses legacy Mac encodings, such as
In addition, all code that calls BSD system routines should ensure that the const
*char parameters of these routines are in UTF-8 encoding. All BSD system functions
expect their string parameters to be in UTF-8 encoding and nothing else. An
additional caveat is that string parameters for files, paths, and other file-system
entities must be in canonical UTF-8. In a canonical UTF-8 Unicode string, all
decomposable characters are decomposed; for example, é (0x00E9) is represented as
e (0x0065) + ´ (0x0301). To put things in canonical UTF-8 encoding, use the
“file-system representation” APIs defined in Cocoa and Carbon (including Core
Foundation). For example, to get a canonical UTF-8 character string in Cocoa, use
NSString’s fileSystemRepresentation: method; for noncanonical UTF-8 strings, use
NSString’s UTF8String method.
If you use regular QuickDraw and want to draw text, you should be aware of some
potential problems. The Carbon File Manager has some file-system calls that return
Mac encodings and others that return Unicode. If you get Unicode text, you will
have problems drawing it using QuickDraw Text because that API doesn't directly
support Unicode. On the other hand, if you get a Mac encoding and you want to use
Cocoa or Carbon’s Apple Type Services for Unicode Imaging (ATSUI) APIs, you
must convert it to Unicode first.
Generally, the encoding that is used depends upon the API you use and not the font.
Fonts are not necessarily limited to particular encodings. TrueType fonts, for
example, declare the set of glyphs they implement and provide encoding tables that
map those glyphs to character values in particular encodings. PostScript fonts have
similar encoding tables. Various parts of the operating system know how to map
characters from one encoding to another. Cocoa and ATSUI use Unicode as the
“destination” mapping for a font. QuickDraw Text in Carbon uses the Mac
encodings, selected according to the script that the ‘FOND’ resource of the font
corresponds to.
The fonts that are installed with Mac OS X have large character sets supporting a
wide range of encodings and scripts. For example, Lucida, the system font, supports
extended Latin, Greek, Cyrillic, Arabic, Hebrew, and Thai. But if you draw text
through QuickDraw Text, you have access only to the MacRoman repertoire. To
access the rest, you must use Cocoa or ATSUI. Similarly, the Hiragino fonts also
have a large repertoire of characters beyond that supported by MacJapanese, and
these are accessible only through Cocoa or ATSUI. Both Cocoa and ATSUI also
substitute glyphs from other fonts when the requested one isn't available; however,
their algorithms for font substitution are different.
For information on file encodings in the context of multiscript support, see “Adding
Multiscript Support” (page 222) in the chapter ““Internationalization” (page 211).”
10 The Finder
The Finder is the primary application of Mac OS X. Running from the moment you
log in, it works with the system software to track and manage the Dock, the file
system (including mounted network volumes), and connected devices. Through the
windows of the Finder, users can view and manipulate items in the file system such
as folders, applications, and documents.
This chapter does not go into detail about the human-interface elements related to
the Finder. Instead it focuses on those aspects of the Finder that are of special
interest to Mac OS X software developers. This information includes
■ application interfaces to the Finder
■ the stores of information the Finder maintains
■ how the Finder handles applications and documents
■ how the Finder handles file operations that take place between volumes of
different formats
■ how the Finder determines which application to launch when the user
double-clicks a document
■ how the Finder handles file sorting
In general, the nature and role of the Finder in Mac OS X is much the same as it is
in Mac OS 9. The Finder in Mac OS X is an application—specifically, a Carbon
application—that manages the user’s desktop and mediates user access to
The Finder
applications, documents, and other items in the file system. Users launch
applications and open documents through the agency of the Finder. In a sense, it is
the primary application, the one that is constantly running while users are logged
in to the system.
There are, however, several striking differences in Mac OS X that affect the nature
and role of the Finder:
■ The Aqua human interface. This interface affects not only the presentation of
desktop elements, but the logic and mechanics behind their use. The Dock and
the controls of Finder windows, for example, introduce paradigms absent from
Mac OS 9.
■ Multiple users. Yes, Mac OS 9 supports multiple users (through the Multiple
Users control panel), but there it is an option. On a Mac OS X system, multiple
users is standard. Users must log in to a Mac OS X system (even if they request
logging in to happen automatically). Once logged in, they work in an
environment largely customized to their own specifications.
■ Multiple application environments. Again, the difference in this respect is not
absolute; if you take Java into consideration, Mac OS 9 does (or can) have
multiple application environments. However, the difference in degree is
significant. Mac OS X must deal with the Carbon, Cocoa, Java, Classic, and
(in some cases) the BSD Commands application environments.
■ Multiple volume formats. Mac OS X supports various volume formats, both
multiple-fork formats such as Mac OS Extended (HFS+) and flat-file formats
(UFS, among others). It tries to make all file-system operations between volumes
of different formats as seamless as possible. See “The Finder and File
Operations” (page 197) for further information.
The Finder attempts to make the user’s experience of all application environments
as much the same as possible. However, there are a few issues with the
Classic environment. Classic applications cannot run from volumes that are not
Mac OS Standard (HFS) or Mac OS Extended (HFS+). Applications from all other
environments can run from any volume, regardless of format. In the same vein,
Classic applications cannot open or save documents on any volume that is not HFS
or HFS+. For more on the Classic environment, see “The Classic Environment and
Your Application” (page 241).
The Finder
At present, the Finder offers the information property list as an interface for
applications. Through this interface, applications can communicate their essential
data to the Finder.
The Finder also defines a suite of Apple events that applications can use to
accomplish a number of tasks, including opening documents and launching
applications.
Apple Events
Applications can send Apple events to the Finder to accomplish a number of
operations. These operations include
■ launching other applications
■ opening URLs
■ opening documents
The Finder
The use of property lists to convey information is more passive than other
interfaces; a developer need only make this information available to the Finder.
When the Finder encounters an application, it extracts the information in
Info.plist and uses it to populate its databases (see “Information Stored by the
Finder” (page 192) for details).
For more information on information property lists and the keys that are specific to
the Finder, see “Information Property Lists” (page 200) in the chapter ““Software
Configuration” (page 199).” For related information, see the chapters “Bundles”
(page 115) and “Application Packaging” (page 131).
The Finder
database contains information about all files and directories on the volume. When
the system is booted, the Finder builds these databases and, thereafter, dynamically
updates them as files and directories are added, changed, and removed.
The way the Finder in Mac OS X builds its databases is also different from the Finder
in Mac OS 9.
■ The Finder first adds applications at boot time by scanning the standard
locations for applications in the user, local (plus system), and network domains.
■ When users navigate through the file system, the Finder adds applications in
each visited directory to its databases.
■ When users try to open a document or attempt any other action that requires an
application, and the Finder cannot find an appropriate application, it displays a
dialog, allowing the user to select an application. This application is added to the
user’s application database.
Because there may be locations in the file system a user has never visited, or
documents of a type the user has never attempted to open, the Finder might have
an incomplete view of the applications available on a system. Yet it has a built-in
capability for “lazily” updating its view of the file system.
The Finder
Finder Attributes
Finder attributes (also known as Finder Info) can be associated with files and folders
in the Mac OS X file system. These attributes affect how the Finder displays or
handles these files and folders. The Finder in Mac OS X recognizes fewer such
attributes than the Finder in Mac OS 9. The supported attributes include
■ bundle bit
■ invisible bit
■ type and creator codes
■ custom icons
In Mac OS X the Finder stores attributes in an invisible per-folder file that contains
a data structure that is extensible and volume-format “agnostic.”
The Finder is the user’s primary interface to applications and documents in Mac OS
X. The following sections describe the techniques used by the Finder to display
documents and respond to user interactions with those documents.
The Finder
Presenting Documents
As described in “Information Stored by the Finder” (page 192), the Finder collects
information from applications in the file system and populates a number of
databases with that information. When the Finder encounters a file or folder, it often
uses this information to determine how to present the file or folder and how to
manage the user’s interaction with it.
The Finder uses a combination of bundle bit, type code, creator code, and filename
extension information to identify and appropriately handle documents,
applications, and loadable bundles. The following steps outline the general logic of
the Finder when it comes across an item in the file system:
The Finder consults the application database and locates the icon to display next
to the filename. If no such icon exists, it displays the default document icon.
The Finder
Two additional features that affect the way the Finder presents files to the user are
filename extension hiding and filename localization. These features are cosmetic
additions to the Aqua interface that alter the displayed name of a file without
changing the actual name of the file in the file system. The Finder uses routines
provided by Launch Services to obtain a displayable name for each file. For
information on filename extension hiding, see “Hiding Filename Extensions”
(page 177). For information on localized filenames, see “Localizing File System
Names” (page 178)
Sorting Files
Mac OS X provides many ways for users to sort and organize documents using the
Finder. As in Mac OS 9, users can sort files by name, by size, by modification date,
and so on. However, Mac OS X does differ from Mac OS 9 in the way it sorts text
strings. In Mac OS X, sorting is based on the Unicode Collation Algorithm
(Technical Standard UTS #10) defined by the Unicode Consortium. This standard
provides a complete and unambiguous sort ordering for all Unicode characters and
is available on the Unicode Consortium website (http://www.unicode.org).
The Finder in Mac OS X takes advantage of some sanctioned ways for altering the
default sorting behavior defined by the Unicode standard. In particular, the Finder
supports the following sorting rules:
■ Punctuation and symbols are significant for sorting.
■ Digit sub-strings are sorted by numeric value rather than as characters.
■ Case is insignificant.
The Finder
3. Select the default application that is registered to handle documents with the
same type or extension.
4. Select the application that claims documents of this type.
The Finder gives preference to native applications over Classic applications. It
also gives preference to later versions of an application and to applications with
a later modification date.
5. If there is an application with the same creator type already running, select that
application instead of the current selection.
6. If the Finder still cannot find a suitable application, it puts up a dialog asking the
user to select an appropriate application.
If the user chooses an application, the Finder adds that information to its
application database for future reference.
Once a suitable application has been found, the Finder proceeds to launch the
application and pass it a reference to the document.
The Finder is the “traffic manager” for most if not all file operations that take place
in Mac OS X. Unless you use shell commands such as cp and mv (something
generally not recommended), or AppleScript, or some other programmatic means,
you must use the Finder to copy, move, and delete files, as well as to make aliases.
Obviously, there are issues related to these operations that relate to multiple
volume formats. This section discusses how the Finder manages file operations
across volumes of different formats.
The Finder
As one might expect, the Finder preserves the resource fork and Finder attributes of
an HFS+ file “as is” when it copies the file to an HFS+ (or HFS) volume. The more
interesting case, however, is when it copies an HFS+ file to a UFS volume. When this
happens, the Finder splits out the information that is not in the data fork
(particularly the type and creator codes) and writes this information to a hidden file
in the same directory location as the copied file. This hidden file has the same name
as the UFS file, except that it has a “dot-underscore” prefix. Thus, if you have an
HFS+ file named MyMug.jpeg, when you copy it to a UFS volume, there will be a file
named ._MyMug.jpeg in the same location.
When the Finder copies a UFS file to an HFS or HFS+ volume, it looks for the hidden
“dot-underscore” file. If one exists, it creates an HFS+ (or HFS) file, using the
information in the hidden file to recreate the file’s resource fork and Finder
attributes. If the hidden file does not exist, the copied file has no resource fork.
Note that the Finder accomplishes these operations through the Carbon APIs on
which it is based.
Note: You can use the BSD cp or mv commands on a application package (or any
other bundle) without ill effect. However, if you use those commands on a
single-file CFM application, the copied (or moved) application is rendered
useless. For the latter purpose, Apple includes the CpMac command-line utility.
How the Finder manages a file-system world in which both aliases and symbolic
links coexist is simple. It recognizes symbolic links but creates only aliases (when
given the appropriate menu command). Even when it encounters a symbolic link in
the file system, it presents it as an alias—that is, there is no visual differentiation
between the two. The only way to make a symbolic link in Mac OS X is to give the
BSD command ln -s.
11 Software Configuration
Mac OS X gives you a number of ways to configure your software. It stores all
configuration data persistently using various mechanisms. These mechanisms
permit dynamic updating of this data and make it available to programs at runtime.
Property Lists
Software Configuration
You can create a property list with the Property List Editor application or, if that is
not available, any text editor. Then you add the file to your project. Property lists
are stored as a bundle resource (usually nonlocalized). Once your program is built
and run, it can easily access the information in the property list by using special
routines that read the property list and convert the data represented in it to the
appropriate types. The supported property-list types are dictionary, array (vector),
string, data, date, number, and Boolean.
Custom property lists are sometimes used to specify certain types of initialization
data, such as key bindings. A file named CustomInfo.plist is often used for this
purpose.
Information property lists are system property lists (see “Property Lists”
(page 199)) that contain essential configuration information for bundles. This
information is readily available to system and program code at runtime. As
described in the section “Types of Bundles” (page 123) of the chapter ““Bundles”
(page 115),” a bundle is a packaging scheme and generic programmatic type for
such things as applications, frameworks, and plug-ins. Information property lists
are thus a pervasive and important means for configuring software of almost all
kinds. They make available information that the Finder (and possibly other
applications) need, and they enable applications to deal with HFS and HFS+ files.
By convention, information property lists are found in files with the name
Info.plist. They can contain platform-specific information, in which case the tag
for the platform is embedded in the filename; the standard platform-specific names
are the following:
Info-macos.plist
Info-macosclassic.plist
Software Configuration
If the configuration information is generic to all platforms (as is ideally the case), the
name is Info.plist. When the bundle code is executed, it looks first for the
platform-specific file; if that does not exist in the bundle, it reads the
platform-generic file. Because the search algorithm searches for a file and not a
particular key, if you have both a platform-specific file and a platform-generic file,
make sure each contains a corresponding set of key-value pairs. Information
property list files are located in the Contents directories of bundles.
The Info.plist file for a bundle can contain all kinds of information. At the top level
of the property list, this information is specified as key-value pairs (that is, as a
dictionary). Mac OS X defines a set of standard keys for basic configuration
information, such as the name of the executable and the version of the bundle. The
Finder also defines keys for such things as documents, icons, and the information it
displays to users. You are free to define and use your own keys. The integrated
development environment (IDE) provides the human interface for entering
standard, Finder, and custom configuration data in the Info.plist file as key-value
pairs. For the standard and Finder-specific information property list keys, see
Appendix A (page 275).
A special localized resource file named InfoPlist.strings goes with the Info.plist
file. The InfoPlist.strings file contains keys for the information property list that
might need to be localized. These keys are the values specified for associated keys
in the Info.plist file. Commonly localized keys are CFBundleName,
CFBundleShortVersionString, CFBundleGetInfoString, CFBundleGetInfoHTML,
and the values of the CFBundleTypeName and CFBundleURLName types. See
“Bundles” (page 115) for more about localized bundles, particularly where they go
in the bundle and how they are located.
Document Configuration
Information property lists for applications that create or “understand” documents
permit the definitions of abstract types and roles. These definitions apply to
Clipboard (pasteboard) data as well as documents.
Software Configuration
A role defines an application’s relation to a document type. There are five roles:
■ Editor. The application can read, manipulate, and save the type.
■ Viewer. The application can read and present the data.
■ Printer. The application can print the data only.
■ Shell. The application provides runtime services for other processes—for
example, a Java applet viewer. The name of the document is the name of the
hosted process (instead of the name of the application), and a new process is
created for each document opened.
■ None. The application does not understand the data, but is just declaring
information about the type (for example, the Finder declaring an icon for fonts).
Listing 11-1 The Info.plist file for the Sketch demo application
Software Configuration
</array>
<key>CFBundleTypeIconFile</key>
<string>Draw2File</string>
<key>CFBundleTypeName</key>
<string>Apple Sketch Graphic Format</string>
<key>CFBundleTypeOSTypes</key>
<array>
<string>sktc</string>
</array>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>NSDocumentClass</key>
<string>SKTDrawDocument</string>
<key>NSExportableAs</key>
<array>
<string>NSPDFPboardType</string>
<string>NSTIFFPboardType</string>
</array>
</dict>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>pdf</string>
</array>
<key>CFBundleTypeName</key>
<string>NSPDFPboardType</string>
<key>CFBundleTypeOSTypes</key>
<array>
<string>pdf </string>
</array>
<key>CFBundleTypeRole</key>
<string>None</string>
</dict>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>tiff</string>
</array>
<key>CFBundleTypeName</key>
<string>NSTIFFPboardType</string>
<key>CFBundleTypeOSTypes</key>
Software Configuration
<array>
<string>tiff</string>
</array>
<key>CFBundleTypeRole</key>
<string>None</string>
</dict>
</array>
<key>CFBundleExecutable</key>
<string>Sketch</string>
<key>CFBundleIconFile</key>
<string>Draw2App</string>
<key>CFBundleIdentifier</key>
<string>com.apple.CocoaExamples.Sketch</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>sktc</string>
<key>CFBundleVersion</key>
<string>1.2.0</string>
<key>NSAppleHelpFile</key>
<string>osxa444.htm</string>
<key>NSAppleScriptEnabled</key>
<string>YES</string>
<key>NSJavaNeeded</key>
<string>YES</string>
<key>NSJavaPath</key>
<array>
<string>Sketch.jar</string>
</array>
<key>NSJavaRoot</key>
<string>Contents/Resources/Java</string>
<key>NSMainNibFile</key>
<string>Draw2Java.nib</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>
Software Configuration
Listing 11-2 The InfoPlist.strings file for the Sketch demo application
// InfoPlist.strings
// Sketch Exampmle
{
CFBundleName = "Sketch";
CFBundleGetInfoString = "Apple Sketch Application Example 1.2.0.
Copyright \U00A9 1998-2001, Apple Computer, Inc.";
NSHumanReadableCopyright = "Copyright \U00A9 1998-2001, Apple Computer,
Inc.";
// Document type human-readable names.
"Apple Sketch Graphic Format" = "Apple Sketch Graphic Format";
"NSPDFPboardType" = "Portable Document Format (PDF)";
"NSTIFFPboardType" = "Tagged Image File Format (TIFF)";
}
Preferences are application or system options that allow users to customize their
working environment. Most applications read in some form of user preferences. For
example, a document-based application may store preferences for the default font,
automatic save options, or page setup information. Preferences are also not limited
to applications. You can read and write preference information, including user
preferences, from any frameworks or libraries you define.
The preferences system of Mac OS X includes built-in support for preserving and
restoring user settings across sessions. Both Carbon and Cocoa applications can use
Core Foundation’s Preference Services for reading and writing preference
information. Cocoa applications can also use the NSUserDefaults class to read user
preferences.
Software Configuration
Important
The assumption with user preferences is that they are not
critical; if they are lost, the application should be able to
recreate the default set of preferences. You should not store
an application’s initial configuration data as a preference.
Initial configuration data is critical and should be stored in
the information property list, or some other property list
stored, inside the application package.
The preferences system stores values that are associated with a key; later you can
use the key to look up the preference value when you need it. Key-value pairs are
assigned a scope using a combination of user name, application ID, and host
(computer) name. This mechanism allows you to create preferences that apply to
different classes of users. For example, you can save a preference value that applies
to
■ the current user of your application on the current host
■ all users of your application on a specific host connected to the local network
■ the current user of your application on any host connected to the local network
(the usual category for user preferences)
■ any user of any application on any host connected to the local network
Software Configuration
part of its information property list (see “Standard Bundle Keys” (page 276) for
details). The system routines related to preferences use the bundle identifier to find
the preferences for a given application.
To ensure that there are no naming conflicts, Apple strongly recommends that
bundle identifiers be the same form as Java package names—your company’s
unique domain name followed by the application or library name. Some examples
are com.apple.finder, com.apple.Sherlock, and com.foo.ImageImport. Using this
scheme minimizes the possibility of name collision and leaves you responsible for
managing the identifier name space under your corporate domain.
Core Foundation’s Bundle Services and, for Cocoa applications, the NSBundle class
provide routines for accessing an application’s bundle identifier. You should
always use these routines and never hard-code the application identifier.
Preference Domains
When you create a new preference or search for an existing one, the preferences
system uses the notion of preference domains to specify the scope and location of
the preference. A preference domain consists of three pieces of information: an
Software Configuration
application identifier, a host name, and a user name. Table 11-1 shows all of the
preference domains, listed in the order they are searched when the preference
system attempts to locate a preference value.
The search routines look through the various preference domains in the order given
above until they find the key you have specified. If a preference has been set in a
less-specific domain—”Any Application,” for example—its value is retrieved with
this call if a more specific version cannot be found. This means that values in
more-specific domains override those for the same key in less-specific domains.
Software Configuration
To run the utility, launch the Terminal application and, in a BSD shell, enter
defaults plus all appropriate command options. For a terse description of syntax
and arguments, run the defaults command by itself. For a more complete
description, read the man page for defaults or run the command with the usage
argument:
$ defaults usage
Because applications access the preferences system while they are running, you
should not modify the defaults of a running application using defaults. If you
change a default in a domain that belongs to a running application, the application
probably won’t see the change and might overwrite the default.
Software Configuration
12 Internationalization
Before going further, it might be helpful to distinguish the seemingly similar terms
localization, internationalization, and multiscript support.
■ Localization is the adaptation of a software product, including online help and
documentation, for use in one or more regions of the world, in addition to the
region for which the original product was created. Localization of software can
include translating user-interface text, resizing text-related graphical elements,
and modifying images and sound to conform to local conventions.
■ Internationalization is the design or modification of a software product to
facilitate localization. With its Unicode-based text storage, bundled resources,
and preferences system, Mac OS X is an internationalized operating system that
enables the input, display, formatting, and manipulation of localized resources.
To internationalize software, you must write code that makes use of these
locale-aware services.
■ Multiscript support refers to a set of programming practices that ensures
software can appropriately handle multilingual text. A program with such
support can, for example, accurately display a single document that contains
multiple scripts such as English, Japanese, and Arabic.
Except for user-interface tweaking, this chapter does not cover localization because
this discipline falls outside software development. Translating text is typically done
by professional translators, and recreating images and sounds is usually done by
211
Apple Computer, Inc. July 2002
C H A P T E R 1 2
Internationalization
Internationalizing your application makes your application localizable. That is, you
build localization support into your application by placing the text, images, and
sounds specific to a language in files in a language-specific subdirectory of your
project directory and by using the proper locale-savvy APIs for accessing those
resources.
Even if you don’t have immediate plans to support multiple languages in your
application, there are advantages to designing your application with
internationalization in mind. If your application is properly designed, you won’t
have to touch its source code to introduce future localizations; therefore, you won’t
run the risk of introducing bugs by putting the necessary hooks in later. Second, you
can test the localization code along with the initial monolingual product, thereby
minimizing the amount of testing needed for any future localized version.
Internationalization
And, of course, the necessary fonts and input services for a particular script must be
installed on a Mac OS X system.
Internationalization
Each string in the list of languages potentially corresponds to the base name of an
.lproj directory in the Resources directory of a bundle. The system’s
bundle-management routines use this string to find the localized resources in the
corresponding .lproj directory. If that directory does not exist, they use the second
language preference to search for a bundle localization. It continues until they find
a localization, the default localization being the language used in development.
Core Foundation Bundle Services (CFBundle) provides this search functionality for
Carbon and Java applications; for Cocoa applications, it is provided by the
NSBundle class. Once your application contains translated versions of
language-specific resources, it can load these localized resources from
Internationalization
the appropriate set of files, based on the user’s language preferences. Thus, your
application automatically presents itself to each user in one of that user’s preferred
languages—ideally (but not necessarily) the user’s first choice.
See the chapter “Bundles” (page 115) for information on how bundles store
resources.
The recommended approach is to use the ISO 639 language abbreviation or, if
appropriate, the ISO 3166 locale abbreviation. However, CFBundle and NSBundle
can recognize language names that have a Mac OS language code and can map ISO
639 abbreviations to these names. This lets you specify names such as English,
French, German, Japanese, Chinese, Spanish, Italian, Swedish, and Portuguese
among others. However, use of these language names is discouraged.
Note: To obtain copies of the ISO 639 and ISO 3166 standards, go to the
International Standards Organization website http://www.iso.ch.
Because of the way the system attempts to match language preference with
localization, the user’s language preferences should be as specific as possible and
the localizations stored in a bundle should be as general as possible. As noted
earlier, the system bundle routines try to match the designation given for a
language preference to the base name of an .lproj directory in a bundle. Failing an
exact match, it tries to find a localization at a more general level.
An example will help clarify this point. Suppose a user has specified a primary
language preference of U.S. English (“en_US”). The user launches an application
that has only two localizations, French.lproj and English.lproj. When the system
is asked to fetch a localized resource, it looks first for a directory named
en_US.lproj, next for directory en.lproj, and finally finds the resource in
English.lproj.
Internationalization
When the bundle routines look for resources, they check both the localization for a
single locale and, if the resource isn’t found there, the localization for the language
of which the locale is a variant. This behavior enables you to put resources that are
specific to locales and those that are general to a language in their own .lproj
directories, and yet have these resources logically combined. The system looks first
in a locale-specific localization (say, en_US.lproj) and if it doesn’t find the resource
it’s looking for, it looks in a language-specific localization such as en.lproj or
English.lproj. If it can’t find it there, it goes on to the user’s next preferred language
or locale. Apple recommends that applications with a localization for a particular
locale should include a localization for the corresponding language; this
localization should contain all resources that are generic to the language.
Because they make reference to the abbreviations in the ISO 639 standard,
CFBundle and NSBundle can handle most known languages. (To give an idea of
how comprehensive their coverage is, the languages include Manx, Faroese, and
Oromo.) You can use the Carbon functions in MacLocales.h to convert ISO 639
abbreviations to user-visible names in a particular language. You can also use a
language or locale abbreviation that is not known to CFBundle and NSBundle;
however, if you do, you must ensure that there is an exact match of the abbreviation
for the language preference and the .lproj directory base name.
Project Builder provides the File Reference Inspector to assist you with
internationalization. To internationalize a resource file, complete the
following steps:
Internationalization
d. In the dialog that Project Builder displays, select “Copy into group folder”,
choose one of the “relative” reference styles (for example, Project Relative),
and make sure the correct target is selected. Click Add.
2. Select the resource file and choose Show Info from the Project menu.
3. In the File Reference Info window (Figure 12-2 (page 217)), choose Make
Localized from the Localization & Platforms pop-up menu.
4. In the dialog that appears, either select one of the standard languages from the
pop-up menu or enter a language that is not in the list.
If you have an existing resource that you want to use as a placeholder or
template for another localization, choose Add Localized Variant and select (or
enter) the other language. Project Builder copies the resource to the other .lproj
directory.
5. If the resource is a text file, choose Unicode from the File Encoding pop-up
menu.
Internationalization
Finally, a word must be said about the tools to use for localizing resources. For
images and sounds, use the appropriate application (for example, Photoshop).
For text, always use a word processor or text editor that can save files in the UTF-16
encoding; the TextEdit application included with Mac OS X provides such
capabilities. If you can define and archive user interfaces using an application such
as Interface Builder, you should provide localized versions of these interface
archives; see the following section for more information on this topic.
Note: This section talks about Interface Builder and its nib files. However, much
of the discussion is applicable to localizable user-interface archives created by
other IDEs.
Nib files store the user interface of an application, including windows, dialogs, and
user-interface elements such as buttons, sliders, text objects, and help tags for these
elements. A nib file also holds the connections between these objects that cause
actions to be performed when the user activates controls. Nib files are typically
localized all at once; the localizer takes a nib file, translates all the user-visible
strings and makes other adjustments as necessary (such as resizing the visible
elements).
In any medium-size or large application, it’s usually a good idea to put each
window or panel (that is, dialog) in its own nib file. This practice not only makes it
possible to load the user interface lazily (that is, to load it as necessary), but it also
permits localization to progress in more incremental steps. It’s also a good idea to
put the menus of the application in a separate nib file.
Internationalization
You should use Interface Builder to localize nib files. To do this, open all of the nib
files in a language.lproj directory, localize all the strings, change the sizes of the
user-interface elements to accommodate the new strings, and save the nib files.
There are a few other things to watch out for:
■ Objects in a nib file typically have connections between them that should not be
broken. You should lock all connections (an option in Interface Builder
preferences) before editing the nibs.
■ Numeric and date fields often have formatters attached to them. Change the
format, if necessary, to be appropriate for the new locale; an example is the
thousands-separator character, which is a comma in the United States and a
period in continental Europe. (Consult the Interface Builder documentation for
instructions on doing this.)
■ Dialogs and windows usually have minimum or maximum sizes that are
specified through the inspector. If you must make a dialog or window wider for
a given language, it’s likely that the minimum size also needs to be modified.
■ Some user-interface objects support help tags—bits of explanatory text that
appear when the user moves the mouse over the object for a short period. You
can define the help tags for an object in Interface Builder’s inspector, where they
can also be localized.
Localizing Strings
Strings files enable you to externalize and localize the strings that are embedded in
your application’s source code. They are called strings files because they have the
extension of .strings, for example Localizable.strings. There is typically at least
one strings file per localization (that is, per .lproj directory) in a bundle.
Note that strings files are not intended for strings that appear in an archived user
interface (for example, a nib file created by Interface Builder). For such strings, you
can localize them using the appropriate development application (see “Localizing
User Interfaces” (page 218)).
Also keep in mind that there are two kinds of embedded strings: those that the user
sees, and those that the user doesn’t see. An example of a string the user doesn’t see
is contained in the following statement:
if (CFStringHasPrefix(value, CFSTR("-")) {
CFArrayAppendValue(myArray, value);
};
Internationalization
The string “-” does not need to be localized since the user never sees it, and it has
no effect on anything that the user does see. On the other hand, a string that appears
in an alert dialog should be localized.
/* A comment */
"Yes" = "Oui";
"The same text in English" = "Le même texte en français";
The string on the left is used as a key in code for locating the string on the right in
the strings file. Carbon and Cocoa provide APIs for accessing localized strings from
a strings file. Cocoa applications should use the following macros (declared in the
header for the Foundation framework’s NSBundle class) to extract strings out of a
strings file:
NSLocalizedString(key, comment)
NSLocalizedStringFromTable(key, table, comment)
Carbon and other non-Cocoa programs should use the equivalent macros defined
in Core Foundation Bundle Services (CFBundle):
CFCopyLocalizedString(key, comment)
CFCopyLocalizedStringFromTable(key, table, comment)
CFCopyLocalizedStringFromTableInBundle(key, table, bundle, comment)
would return “Oui” from the above table. The arguments to the above macros are
as follows:
key
The string used in looking up the localized value.
table
The name of the strings file to look in (by default, “Localizable”, which
causes the macro to look for Localizable.strings).
Internationalization
comment
The comment to put in the strings file when generating the strings file.
Some functions and methods (such as the Cocoa stringWithFormat: method and the
Core Foundation CFStringCreateWithFormat function) allow string arguments with
formatting characters in the string. For these functions and methods, you can
specify formatting characters in both keys and values, as in this example:
The localizer can reorder the arguments in the translated string if that is necessary.
If a string contains multiple variable arguments, you can change the order of the
arguments by using the n$ modifier where n indicates the order of the argument.
For example:
Strings files are best saved in Unicode format. This allows them to be
encoding-independent, and simplifies the encoding to use when an application
loads strings files. The TextEdit application can save in Unicode format. You can
select the encoding either from the Save dialog in Plain Text mode, or as a general
preference for TextEdit.
Internationalization
The program works by parsing the source files that you specify, extracting the
information from each call to Cocoa’s NSLocalizedString macro (and variant) and
Core Foundation’s CFCopyLocalizedString macro (and variants), and adding that
information to the appropriate strings file. Every entry generated from a call to one
of the relevant macros is placed in a file called table.strings where table derives
from the “table” argument of the macro (Localizable.strings by default if no table
is specified). Using separate tables creates separate domains for sets of strings,
allowing different translations of the same string depending on the context.
The comment provided in these calls is also written out to the strings file, allowing
the translator to get a better idea of what the string is used for. It’s important to
understand that genstrings generates one entry for each call to one of the related
macros and duplicates any identical entries. If your code has more than one of these
macros with the same arguments, you’ll have to edit the strings file after you run
genstrings to remove the redundant entries. Although a key can occur multiple
times in a source file, each key in a strings file must be unique. (However, you can
have multiple strings files, or “tables,” per localization, and each of these files
can contain the same key.)
Whether you want to generate strings files automatically or create them by hand is
up to you. In some cases you might find it convenient to generate your strings files
once in the lifetime of your application development, then tweak them by hand.
However, in most cases, it’s better to generate new strings files from the source
whenever you change or add any localized strings.
Internationalization
Internationalization
You can no longer assume that all text data is in MacRoman or ignore text
encoding issues altogether. You must be prepared to handle text encoding
issues. Untagged text data unaccompanied by script code is not necessarily in
the system script (Roman) anymore. If this assumption is wrong, as it can often
be, users are presented with garbled text. Worse, it could lead to anomalies that
corrupt user data or even crash the system.
For more information on file encodings in Mac OS X, see “File Encodings and Fonts”
(page 186) in the chapter “The File System” (page 165).”
The moment arrives. You’ve worked for months on your Mac OS X application,
designing, coding, redesigning, debugging, testing, tuning, and fixing bugs. Now,
with one final build, your application should emerge as what it was meant to be: an
elegant, rock-steady feat of engineering, purring with power and potential.
But wait. Are you sure it’s ready? Is it truly in shape for deployment? Is it of
commercial quality, and can customers easily install it and use it? Is there anything
you have overlooked?
This chapter tries to help you answer these questions. First, it provides a checklist
of important tasks that you should complete (or at least consider completing) before
deploying your application. Some of these tasks are in the realm of fit-and-finish but
others are essential to a well-designed application. Second, it discusses issues
affecting how your application can best be integrated with the various pieces of
Mac OS X as well as with other applications. Finally, this chapter describes the
various approaches you can take and tools you can use for installing your
application. You’ve worked hard to produce a great application with the feature set
your customers value. Now take the time to ensure that they can enjoy your
application by delivering a great installation and setup experience.
typing. However, one approach is often better than another and sometimes you can
combine approaches. The following section describes various important facets of
application design, discussing not only what you can do, but more importantly
what you should do for reasons of performance, interoperability, or robustness.
Because the bundle bit, as with other forms of HFS and HFS+ metadata, can easily
be stripped in a networked environment involving multiple file systems, it is
important that your application bundles always have the extension of .app. Project
Builder automatically appends this extension when you build an application, but
other IDEs might not. In no case should you remove the extension or encourage
your users to. If the “unsightliness” of .app bothers you, don’t worry; the Mac OS X
Finder suppresses the display of the .app extension.
Although Apple does not set the bundle bit on its applications, you may set this
attribute on the bundle folder of your application when you build it.
For more on this subject, see “The Finder and Bundles” (page 122) and “The
Handling of Applications and Documents” (page 194).
The reason for this recommendation is the same reason behind having filename
extensions as well as Finder metadata for document typing (see “Why even have
extensions?” (page 230)). The HFS and HFS+ volume formats permit files with
multiple forks, or data streams. However, anything not in the data fork of a file can
easily be stripped away as the file travels between heterogeneous computer systems
in a local area network, an intranet, or the Internet. The point is to make resources
and all other forms of data persistent in an increasingly networked world.
Carbon applications, whether they are CFM-based or dyld-based, can always use
Resource Manager–style resources. However, if you package your application in a
bundle (as is recommended) you should put your resources in files in the Resources
directory of the bundle and you should use only the data forks of these files. These
files, which should have an extension of .rsrc, are treated as bundle resources just
like any other file, and are easily internationalized. Although .rsrc files can have
any base name, if you give them standard names and put them in the standard
bundle locations for resources, the system bundle routines manage the resources
automatically. It works like this:
■ Put nonlocalized resources in a file named executableName.rsrc and place this
file in the bundle location for such resources (that is, directly in the Resources
directory).
■ Put localized resources in files named Localized.rsrc and place these files in the
appropriate bundle locations (that is, the .lproj directories) for localized
resources.
When the application is launched, the system bundle routines automatically open
these resources and make them available to the application.
If you want the Finder to handle the application and its documents properly,
you must specify the key-value pairs otherwise found in a bundle’s information
property list as a resource of type 'plst', ID 0.
For further information on this subject, see “Bundles and the Resource Manager”
(page 129) and “Resource Forks” (page 183).
Apple recommends that your applications make use of both forms of document
typing. If your application owns a document, you can specify both type and creator
codes and file extensions in the information property list (Info.plist) of the
application project (see “Information Property Lists” (page 200)). Project Builder
provides a means for entering this information: the Application Settings pane for a
build target. Your application should enforce the setting of all valid types for its
documents, particularly file extensions. See “How should my application save
documents?” (page 231).
There is one final caveat with regard to extensions. Applications in general should
be prepared to open documents that have extensions but no type and creator codes.
This behavior is especially expected for common (and hence cross-platform)
document types, such as image files, text files, and HTML files.
as a key to look up the application to use for that action. Depending on the
specificity of the typing information (for example, there is an extension but no type
or creator codes), the Finder might
■ immediately open the document in an application
■ display a dialog enabling the user to select an application
■ open the document in one of the applications claiming that document type
If a file has neither type and creator codes nor extension, the Finder treats it as a
non-document file; the file is displayed with a generic icon and double-clicking it
does not open it in any application.
This is true, but only in a limited context. Macintosh users do not live anymore
within a parochial Macintosh world. In the Internet age, documents frequently
travel around a heterogeneous network, going, for instance, from a home
Macintosh to a Linux network server to a Windows computer on a corporate local
area network. Each computer on this path may have a different notion not only of
what constitutes a document type but what constitutes a file. Many computer
systems define a document’s type solely by well-known extensions (such as .jpg,
.mp3, and .html). They might not know what to do with an extensionless file and
treat it as an unknown type. They would also ignore the HFS+ metadata—or worse,
strip it out altogether, so that it is irretrievably lost.
When your application can save documents under more than one type, Apple
recommends that it present those types in a pop-up menu in the Save dialog (with
any “native” document type being preselected). Applications then would handle
extensions in the following way:
■ If users type no extension in the filename field, add it for them.
■ If users type the wrong extension, remove it and add the correct one.
■ If users type the correct extension, accept it.
CFM Executables
As noted earlier, Mac OS X is a very accommodating operating system. It supports
multiple file systems, multiple application environments, multiple programming
models, multiple graphics-rendering libraries, and multiple network protocol
stacks. It also supports multiple runtime environments and executable formats.
Specifically, the following types of binaries execute on Mac OS X:
■ Mach-O code modules managed by the dynamic link editor (dyld)
■ PEF code fragments managed by the Code Fragment Manager (CFM)
■ Java class files managed by the Java virtual machine
Of the three executable formats, the Mach-O is preeminent. It is the native format
upon which the others ultimately depend. CFM and PEF technology, which are the
preeminent library manager and executable format in Mac OS 9, are bridges to the
Mach-O/dyld technology, much in the manner CFM-68K was a bridge to PowerPC.
Saying that Mach-O and dyld are the native executable format and library manager
in Mac OS X means that all system frameworks, even Carbon frameworks, are built
as dyld-managed binaries in the Mach-O format. However, CFM is the traditional
Macintosh library manager and PEF is the traditional executable format for code
fragments, and so many Macintosh IDEs currently generate application executables
for this runtime environment (which includes the Classic compatibility
environment).
As the section “Library Managers and Executable Formats” (page 269) explains,
there are good reasons for building applications for Mac OS X as Mach-O
executables. Foremost among these reasons is performance. The CFM/PEF runtime
environment is layered on top of the dyld/Mach-O runtime environment; thus,
code that is CFM/PEF-based must go through an additional layer of software in
order to execute.
If you choose to deploy your application as a CFM executable, you must decide
whether to package it in an application bundle. When packaging is considered (and
Java is excluded), there are three different types of applications that can run on
Mac OS X. Table 13-1 shows the possible types.
■ Put the application’s resources in the bundle, following the instructions in “How
should I store application resources?” (page 227).
If you wish, you may deploy a CFM executable as a single-file application that
stores its Resource Manager–style resources in its resource fork. If you do this, and
you want the Finder to handle the application and its documents properly, you
must specify the contents of your application’s information property list as a
resource of type 'plst', ID 0. If a single-file executable does not have a 'plst'
resource, it is considered to be an application to be run only in the Classic
environment. Through a Finder Info-window option, you can force-launch a CFM
application into the Classic environment.
http://developer.apple.com/techpubs/macosx/
Second, make sure that your application is properly internationalized and localized
for all languages and regions where it will be marketed; as part of
internationalization, ensure that your application can support the presentation of
multiple scripts in one document. For information on these topics, see the chapter
“Internationalization” (page 211).
The following sections discuss other aspects of your application’s user interface
related to development.
Icons
An application or document icon must be an 'icns' resource contained in the data
fork of a file having an extension of .icns. Apple provides two applications (in
/Developer/Applications) to help you create and manage icons:
Users can assign custom icons to documents just as they can in Mac OS 9. To do so,
they must paste a copy of the custom icon into the well holding the current icon
displayed in the Finder’s Info window (File > Show Info). To enable users to do this,
you must override the default document icon in the Finder metadata (Finder Info).
To make a Carbon custom control comply with the system appearance, your custom
control definition must take advantage of the Appearance Manager APIs (declared
in Appearance.h). For a custom Cocoa control to be compatible with the selected
Aqua appearance, the custom subclass of an Application Kit class should use the
NSColor colorForControlTint: method to get the NSColor object corresponding to
the current Aqua tint selection, and then use that object to colorize its own drawing.
Generally you should avoid creating custom controls that draw themselves because
there is always the possibility of some incompatibility with Aqua. If you do create
a custom control, the new behavior should ideally involve something other than
drawing.
A Carbon nib file can contain definitions for most of the user-interface objects
typically found in Carbon applications. It also incorporates functionality for
features such as the Carbon event model. Special Carbon APIs give your application
access to the objects defined in the nib file. Nib files are not only a convenient way
to store the specification of an interface, but can be used to localize versions of a user
interface. And, because a nib file is XML-based, it is inherently more exportable to
other environments.
For these reasons, Apple recommends that Carbon developers start converting
many of the user-interface elements previously stored as Resource Manager–style
resources to Interface Builder objects. See the project example in
/Developer/Examples/InterfaceBuilder/IBCarbonExample to get an idea of what is
possible. Note that Carbon nib files lack many of the capabilities defined in Cocoa
nib files (target-action connection, for example) largely because of the differences
between the procedural and object-oriented programming models.
starts with a quick summary of the BSD permissions model before discussing these
differences. (For a more complete description, consult one of the numerous books
or websites devoted to BSD.)
On BSD systems there is a special root user, also known as the superuser. Root users
have unlimited access to the folders and files on the devices attached to the
computer they are using; they can
■ read, write, and execute any file
■ copy, move, and rename any file or folder
■ transfer ownership and reset permissions for any user
There is a special group called the wheel group. Membership in the wheel group
confers on users the ability to become the superuser after entering su at the
command line and providing a password.
In a BSD shell, if you enter the command ls -l for some location in the file system
(say, ~steve/Documents), you get results similar to the following:
total 3704
drwxrwxrwx 5 steve staff 264 Oct 24 20:56 General
drwxrwxr-x 5 steve admin 264 Oct 21 21:47 ProjectDocs
drwxr-xr-x 6 steve staff 160 Oct 25 12:00 Planning
drwx--x--x 6 steve staff 160 Oct 21 15:22 Private
-rwxrwxrwx 1 steve staff 0 Oct 23 09:55 picture clipping
[spongebob:~/Documents] steve%
The results show, among other things, the owner and primary group for a file or
folder and what the permissions are for each category of user. Users are shown in
the third column and the primary group in the fourth; thus, for the General folder,
the user is steve and the group is staff. The first column is a set of ten coded “bits”
that represents the type of file-system entity and the permissions for that entity. An
initial d indicates that the item is a folder (directory); if the initial position is a dash,
the item is an ordinary file. The remaining nine bits fall into three implicit groups
representing first owner, then group, then other. The r, w, and x characters, if
present, indicate that read, write, and execute permissions are turned on for the
type of user the set of bits applies to.
The owner permissions for this folder are rwx, meaning that the owner of the folder
(the holder of the steve account) can copy files and folders to this directory and can
make it his or her current working directory (through the cd command) and execute
any program in it. The permissions for anyone in the staff group and anyone else
are both r-x, meaning that those users can read files in steve and can make it their
current working directory, but they cannot write files to that folder or modify or
delete files in that folder.
Here read, execute, and write access are turned on for the group (rwx), but you have
to be a member of group admin in order to be granted this access.
Each read, write, execute triplet can also be represented as a decimal number
between 0 and 7. XREF lists the relationships between number and triplet.
Decimal
Number Permission English translation
0 --- No permissions
1 --x Execute only
2 -w- Write only
3 -wx Write and execute
4 r-- Read only
5 r-x Read and execute
6 rw- Read and write
7 rwx Read, write, and execute
Here you can represent the triplet rwx with the number 7, and the triplet --x with
the number 1. Thus, you can express the permissions for the Private folder as 711.
The numerical representation is useful with tools that change file permission.
If you have the appropriate permissions, you can change owner, group, and
individual permissions from a Terminal shell using, respectively, the chown, chgrp,
and chmod commands. See the associated man pages for details. You can also see the
same ownership and permissions information for a selected file or folder in the
Privileges pane in an Info window in the Finder. If you are the owner of the file or
folder, you can also change permissions in this window.
However, Mac OS X provides the administrator user in place of the root user. The
administrator can perform almost all functions the root user can, and can do them
using the Finder (that is, without resorting to the command line). The only thing the
administrator is prevented from doing is directly adding, modifying, or deleting
files in the system domain; however, an administrator can use special applications
such as Installer or Software Update for this purpose. The administrator is not a real
user (in the sense of a user with an account of “admin”); an administrator is any user
who belongs to the admin group.
The user who installs Mac OS X on a system and who provides information to the
Setup Assistant application automatically becomes the first administrator for the
system. Thereafter, this user (or any other administrator) can use the Users pane of
Accounts System Preferences to create accounts on the local system for new users.
An administrator can grant administrative privileges to a new user by setting the
appropriate options on the user’s account. Administrative users belong to the
“admin” group. Non-administrative users belong to the “staff” group.
Although the root user is disabled by default, you can, if you’re an administrator,
reenable it and acquire superuser status. But, for security reasons, you should do
this only if circumstances absolutely require it. To reenable root, run the NetInfo
Manager application in /Applications/Utilities and authenticate yourself as the
local administrator. Then choose Enable Root User from the Security menu; this
menu item is enabled only if you are a member of the local admin group and you
have been previously authenticated in the local domain. Once you’re enabled as
root user, your password is blank, so it is recommended that you give root a
password (via the Domain > Security > Change Root Password command). After
you’ve completed the task requiring root access, you should relinquish superuser
privileges by choosing Disable Root User from the same menu.
The -rwxr-xr-x setting should suffice except in the rare situations where an
application requires privileged (root) access. An example would be an application
such as a disk repairer that requires low-level hardware access through the kernel.
In cases such as this, you should install the application setuid to acquire root access
for the application; then use the features of the NetInfo Kit and System frameworks
that allow you to authenticate administrators. For more information on setuid,
consult the setuid (2) and chmod (1) man pages.
Although the permission set of the application (particularly the “x” bits) determines
who can launch an application, once the application is launched, the process is
owned by the user who launches it. This means the application has the same access
rights as the logged-in user, given that person’s owner and group identities.
Consequently, if that user has permission to write a document to a certain location,
the application is able to save a document there.
The Classic compatibility environment (or simply, Classic) makes it possible for the
latest version of Mac OS 9, and all the applications capable of running on that
version, to run on a Mac OS X system. As you would expect, there are strong
This section describes the Classic environment, especially its compatibility with
native Mac OS 9 systems and its integration with the rest of Mac OS X. It informs
developers of Mac OS 9 applications about things they should take into
consideration if those applications are run in Classic. It also tells developers of
software for the application environments of Mac OS X—Carbon, Cocoa, and
Java—about aspects of design that might cause problems for applications running
in the Classic environment.
To the Mac OS 9 operating system that it hosts, Classic appears as a new hardware
platform. It implements hardware services using the Mac OS X kernel environment
(particularly the I/O Kit). The Classic environment is not an emulator; Mac OS 9
runs natively in it. It is visually and functionally compatible with the rest of
Mac OS X so that to users—with the exceptions noted in “Integration With Mac OS
X” (page 244))—it is largely indistinguishable from the other environments of
Mac OS X.
Generally, programs that modify or rely on Mac OS internals below the hardware
abstraction provided by the kernel environment (and especially the I/O Kit) will
not work in the Classic environment. These programs should instead use a
higher-level API, if one is available, for such access. For example, all file-system
access should be through the File Manager API.
Device Support
Most devices that Mac OS X generally supports are also supported for the Classic
environment (or are planned to be supported soon). The classes of supported
devices include the following:
■ USB
■ sound (in and out)
■ disk images and SMIs (Self Mounting Image files)
■ Ethernet
■ SCSI (forthcoming)
■ FireWire (forthcoming)
■ video (forthcoming)
Mac OS X mounts all block storage (“disk”) devices, and the Classic environment
sees them as volumes through the File Manager API. The Classic environment can
grab access to a device if Mac OS X hasn’t. Disk images (including SMIs) and
AppleShare volumes mounted in Mac OS X appear through the File Manager API
within Classic. Note that Mac OS X always grabs access to the USB keyboard and
mouse; Classic communicates with these devices at a higher level of event.
This section discusses areas of integration where there are known differences. It is
possible that other differences might be introduced in a later version of the
operating system. As as rule of thumb, if you don’t know if a specific Classic
element is integrated with the rest of Mac OS X, assume that it isn’t.
User Interface
The differences between windows and other user-interface elements in the Classic
environment and the rest of Mac OS X are probably the most conspicuous. Instead
of Aqua, windows have the platinum look and feel. For example, instead of the
translucent red, yellow, and green window controls, Classic windows sport the
close box, the collapse box, and the zoom box. When you click the collapse (or
windowshade) box, there is no special “genie” effect that hides the window as in
Aqua; the window’s content simply disappears. A platinum window casts no
“shadow.”
You can also see several differences in the menu conventions adopted by Classic
applications and other Mac OS X applications. In Mac OS X applications, for
instance, the placement of the menu command for terminating an application is
different; a Classic application has the Quit menu item in the File menu whereas a
Mac OS X application has the “Quit application” menu item in the application menu.
The differences extend to actions such as resizing and dragging windows. In Aqua,
the window is redrawn at each point. However, when you drag or resize a Classic
window, you see an outline of the window (a marquee) and the window is not
redrawn until the operation ends.
Classic doesn’t take part in transparency effects, and when a Classic object is below
a semi-transparent Aqua window, the object might appear completely white. This
is not the case when a Classic window is over an Aqua object.
Another obvious difference is the file-system browser. Mac OS X makes use only
of Navigation Services for this feature whereas Classic applications can use
Navigation Services or the Standard File Package.
On the integration side, both Classic and Mac OS X support OpenGL and 8-bit
graphics.
The Classic environment also differs from Mac OS X in the manner in which it
handles file-system access permissions. Although Mac OS 9 itself is not aware of
permissions on local disk volumes, AFP recognizes permissions on a per-folder
basis; access to files is determined by the permissions assigned to the containing
folder. Classic maps BSD permissions failures to the closest corresponding AFP
permissions error, which results in the most compatible behavior for applications
running in the Classic environment.
Note: Often the only recourse for installers with such problems on Mac OS X is
for the user to boot back into native Mac OS 9 and install there.
Classic respects BSD file permissions except in a few special places, such as the
System Folder, Trash, the Desktop Folder, and certain hidden folders specific to
Mac OS 9. If a user has read-write permissions at the root of the Classic
environment’s file system, a Classic application can write to the System Folder and
can move items to the Trash folder. When a program running in the Classic
environment attempts to write to a folder where it doesn’t have permission, an AFP
error code is returned.
There can be conflicts between the set of extensions used in a native Mac OS 9
system and the corresponding extensions in the Classic environment. These
conflicts can lead to crashes. Generally, when there are conflicting extensions,
Classic disables the corresponding “native” extension when it starts up. A case in
point is the Multiple Users extension. Mac OS X is inherently a multiple-user
system. Therefore, the Classic environment disables the Multiple Users extension
when it starts up; when the user boots into the native Mac OS 9 system, the Multiple
Users extension is reenabled.
Note: The release notes for the Classic environment list the currently known set
of conflicting extensions.
The Mac OS X Finder and Navigation Services hide the Mac OS 9 Desktop Folder if
it is on the boot volume. In the scenario where Mac OS X is installed “over” Mac OS
9, if users want to get to the Mac OS 9 Desktop Folder from the Finder or Navigation
Services, they can navigate there through an alias in /MacOS9. When users boot back
to native Mac OS 9, they will see the Mac OS 9 desktop—the union of all non-AFP
desktop folders on all mounted volumes—as they left it.
The Mac OS X Finder performs System Folder autorouting and Mac OS 9 System
Folder blessing in the Classic environment.
With Mac OS X there are several options for installing your application. You can
simply instruct users to drag the application to their hard disks, or you can prepare
the application for an installer. This section describes these possibilities and
summarizes the work required on your part to make an application installable.
Where to Install
As described in “How the File System Is Organized” (page 165), the standard
directory layout of the file system has several places where applications can be
installed:
■ the combined system and local domains (/Applications)
■ the user domain (~/Applications, either local or on the network)
■ the network domain (for example, /Network/Applications)
Important
Do not install any software or resources, such as frameworks
or fonts, anywhere in /System/Library. Such items should go
in the appropriate locations in the local domain (/Library).
Users are not required to install applications in one of the domain locations. Because
applications when packaged in bundles are designed to be largely self-contained,
users can install them anywhere and they should execute without problems.
However, by being outside the recommended locations, an application might not be
able to take advantage of some system features, such as application services for
Cocoa applications. Another missing feature would be Finder awareness of the
application. The Finder, when it’s building its application database, looks for
applications in the known domains. If an application is outside all domains, that
could affect the efficiency of the system. For more information on the Finder and
applications, see the chapter “The Finder” (page 189).
Manual Installation
Because most applications for Mac OS X are packaged as self-contained bundles, all
users need to do to install an application in most situations is to drag the bundle to
a folder for which they have write permission. When you have a simple application
where this type of installation is all that is required, you can provide instructions
along with the application (in the form of a brief online or printed document) that
tells users what to do.
Installers
For some applications, simple drag-and-drop installation will not suffice. Either the
requirements for preparing the application for execution are too complex, or the
advantages of using an installer are too compelling. Among these advantages are
■ compression
■ displaying a Read Me file as part of the installation process
■ requiring the user to agree to a license before installing
■ requiring the user to authenticate as an administrator prior to installing
■ a more professional-looking presentation
Important
Although an installer might have some advantages, Apple
recommends the simple drag-and-drop manual installation
whenever possible. You should use an installer only for
applications that, for whatever reasons, need to install items
outside their bundles.
If you decide to install your application with an installer, you have several options.
If your application is a Cocoa or Java application—or a Carbon application that will
only be installed in Mac OS X—you can use Mac OS X’s native installer technology.
If your application is a Carbon application, and you want to install this application
on both Mac OS 9 and Mac OS X, you can take one of two approaches:
■ For both platforms, use a third-party installer that has been ported to Mac OS X.
■ Use the native installer technology for installing the application on Mac OS X
and a third-party installer for Mac OS 9.
The native installer application for Mac OS X is called Installer, and it is located in
/Applications/Utilities. When users double-click an installation package, the
Installer application launches. The application steps the user through the
installation process by presenting a series of panes for things such as authenticating
the user’s privileges (shown in Figure 13-1 (page 252)), specifying an installation
location, and customizing the installation. The Installer application can also display
the bill of materials and an installation log. The section “Installation Packages”
(page 253) describes the structure and contents of an installation package.
You create an installable package for Mac OS X using another application named
Package Maker (/Developer/Applications/PackageMaker). The general approach to
preparing software for packaging and using Package Maker is described in
“Creating an Installation Package” (page 254).
Installation Packages
The native form of installer-ready software on Mac OS X is called a package. An
installation package is a file package—that is, a folder presented to the user as a
file—that has an extension of .pkg. An installation package contains several
components, most significantly the file archive, the Read Me and licensing
documents (optional), and any installer scripts (optional). The format of installation
packages enables Installer to provide useful features such as descriptive
information, a default installation location, the ability to uninstall the software, and
so forth.
Although the Finder presents a package as a single file-system entity, you can enter
a package directory using the BSD cd command (via the Terminal application) and
view the components of the package. The files that make up a package are named
with suffixes that indicate the type of information stored in the file. A basic package
contains these files:
■ A bill of materials (.bom), a file in binary format that describes the contents of the
package.
■ An information file (.info), a text file that contains the information entered into
the Package Maker application when the package was created.
■ An archive file (.pax), an archive of the complete set of files to be installed. If the
archive is compressed, the archive has an additional suffix of .gz.
■ A size calculation file (.sizes), a text file that contains the compressed (and
uncompressed) size of the unarchived software, which enables the installer to
calculate space needed for installation.
■ Additional (and optional) resources, such as icons, Read Me files, licensing
information, pre- or post-install scripts, and so forth. These are package
resources, used (or run) during installation but not installed along with the
software.
Because installation packages are essentially folders (that is, file packages), their
contents are susceptible to alteration and even corruption during handling. To
prepare a package for distribution, you should archive and perhaps compress the
package into a form that can be distributed safely.
For example, if you have built a framework and you want it installed in
/Library/Frameworks, you might create the directory hierarchy
~/dstroot/Library/Frameworks and copy the framework into this location. When
Package Maker builds your package, it records this directory hierarchy. When your
package is installed, Installer will place the software at the correct point in the file
system. (However, if your package is relocatable, the user may choose to install it
elsewhere.)
These Read Me and license files can be in one of three forms (with the appropriate
extension): text (.txt), HTML (.html) or Rich Text Format (.rtf). When you create
the files, use a text editor that can save the files in Unicode encoding. Special base
names are reserved for the Read Me and license files. If the Read Me file is named
ReadMe.ext and the license file is named License.ext, Installer recognizes each file (if
it is present in a package) and handles it automatically:
■ Installer adds a “Read Me” item to the bulleted list presented in the left column
of the application. When the user reaches the Important Information pane,
Installer displays the contents of the file. The user dismisses the Read Me by
clicking the Continue button.
■ Installer adds a “License” item to the bulleted list presented in the left column
of the application. When the user reaches the Software License Agreement pane,
Installer displays the contents of the file. When the user clicks the Continue
button, Installer displays a dialog requesting that the user agree to the terms of
license (by clicking Agree).
Because the supplementary installation resources are not installed along with your
software, you should not place them in the distribution directory. Instead, create a
“resources” directory at the same level as dstroot and put the files in there. The
contents of the resources directory are copied into the package when it is created.
Notice the first two fields: Package Root Directory and Package Resources
Directory. These fields should contain paths that point to the roots of the
distribution directory and the resources directory that you created earlier. See the
application’s online help for the purposes and expected values for these fields and
for other fields and controls.
System-Wide Resources
If a bundled executable has resources that, for one reason or another, must be
installed outside the bundle, the installer should take care of that. Often such
resources need to be in certain locations to take advantage of system services. An
example is fonts. The Apple Type Solution (ATS) system manages fonts by looking
for them in Library/Fonts in the system, local, network, and user file-system
domains.
Different components make up Mac OS X, each with its own background, and this
sometimes leads to clashes in terminology. This different terminology is often
reflected in APIs as well as in documentation. The notions of “task” and “process”
provide an important case in point. You have Mach tasks and BSD processes and
Carbon Process Manager (CPM) processes and Multiprocessing Services tasks and
so on.
One Carbon Process Manager (CPM) process is layered on top of one BSD process.
This layering enables the CPM APIs. Every Carbon, Cocoa, and Java application
process is thus, at the same time, a Mach task, a BSD process (with its own process
ID), and a CPM process (with its own PSN, or process serial number). Classic
processes are an exception to the one-to-one process model. The applications
running in Classic each have their own CPM process, but these multiple processes
are layered on one BSD process.
Both Carbon and Cocoa include the name “task” elsewhere in their APIs. Cocoa
uses “task” and “process” in the Mach and BSD senses. An object created with the
Foundation framework’s NSTask class is actually associated with a subprocess
spun off from a parent process; it is a separate executable entity with its own set of
threads and address space. Multiprocessing Services calls its user-level preemptive
threads “tasks,” largely to avoid conflict with the Thread Manager’s (cooperative)
threads. See the following section, ““Threading Packages” (page 260),” for more on
Multiprocessing Services tasks.
Threading Packages
POSIX threads
Mach threads
The other threading models or packages are implemented on top of Mach threads.
You should always use one of the client APIs instead of the Mach APIs if possible.
Layering Details
As Figure 14-1 (page 261) illustrates, the BSD POSIX threads package (also known
as Pthreads) layers its own multithreading environment on top of the kernel
environment’s Mach threads. The package schedules its threads preemptively and
maintains a one-to-one mapping between a Mach thread and a POSIX thread.
The thread packages of the application environments are layered on top of POSIX
threads. As with POSIX threads, they build their own multithreading environments
on the threading substrata. The threads provided by Multiprocessing Services in
Carbon and the NSThread class in Cocoa are preemptively scheduled and have a
one-to-one mapping with the underlying POSIX thread. (In fact, the
Multiprocessing Services threads, called “tasks” in the API, are thin covers for
POSIX threads.) The Thread Manager’s threads, on the other hand, are
“multiplexed” onto a single POSIX thread and can be scheduled only cooperatively.
Usage Guidelines
When an application process is launched it automatically acquires one thread,
regardless of the application environment. If you want your application to be
multithreaded, you should use, in most cases, the thread package appropriate to
your application environment and, for Carbon, to the type of required thread
(preemptive or cooperative).
You should use POSIX threads when you want maximum source code
compatibility with other operating systems. For example, a good deal of BSD code
uses POSIX threads, which should be compatible with the implementation in
Mac OS X.
With rare exceptions (such as debuggers), your projects should avoid creating and
managing Mach threads. These threads lack much of the infrastructure provided by
POSIX threads. Moreover, use of Mach threads is likely to lead to compatibility
problems later.
Interprocess Communication
Usually at some point in its life, a process needs to communicate in some way with
another process. Perhaps it needs to transfer some data, or it needs to let other
processes know that something happened to it. However, communication between
processes on a modern operating system can be a tricky affair; if such
communication is poorly conceived and carried out, the overall stability and
performance of the system could suffer.
■ Combine shared memory with POSIX semaphores to share large resources such
as pictures, sounds, or movies with other processes. See “Sharing Large
Resources With Shared Memory” (page 267).
■ NSPasteboard is a Cocoa class that allows simple runtime-persistent storage of
publicly sharable data. Low-level interapplication Clipboard operations (cut,
copy, paste) are implemented using NSPasteboard.
■ Cocoa applications can use a services facility that allows them to advertise the
services (through the Services menu) they can perform on behalf of other
applications. See “Making Services Available to Other Applications” (page 268).
■ Cocoa applications can also use distributed objects to send messages to objects
residing in other threads or processes on the same computer. See “Calling Other
Processes With Distributed Objects” (page 268).
■ The Mach port object is the underlying primitive used for all interprocess
communication on Mac OS X. See “Messaging With the Mach Port Object”
(page 268).
Apple event objects have a well-defined data structure with support for extensible,
hierarchical data types. Applications typically use Apple events to request services
and information from other applications, or to provide services and information in
response to such requests. You can define your own custom events to suit your
needs, but, to increase interoperability with other applications, it’s a good idea to
make the effort to adopt the standard set of Apple events documented by Apple.
Apple event objects can take a significant amount of time to create, so you will not
usually want to use Apple events in performance-critical situations. To improve
AppleEvent creation performance, try using the Carbon AEBuild and AEStream
utilities, which are often significantly faster than AEPutDesc and AEPutParam.
Distributed notifications are ideal for simple notification-type events. For example,
a notification might communicate the status of a certain piece of critical hardware,
such as the network interface, or a typesetting machine.
There is no way to restrict the set of processes that are allowed to receive a
distributed notification. Any process which registers for a given notification may
receive it. Because distributed notifications use a string for the unique registration
key, there exists potential for namespace conflicts.
There are two primary variants of sockets, file and network. File sockets are
addressed as filenames and for various reasons do not support communication
between processes on different machines. Network sockets are addressed using the
network host name combined with the port number (for example, www.apple.com
and 80). Both types of sockets are read and written using the POSIX calls read and
write,
Using CFSocket with CFRunLoop allows you to multiplex data received from a
socket with data received from other sources. This allows you to keep the number
of threads in your application to an absolute minimum, which is good for
performance. CFMessagePort can also work with CFRunLoop.
Unnamed pipes must be created by a common ancestor process which then hands
the pipe descriptor number to both child processes. This facility is typically used by
the command line shell to connect processes which have been piped together (for
example, “cat magic.txt | grep -e Gwendoyln“ sends the contents of magic.text to
the grep command via the C library console input stream).
A named pipe is represented by a file in the file system called a FIFO special file. A
named pipe must be created with a unique name known to both the sending and
receiving processes.
Reading and writing small amounts of data to a pipe can occur atomically if the size
of the data written is below a certain, kernel-specified size. This allows the receiving
end of the named pipe to avoid reading a partial buffer.
The most typical use of signals is by the kernel, which uses signals to notify a
process of exceptional conditions such as invalid address errors and divide-by-zero
errors. Another typical use is the command-line kill tool, which is capable of
sending any user-specified signal to a process, though the most common use is to
terminate a process with SIGHUP.
Signals are complex to use effectively, and they tend to behave differently
(sometimes unreliably) on different operating systems. The signal namespace,
being composed of a single integer, is limited, and collisions with either third-party
signal numbers or numbers provided by future versions of the operating system are
possible. As such, signals should generally be avoided for normal interprocess
communication needs.
Shared memory has two distinct advantages over other forms of interprocess
communication:
■ Any process with appropriate permissions may read or write a shared memory
region.
■ The data is never copied, because any process can directly read it.
The disadvantage of shared memory is that it is very fragile. When a data structure
in a shared memory region is corrupted, all processes which reference that data
structure are also corrupted. For this reason, shared memory is best used simply as
a repository for raw storage of data (such as raw pixels or audio), with the controlling
data structures accessed through more conventional interprocess communication.
Because the sending and receiving process are scheduled independently of each
other, there is no guarantee that a given process will be free to receive a message
sent to it at any given time. Therefore, arriving messages are placed in a queue and
retrieved at the convenience of the receiving process.
Processes may not access a given port without appropriate access permissions (or
“port rights“ in Mach terminology). The inherent stability of the Mach kernel is
partly attributable to this mechanism.
You should not use Mach messaging directly if other alternatives are available,
because the interfaces may change in future versions of the kernel.
The Mach port object is not related to and should not be confused with the internet
address port number as used in BSD sockets (see “Communicating With BSD
Sockets” (page 265)). The Mach port object is also not related to the Carbon graphics
port primitive (GrafPort).
This section provides a comparative overview of the dyld and CFM runtimes as
well as the executable formats of the code and data they operate upon. For a more
detailed discussion of the CFM-based runtime environment, see the Carbon
documentation on the Code Fragment Manager, especially the chapter “CFM-Based
Runtime Architecture.” In this book, see “Dynamic Shared Libraries” (page 146) in
the chapter ““Frameworks” (page 141)” for a description of the dynamic link editor.
Also, see “CFM Executables” (page 231) for a description of how to prepare a CFM
executable for Mac OS X.
The major difference in the behavior of the dyld and CFM library managers is when
they resolve these references and bind them to addresses in the appropriate
libraries. CFM takes a static approach; it prepares each container of code and data
(called a fragment) as a unit (called a closure). At build time, CFM finalizes the
executable by determining where the various referenced symbols will exist at
runtime. The dyld library manager, on the other hand, attempts to resolve all
undefined symbols at runtime. More specifically, symbols are resolved only as they
are referenced during program execution. The dyld manager links code modules in
a dynamic shared library only as they are needed.
PEF and Mach-O are similar in many respects. They both define sections (or
segments) for code, global data, non-constant data, and so on. Where they primarily
differ is their allowance for multiple containers. PEF is a format for a container (a
fragment) that maps one-to-one to an executable. In the dyld world, however, an
executable can be composed from multiple Mach-O containers (object files).
Code-Generation Models
Although they are significant, the major differences discussed so far between
library managers and their executable formats do not explain why a CFM-based
program cannot directly call a function in a dyld-based library. The real source of
incompatibility between the CFM runtime and the dyld runtime is the different
external calling conventions used by their code-generation models. The differences
affect the representation of C function pointers and the way global data is accessed.
■ The CFM code-generation model uses a pointer to a TVector as the basis for
function pointers. It accesses global data indirectly via the R2 register, using it as
a base pointer to the global data. This method of access is known as TOC.
■ The dyld code-generation model uses a simple pointer to code as the basis for
function pointers. It accesses global data relative to code, using an offset from a
base address. This method of access is known as GOT.
Vector Libraries
All system frameworks in Mac OS X are based on dyld and Mach-O. Some of these
frameworks contain Carbon APIs. Therefore, if you have a CFM-based Carbon
application or library, your code needs to call functions in these system
frameworks. Apple has made it possible for CFM-based code to call functions in a
dyld-based framework through a technology called a vector library. A vector
library functions as a bridge for a system framework that contains Carbon APIs.
Part of this bridge is a vector or jump table that provides the “glue” code to handle
the differences in code-generation models. A CFM-based client (application or
library) can use these vector libraries and thereby access the Carbon APIs in the
associated dyld-based framework.
Note that vector libraries do not bridge in the other direction—from a dyld
application or framework into a CFM library. It is possible to call from dyld to CFM
using a CFBundle, but this solution is not appropriate for all situations. In general,
if you want a library to be available to all of the Mac OS X execution environments,
you should build it as a dyld-based library.
The system does provide another mechanism for accessing non-Carbon APIs in
system frameworks: the bundle. You can create a dyld-based bundle that links with
a non-Carbon framework and is therefore able to directly call the framework’s
functions. A CFM application can then use the Carbon bundle APIs (specifically
Core Foundation Bundle Services) to load the bundle and use it to call into the
non-Carbon framework. Figure 14-2 illustrates how this is done.
CFM dyld
MyCarbonApp.app MyBundle.bundle
Carbon.framework System.framework
2. Loads
This appendix describes the keys you can specify in property list files for bundles
and packages.
Bundle Keys
Information about a bundle is specified using property lists inside the bundle
directory. The Finder and system APIs use this information when several situations.
Bundles support the following types of keys:
■ Core Foundation keys—specify general bundle properties
■ Cocoa-specific keys—specify properties for bundles written using Cocoa
■ Finder-specific keys—specifies information used by the Finder and file system
■ Launch Services keys—specifies information used by Launch Services.
CFBundleDevelopmentRegion
The CFBundleDevelopmentRegion key specifies a string value identifying the
native region for the bundle. Usually, this value corresponds to the native language
of the person who wrote the bundle. This value is used as the last resort if a resource
cannot be located for the user’s preferred region or language.
CFBundleDisplayName
The CFBundleDisplayName key specifies a string value identifying the display
name of the bundle. This is the name that the Finder and other user interface
elements display to the user. It does not necessarily correspond to the name of the
bundle in the file system. This key can be localized by including it in the
InfoPlist.strings file of the appropriate .lproj subdirectory. If you localize this
key, you should also provide a localized version of the CFBundleName key.
See “Localizing File System Names” (page 178) for more information on display
names.
CFBundleDocumentTypes
The CFBundleDocumentTypes key contains an array of dictionaries, each of which
contains information about a document type supported by the application. Each
dictionary is called a type-definition dictionary and contains keys used to define the
document type. Table A-2 lists the keys that are supported in a type-definition
dictionary:
CFBundleExecutable
The CFBundleExecutable key identifies the name of the bundle’s main executable
file. For an application, this is the application executable. For a loadable bundle, it
is the binary that will be loaded dynamically by the bundle. For a framework, it is
the shared library for the framework. Project Builder automatically adds this key to
the Info.plist file of appropriate projects.
For frameworks, the executable name is required to be the same as the framework
name for launch-performance reasons. The executable name should not include any
extension that may be used on various platforms.
Important
You must include a valid CFBundleExecutable key in your
bundle’s Info.plist file. Mac OS X uses this key to locate the
bundle’s executable or shared library in cases where the user
renames the application or bundle directory.
CFBundleGetInfoHTML
The CFBundleGetInfoHTML key identifies the human-readable HTML string
displayed in the Info window of the bundle. You can specify this key-value pair
instead of the plain text CFBundleGetInfoString if you want a richer representation
in the Info window. You can localize this string by including it in the
InfoPlist.strings file of the appropriate .lproj directory.
CFBundleGetInfoString
The CFBundleGetInfoString key identifies a human-readable plain text string
displayed in the Info window of the bundle. (This string was also known as the long
version string in Mac OS 9). The format of the key should conform to the long
version string of Mac OS 9, for example, “2.2.1, © Great Software, Inc, 1999”. You
can localize this string by including it in the InfoPlist.strings file of the
appropriate .lproj directory.
CFBundleHelpBookFolder
The CFBundleHelpBookFolder key identifies the folder containing the bundle’s
help files. Help is usually localized to a specific language, so the folder specified by
this key represents the folder name inside the .lproj directory for the selected
language.
CFBundleHelpBookName
The CFBundleHelpBookName key identifies the main help page for your
application. This key identifies the name of the Help page, which may not
correspond to the name of the HTML file. The Help page name is specified in the
CONTENT attribute of the help file’s META tag.
CFBundleIconFile
The CFBundleIconFile key identifies the file containing the icon for the bundle. The
filename you specify does not need to include the.icns extension, although you can.
The Finder looks for the icon file in the Resources directory of the bundle.
If your bundle uses a custom icon, you must specify this property. If you do not
specify this property, the Finder (and other applications) display your bundle with
a default icon.
CFBundleIdentifier
The CFBundleIdentifier key specifies a unique identifier string for the bundle. This
identifier should be in the form of a Java-style package name, for example
com.apple.myapp. The bundle identifier can be used to locate the bundle at runtime.
The preferences system uses this string to identify applications uniquely.
CFBundleInfoDictionaryVersion
The CFBundleInfoDictionaryVersion key identifies the current version of the
property list structure. This key exists to support future versioning of the
Info.plist format. Project Builder generates this key automatically when you build
a bundle.
CFBundleName
The CFBundleName key identifies the short name of the bundle. This name should
be less than 16 characters long and be suitable for displaying in the menu and the
About box. This key can be localized by including it in the InfoPlist.strings file of
the appropriate .lproj subdirectory. If you localize this key, you should also
provide a localized version of the CFBundleDisplayName key.
CFBundlePackageType
The CFBundlePackageType key identifies the type of the bundle and is analogous
to the Mac OS 9 file type code. The value for this key consists of a four-letter code.
For applications, this code is 'APPL'; for frameworks, it is 'FMWK'; for loadable
bundles, it is 'BNDL'. For loadable bundles, you can also choose a type code that is
more specific than 'BNDL' if you want.
CFBundleShortVersionString
The CFBundleShortVersionString key identifies the marketing-style version of the
bundle. The marketing-style version string usually displays the major and minor
version of the bundle. This string is usually of the form n.n.n where n represents a
number. The first number is the major version number of the bundle. The second
and third numbers are minor revision numbers. The value of this key is displayed
in the default About box for Cocoa applications.
The value for this key differs from the value for the CFBundleVersion key, which
identifies a specific build number. The CFBundleShortVersionString value
represents a more formal version that does not change with every build.
CFBundleSignature
The CFBundleSignature key identifies the creator of the bundle and is analogous to
the Mac OS 9 file creator code. The value for this key consists of a four-letter code
that is specific to each bundle.
CFBundleURLTypes
The CFBundleURLTypes key contains an array of dictionaries describing the URL
schemes supported by the application. The purpose of this key is similar to that of
the CFBundleDocumentTypes key, but it describes URL schemes instead of
document types. Each dictionary entry corresponds to a single URL scheme. Table
A-3 lists the keys to use in each dictionary entry.
CFBundleVersion
The CFBundleVersion key specifies an application-specific string for identifying the
build number. The value of this key typically changes between builds and is
displayed in the Cocoa About panel in parenthesis.
Application-Specific Keys
Table A-4 lists the keys that are applicable to Application bundles only:
CFAppleHelpAnchor
The CFAppleHelpAnchor key identifies the name of the bundle’s initial HTML help
file, minus the .html or .htm extension. This file is located in the bundle’s localized
resource directories or, if non-localized, directly under the Resources directory.
NSAppleScriptEnabled
The NSAppleScriptEnabled key identifies whether the application is scriptable. Set
the value of this string to “Yes” if your application supports AppleScript.
NSHumanReadableCopyright
The NSHumanReadableCopyright key contains a string with copyright
information for the bundle. You can load this string and display it in an About
dialog box. This key is usually in the InfoPlist.strings file because it needs to be
localized.
NSJavaNeeded
The NSJavaNeeded key contains a Boolean value that determines whether the Java
VM must be loaded and started up prior to executing the bundle code. You can also
specify a string type with the value “YES” instead of a Boolean value if desired.
NSJavaPath
The NSJavaPath key contains an array of paths. Each path points to a Java class. The
path can be either an absolute path or a relative path from the location specified by
the NSJavaRoot key. The development environment (or, specifically, its jamfiles)
automatically maintains the values in the array.
NSJavaRoot
The NSJavaRoot key contains a string identifying a directory. This directory
represents the root directory of the application’s Java class files.
NSMainNibFile
The NSMainNibFile key contains a string with the name of the application’s main
nib file (minus the .nib extension). A nib file is an Interface Builder archive
containing the description of a user interface along with any connections between
the objects of that interface. The main nib file is automatically loaded when an
application is launched. Mac OS X looks for a file whose name matches the name of
the application.
NSPrincipalClass
The NSPrincipalClass key contains a string with the name of a bundle’s principal
class. The principal class should have a central relation to other classes in the
bundle. For applications, this name is the application name by default.
NSServices
The NSServices key contains an array of dictionaries specifying the services
provided by an application. Table A-5 lists the keys for specifying a service:
LSBackgroundOnly
If this key exists and is set to “1”, Launch Services runs the application in the
background only. You can use this key to create faceless background applications.
You should also use this key if your application uses higher-level frameworks that
connect to the window server, but are not intended to be visible to users.
Background applications must be compiled as Mach-O executables. This option is
not available for CFM applications.
You can also specify the type of this key as Boolean or Number. However, these type
values are only supported in Mac OS X 10.2 or later.
LSPrefersCarbon
If this key is set to “1,” the Finder displays the “Open in the Classic environment”
control in the application’s Get Info panel, and leaves the control unchecked by
default. The user can modify this control to launch the application in the Classic
environment if desired.
You can also specify the type of this key as Boolean or Number. However, these type
values are only supported in Mac OS X 10.2 or later. If you include this key in your
property list, do not include the LSPrefersClassic, LSRequiresCarbon, or
LSRequiresClassic keys.
LSPrefersClassic
If this key is set to “1,” the Finder displays the “Open in the Classic environment”
control in the application’s Get Info panel, and puts a check mark in the control by
default. The user can modify this control to launch the application in the Carbon
environment if desired.
You can also specify the type of this key as Boolean or Number. However, these type
values are only supported in Mac OS X 10.2 or later. If you include this key in your
property list, do not include the LSPrefersCarbon, LSRequiresCarbon, or
LSRequiresClassic keys.
LSRequiresCarbon
If this key is set to “1,” Launch Services runs the application in the Carbon
environment only. Use this key if your application should not be run in the Classic
environment.
You can also specify the type of this key as Boolean or Number. However, these type
values are only supported in Mac OS X 10.2 or later. If you include this key in your
property list, do not include the LSPrefersCarbon, LSPrefersClassic, or
LSRequiresClassic keys.
LSRequiresClassic
If this key is set to “1,” Launch Services runs the application in the Classic
environment only. Use this key if your application should not be run in the Carbon
compatibility environment.
You can also specify the type of this key as Boolean or Number. However, these type
values are only supported in Mac OS X 10.2 or later. If you include this key in your
property list, do not include the LSPrefersCarbon, LSPrefersClassic, or
LSRequiresCarbon keys.
LSUIElement
If this key is set to “1”, Launch Services runs the application as a user interface
element. User interface elements do not appear in the Dock or in the Force Quit
window. Although they typically run as background applications, they can come to
the foreground to present a user interface if desired. A click on a window belonging
to a user interface element brings that application forward to handle events.
The Dock and loginwindow are two applications that run as user interface
elements.
CFBundleInstallerInfo
The root key for application package information is the CFBundleInstallerInfo key.
This key specifies a dictionary that contains the keys shown in Table A-7. The
Required column lists the keys that you must have to support this feature.
APInstallerURL
The APInstallerURL key identifies the base path to the files you want to install. You
must specify this path using the form file://localhost/path/. All installed files
must reside within this directory.
APFiles
The APFiles key specifies a dictionary with or more files you want to install. Each
dictionary entry can contain the description for a file or directory. You can nest the
APFiles key inside itself to specify files inside of a directory. Table A-8 lists the keys
for specifying information about a single file or directory.
295
Apple Computer, Inc. July 2002
G L O S S A R Y
bit depth The number of bits used to bytecode is contained in a binary file with a
describe something, such as the color of a .class suffix. (Strictly speaking, “bytecode”
pixel. Each additional bit in a binary number means that the individual instructions are
doubles the number of possibilities. one byte long, as opposed to PowerPC code,
for example, which is four bytes long.) See
bitmap A data structure that represents the also virtual machine (VM).
positions and states of a corresponding set of
pixels. Carbon An application environment in
Mac OS X that features a set of programming
BSD Berkeley Software Distribution. interfaces derived from earlier versions of the
Formerly known as the Berkeley version of Mac OS. The Carbon APIs have been
UNIX, BSD is now simply called the BSD modified to work properly with Mac OS X,
operating system. The BSD portion of Mac especially with the foundation of the
OS X is based on 4.4BSD Lite 2 and FreeBSD, operating system, the kernel environment.
a “flavor” of 4.4BSD. Carbon applications can run in Mac OS X,
Mac OS 9, and all versions of Mac OS 8 later
buffered window A window with a than Mac OS 8.1.
memory buffer into which all drawing is
rendered. All graphics are first drawn in the CFM Code Fragment Manager, the library
buffer, then the buffer is flushed to the manager and code loader for processes based
screen. on PEF (Preferred Executable Format) object
files (Carbon).
bundle A directory in the file system that
stores executable code and the software class In object-oriented languages such as
resources related to that code. Applications, Java and Objective-C, a prototype for a
plug-ins, and frameworks are types of particular kind of object. A class definition
bundles. Except for frameworks, bundles are declares instance variables and defines
file packages, presented by the Finder as a methods for all members of the class. Objects
single file. that belong to the same class have the same
types of instance variables and have access to
bytecode Computer object code that is the same methods (included the instance
processed by a virtual machine. The virtual variables and methods inherited from
machine converts generalized machine superclasses).
instructions into specific machine
instructions (instructions that a computer's Classic An application environment in Mac
processor can understand). Bytecode is the OS X that lets you run non-Carbon legacy
result of compiling source language Mac OS software. It supports programs built
statements written in any language that for both Power PC and 68K chip architectures
supports this approach. The best-known and is fully integrated with the Finder and
language today that uses the bytecode and the other application environments.
virtual machine approach is Java. In Java,
296
Apple Computer, Inc. July 2002
G L O S S A R Y
297
Apple Computer, Inc. July 2002
G L O S S A R Y
demand paging An operating system not require their own copies of that code.
facility that causes pages of data to be With dynamic shared libraries, a program
brought from disk into physical memory not only attempts to resolve all undefined
only as they are needed. symbols at runtime, but attempts to do so
only when those symbols are referenced
device driver A component of an operating during program execution.
system that deals with getting data to and
from a device, as well as the control of that encryption The conversion of data into a
device. form, called ciphertext, that cannot be easily
understood by unauthorized people. The
domain An area of the file system reserved complementary process, decryption,
for software, documents, and resources and converts encrypted data back into its original
limiting the applicability of those items. A form.
domain is segregated from other domains.
There are four domains: user, local, network, Ethernet A high-speed local area network
and system. technology.
298
Apple Computer, Inc. July 2002
G L O S S A R Y
file system A part of the kernel HFS Hierarchical File System. The Mac OS
environment that manages the reading and Standard file-system format, used to
writing of data on mounted storage devices represent a collection of files as a hierarchy of
of a certain volume format. A file system can directories (folders), each of which may
also refer to the logical organization of files contain either files or folders themselves.
used for storing and retrieving them. File HFS is a two-fork volume format.
systems specify conventions for naming files,
for storing data in files, and for specifying HFS+ Hierarchical File System Plus. The
locations of files. See also volume format. Mac OS Extended file-system format. This
file-system format was introduced as part of
firewall Software (or a computer running Mac OS 8.1, adding support for filenames
such software) that prevents unauthorized longer than 31 characters, Unicode
access to a network by users outside of the representation of file and directory names,
network. (A physical firewall prevents the and efficient operation on very large disks.
spread of fire between two physical HFS+ is a multiple-fork volume format.
locations; the software analog prevents the
unauthorized spread of data). host The computer that’s running (is host
to) a particular program. The term is usually
fork (1) A stream of data that can be opened used to refer to a computer on a network.
and accessed individually under a common
filename. The Mac OS Standard and information property list A property list
Extended file systems store a separate data that contains essential configuration
fork and a resource fork as part of every file; information for bundles. A file named
data in each fork can be accessed and Info.plist (or a platform-specific variant of
manipulated independently of the other. (2) that filename) contains the information
In BSD, fork is a system call that creates a property list and is packaged inside the
new process. bundle.
299
Apple Computer, Inc. July 2002
G L O S S A R Y
300
Apple Computer, Inc. July 2002
G L O S S A R Y
makefile A specification file used by the other to talk to hosts inside; the operating
program to build an executable version of an system provides facilities for passing
application. A makefile details the files, information between the two.
dependencies, and rules by which the
application is built. multitasking The concurrent execution of
multiple programs. Mac OS X uses
memory-mapped file A file whose preemptive multitasking. Mac OS 8 and 9 use
contents are mapped into memory. The cooperative multitasking.
virtual-memory system transfers portions of
these contents from the file to physical network A group of hosts that can directly
memory in response to page faults. Thus, the communicate with each other.
disk file serves as backing store for the code
or data not immediately needed in physical nonretained window A window without
memory. an off-screen buffer for screen pixel values.
301
Apple Computer, Inc. July 2002
G L O S S A R Y
NFS Network File System. An NFS file type’s functions offer access to most values of
server allows users on the network to share these fields. An opaque type is roughly
files on other hosts as if they were on their equivalent to a class in object-oriented
own local disks. programming.
object A programming unit that groups Open Source A definition of software that
together a data structure (instance variables) includes freely available access to source
and the operations (methods) that can use or code, redistribution, modification, and
affect that data. Objects are the principal derived works. The full definition is available
building blocks of object-oriented programs. at www.opensource.org.
302
Apple Computer, Inc. July 2002
G L O S S A R Y
303
Apple Computer, Inc. July 2002
G L O S S A R Y
process A BSD abstraction for a running defines or initiates an event and the event
program. A process’ resources include a occurs instantaneously, the computer is said
virtual address space, threads, and file to be operating in real time. Real-time
descriptors. In Mac OS X, a process is based support is especially important for
on one Mach task and one or more Mach multimedia applications.
threads.
reentrant The ability of code to process
property list A structured, textual multiple interleaved requests for service
representation of data that uses the nearly simultaneously. For example, a
Extensible Markup Language (XML) as the reentrant function can begin responding to
structuring medium. Elements of a property one call, be interrupted by other calls, and
list represent data of certain types, such as complete them all with the same results as if
arrays, dictionaries, and strings. the function had received and executed each
call serially.
Pthreads The POSIX Threads package
(BSD). resolution The number of pixels
(individual points of color) contained on a
RAM Random-access memory. Memory display monitor, expressed in terms of the
that a microprocessor can either read or write number of pixels on the horizontal axis and
to. the number on the vertical axis. The
sharpness of the image on a display depends
raster graphics Digital images created or on the resolution and the size of the monitor.
captured (for example, by scanning in a The same resolution will be sharper on a
photo) as a set of samples of a given space. A smaller monitor and gradually lose
raster is a grid of x-axis (horizontal) and sharpness on larger monitors because the
y-axis (vertical) coordinates on a display same number of pixels are being spread out
space. (Three-dimensional images also have over a larger area.
a z-coordinate.) A raster image identifies the
monochrome or color value to illuminate resource Anything used by executable
each of these coordinates with. The raster code, especially by applications. Resources
image is sometimes referred to as a bitmap include images, sounds, icons, localized
because it contains information that is strings, archived user-interface objects, and
directly mapped to the display grid. A raster various other things. Mac OS X supports both
image is usually difficult to modify without Resource Manager–style resources and
loss of information. Examples of raster-image “per-file” resources. Localized and
file types are BMP, TIFF, GIF, and JPEG files. nonlocalized resources are put in specific
See also vector graphics. places within bundles.
real time In reference to operating systems,
a guarantee of a certain capability within a
specified time constraint, thus permitting
predictable, time-critical behavior. If the user
304
Apple Computer, Inc. July 2002
G L O S S A R Y
305
Apple Computer, Inc. July 2002
G L O S S A R Y
306
Apple Computer, Inc. July 2002
G L O S S A R Y
umbrella framework A system framework VFS Virtual File System. A set of standard
that includes and links with constituent internal file-system interfaces and utilities
subframeworks and other public that facilitate support for additional file
frameworks. An umbrella framework systems. VFS provides an infrastructure for
“contains” the system software defining an file systems built in the kernel.
application environment or a layer of system
software. See also subframework. virtual address A memory address that is
usable by software. Each task has its own
Unicode A 16-bit character set that assigns range of virtual addresses, which begins at
unique character codes to characters in a address zero. The Mach operating system
wide range of languages. Unlike ASCII, makes the CPU hardware map these
which defines 128 distinct characters addresses onto physical memory only when
typically represented in 8 bits, there are as necessary, using disk memory at other times.
many as 65,536 distinct Unicode characters See also physical address.
that represent the unique characters used in
many languages. virtual machine (VM) A simulated
computer in that it runs on a host computer
vector graphics The creation of digital but behaves as if it were a separate computer.
images through a sequence of commands or The Java virtual machine works as a
mathematical statements that place lines and self-contained operating environment to run
shapes in a two-dimensional or Java applications and applets.
three-dimensional space. One advantage of
vector graphics over bitmap graphics (or virtual memory The use of a disk partition
raster graphics) is that they makes it possible or a file on disk to provide the same facilities
to change any element of the picture at any usually provided by RAM. The
time since each element is stored as an virtual-memory manger in Mac OS X
independent object. Another advantage of provides 32-bit (minimum) protected
vector graphics is that the resulting image file address space for each task and facilitates
is typically smaller than a bitmap file efficient sharing of that address space.
containing the same image. Examples of
vector-image file types are PDF, volume A storage device or a portion of
encapsulated PostScript (EPS), and SVG. See that device that is formatted to contain
also raster graphics. folders and files of a particular file system. A
hard disk, for example, may be divided into
versioning With frameworks, schemes to several volumes (also known as partitions).
implement backward and forward
compatibility of frameworks. Versioning volume format The structure of file and
information is written into a framework’s folder (directory) information on a hard disk,
dynamic shared library and is also reflected a partition of a hard disk, a CD-ROM, or
in the internal structure of a framework. See some other volume mounted on a computer
also major version; minor version. system. Volume formats can specify such
things as multiple forks (HFS and HFS+),
307
Apple Computer, Inc. July 2002
G L O S S A R Y
308
Apple Computer, Inc. July 2002
Index
309
© Apple Computer, Inc. July 2002
INDEX
C
B canonical text encoding 187
Carbon environment 60–63
background processes, terminating 105 CFM-based code and 271–273
Base Services 80 documentation website 63
bill of materials file. See .bom file event handling in 87
.bom file 253 introduced 56
boot volume 166 Launch Services keys 290
booting sequence 89–100, 105 nib files 236
BOOTP. See Bootstrap Protocol Carbon Event Manager 78, 86
BootROM 90 Carbon framework 75
bootstrap port server 91, 99, 102 Carbon graphics port primitive (GrafPort) 269
Bootstrap Protocol 47 Carbon managers in Core Services 82–83
BootX booter 90 Carbon Process Manager (CPM) 259
BSD Commands environment 56, 59 CarbonLib SDK 271
BSD operating system 34, 58 CD recording 45
BSD permissions 237–239 central directory 135
BSD pipes 266 CFAppleHelpAnchor key 284
CFBundle 214, 220
310
© Apple Computer, Inc. July 2002
INDEX
311
© Apple Computer, Inc. July 2002
INDEX
CUPS. See Common UNIX Printing System dynamic link editor (dyld) 146, 231, 269–273
cupsd daemon 95 dynamic linking 125, 146
Current directory 162 dynamic pager 92
custom controls 235 dynamic shared libraries 142, 146–148
dynamic_pager daemon 98
D
E
daemons
creating 107 Ethernet 46
launching 99, 106 event handling 85–87
overview 96–100 executable formats 269–273
DARPA protocol 99 extensions
Darwin 33–38 networking 35
data corruption, and shared memory 267 system 247
data forks, storing resources in 183, 227
defaults utility 112, 208
Desktop Folder 193
Desktop Printer Utility 248 F
Developer directory 174–175
device drivers 35, 58 FIFO (first-in, first-out) special file 266
device-driver loader 98 file encodings 186
DHCP. See Dynamic Host Configuration Protocol file packages 122
disc recording 45 file permissions 236–240
distributed notifications 265 File Reference Inspector 216
distributed objects 268 file sockets 266
DNS. See Domain Name Services file systems 36–37, 165–186
Dock 26 and Classic environment 245
documents domains 167–177
abstract types 201 kernel environment and 58
application roles and 201 localizing names 178–181
FAQ 226–231 locating folders 175
and Finder 194 organization 165–181
permissions for 241 resource paths 168
resources for 140 searching 177
typing 229 File Transfer Protocol 47
Domain Name Services 47 filename extensions
domains, file-system 167–177 hiding 177–178
dot-underscore prefix (._) 198 using 227
drag-and-drop installation of applications 250 file-system root 166
DVD recording 45 fileSystemRepresentation method 187
dyld (dynamic link editor) 146, 231, 269–273 Finder 26–27, 189–198
.dylib extension 146 attributes of files and folders 194
Dynamic Host Configuration Protocol 47 bundles and 122, 131
312
© Apple Computer, Inc. July 2002
INDEX
313
© Apple Computer, Inc. July 2002
INDEX
314
© Apple Computer, Inc. July 2002
INDEX
315
© Apple Computer, Inc. July 2002
INDEX
316
© Apple Computer, Inc. July 2002
INDEX
Q sendmail daemon 96
Service Location Protocol 47
Quartz 38–40, 67–69 Services menu 32, 268
Quartz 2D 39, 67, 70–80 Setup Assistant 100, 240
Quartz Compositor 39, 67, 70 shared application code 135
Quartz Extreme 39, 52 See also frameworks
QuickDraw 40, 187 shared frameworks 135
QuickTime 41, 57 shared libraries. See dynamic shared libraries
shared memory 267
SharedFrameworks directory 122, 134
SharedSupport directory 136
R sharing files 170
sheets 26
raster printers 43 Sherlock 32
rc script 91, 92 signal handler routines 267
rc.boot script 91, 92 signals, BSD 267
Read Me files 254 Simple Object Access Protocol 48
Rendezvous 49, 94 SLP. See Service Location Protocol
resource forks 121, 183–186, 227 smbd daemon 95
Resource Manager 83, 121, 228 SOAP. See Simple Object Access Protocol
resource paths 168 sockets, BSD 265
resources software configuration 199–209
bundle structure and 117, 120 sshd daemon 95
external to application 138–140 standard keys for information property lists
localized. See localized resources 276–291
nonlocalized 145, 228 standard-error output 101
system-wide 257 startup items
used during installation 254–255 configuring 93
Resources directory 214, 255 conflicting names 109
root user 237, 240 core items 94
root volume 166 creating 105–109
routing, network 49 dependencies 93, 107
RPC (Remote Procedure Call) 99 overview 93
RTP (Real-Time Transport Protocol) 42 properties 107
RTSP (Real-Time Streaming Protocol) 42 restarting 109
Run Loop Services 81 starting 109
runtime environments 269–273 stopping 109
StartupParameters.plist file 93
stderr 101
Sticky keys. See Accessibility support
S String Services 81, 222
Samba 37, 95 .strings extension 126, 219
searching file systems 177 strings files 126, 218–222
semaphores 267 subframeworks 157, 160–162
superuser 237, 240
317
© Apple Computer, Inc. July 2002
INDEX
tasks 259
TCP. See Transmission Control Protocol
Terminal application 209 V
Text Encoding Conversion Manager 83
Text Utilities 83 vector libraries 271
Thread Manager 83, 261 Velocity Engine 39, 51
threading packages 260–261 versioned bundles 117, 122, 142
Time Manager 83 See also frameworks
TOC 271 Versions directory 162
tools, for developers 174 video frame buffer 39
Transmission Control Protocol 47 Virtual File System (VFS) 36, 57, 59
ttys file 111 virtual memory 34, 57, 98
TVector 271
type codes 194, 195
W
U WebDAV 37
window compositing 70
UDF (Universal Disk Format) 37 Window Manager daemon 96, 99, 111
318
© Apple Computer, Inc. July 2002
INDEX
X, Y
XML (Extensible Markup Language) 199
XML Parser 81
XML-RPC 48
Z
zero-configuration networking 49, 94
Zooming. See Accessibility support
319
© Apple Computer, Inc. July 2002
INDEX
320
© Apple Computer, Inc. July 2002