Buy this Book
Print Book $34.95 Read it Now!
Print Book £24.95
Add to UK Cart
Reprint Licensing
Learning Carbon
Learning Carbon

By Apple Computer, Inc.
Price: $34.95 USD
£24.95 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction to Carbon
The element carbon is an essential building block for life on earth. For C programmers, Apple's Carbon is the essential building block for applications on Mac OS X. With Carbon, you not only gain the benefits of Mac OS X, but you do so while using some of the simplest traditional C interfaces available. This combination makes it easier than ever to create world-class applications for a world-class operating system.
Carbon is the collection of C programming interfaces for Mac OS X, Apple's next-generation operating system.
A programming interface is the set of functions and data structures defined by one piece of software, such as an operating system service, for use by client software, such as applications and device drivers. For example, you would access one programming interface to enable your application to print and another to manipulate your application's menus.
Carbon was originally designed to support the evolution of the Mac OS. Apple updated and reimplemented programming interfaces written for earlier versions of the Mac OS to take advantage of new features and enhancements in Mac OS X. Mac OS X brings many modern operating-system features to the Macintosh, including:
  • Protected memory. Each application lives in its own address space, which prevents errant applications from crashing the system or other applications.
  • Preemptive multitasking. Each application is guaranteed processing time, resulting in a more responsive user experience.
  • Dynamic resource allocation. Your application can allocate memory and other shared resources based on actual needs rather than predetermined values, such as fixed memory allocations.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Carbon and Mac OS X
Carbon is the collection of C programming interfaces for Mac OS X, Apple's next-generation operating system.
A programming interface is the set of functions and data structures defined by one piece of software, such as an operating system service, for use by client software, such as applications and device drivers. For example, you would access one programming interface to enable your application to print and another to manipulate your application's menus.
Carbon was originally designed to support the evolution of the Mac OS. Apple updated and reimplemented programming interfaces written for earlier versions of the Mac OS to take advantage of new features and enhancements in Mac OS X. Mac OS X brings many modern operating-system features to the Macintosh, including:
  • Protected memory. Each application lives in its own address space, which prevents errant applications from crashing the system or other applications.
  • Preemptive multitasking. Each application is guaranteed processing time, resulting in a more responsive user experience.
  • Dynamic resource allocation. Your application can allocate memory and other shared resources based on actual needs rather than predetermined values, such as fixed memory allocations.
  • Aqua look and feel. Apple's new user interface is available only to applications that run natively on Mac OS X. Aqua provides a feast of visual effects—active buttons pulse, icons dance, windows spring to life—and showcases the sharpest graphics ever seen on a personal computer.
Carbon is especially useful for developers who need to update older Mac OS code to run on Mac OS X. This book doesn't cover this porting process, but if you're interested, see
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What's in Carbon?
Carbon contains thousands of functions, data structures, and constants, but don't worry, this book uses only a small number of these. Related functions and data structures are organized into functional groups, usually referred to as managers or services. For example, the Window Manager contains functions and data structures that let you create, remove, and otherwise manipulate application windows.
In this book you'll use functions from only a handful of these managers and services, most of which are commonly used in all Carbon applications. These interfaces cover the following functionality:
  • User interface creation and manipulation. That is, handling windows, menus, and other common graphical user interface (GUI) elements.
  • Event handling. How to find out when something happens and what to do when it does.
  • Basic string manipulation. How to put together text you want to display in a window.
  • Basic graphics rendering. How to display the text and windows on a screen.
  • Printing. How to print the text in a window.
  • Saving and opening files.
  • Help. How to implement a simple online help system and how to add informative "help tags" to buttons and other controls.
  • Storing and accessing resources. Mac OS X has a "bundle" feature that lets you store all the files an application needs in one easily accessible package.
You'll probably be surprised to see how few functions you need from each manager or service to implement basic functionality. That's what's great about Carbon on Mac OS X. The operating system and the development tools you'll use—Project Builder and Interface Builder—do most of the grunt work for you. For example, you might think you'd have to write a lot of complicated code to allow a user to drag a window around the screen. In actuality, you get this for free: the operating system automatically makes the appropriate calls for you and makes sure the dragged window behaves properly. Of course, if you need to control every aspect of an action or want to add custom features, Carbon lets you do that too. However, if you're willing to accept the standard behavior—and there is little reason not to—for most user interface elements, you'll have far less code to write.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building Carbon Applications
Because Carbon is just a collection of C programming interfaces, you can use just about any Macintosh C development environment that supports PowerPC to build Carbon applications. However, there are some limitations. For example, Carbon developers can create applications in two different executable formats:
  • Mach-O. This is the native executable format on Mac OS X. Mach-O-based executables can run only on Mac OS X.
  • PEF. The Preferred Executable Format (PEF) binary was the native executable format for PowerPC Mac OS systems before Mac OS X. With some work, PEF executables can run on Mac OS X as well as some earlier systems. Note that PEF applications are sometimes called CFM-based applications because the Code Fragment Manager is the mechanism for preparing and executing such files.
Older environments, such as Apple's MPW, can produce only PEF executables; while others, such as Metrowerks CodeWarrior, let you build either PEF or Mach-O versions. Which tool you use depends on what platforms you are targeting.
The tutorials in this book will use Project Builder and Interface Builder, which are Apple's development tools for building Mach-O-based applications on Mac OS X. Both tools have been written with Carbon in mind, and they come free with Mac OS X, making them excellent choices for new developers.
Project Builder and Interface Builder work in conjunction with each other to make building applications easier than ever:
  • Project Builder. The main development environment; it lets you create and assemble the components of your application. Being a user-friendly development environment, Project Builder gives you many standard application features for free, such as support for basic event handling.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Carbon Factory Tour
Because Carbon contains many, many programming interfaces, it can be quite daunting to a new developer. While this book provides a good start, at some point you will need to begin fending for yourself. What interfaces you will require depends on the type of applications you want to write, but as is often the case, some are more commonly used than others. This section divides up the Carbon interfaces according to usage (from fundamental to esoteric) and gives some useful information about each one. To learn more about a particular interface, you can use the Carbon Help feature integrated into Project Builder (to be described later in this book). You can also consult the technical documentation on the Apple developer web site.
This section covers the interfaces most likely to be called by a Macintosh application (and covers those that can be found in this book). These managers and services provide basic user interface functionality as well as fundamental features, such as the ability to save and print files. You can build basic but fully functional Carbon applications using the interfaces described here.
If Carbon were an interface to build automobiles, the Starter Kit interfaces would define the engine, wheels, brakes and other essential components, as well as the user interface (dashboard, steering wheel, gas and brake pedals, and so on).

Section 1.4.1.1: The Toolbox interfaces

The following interfaces are grouped together because they generally work together to create and manage the user interfaces. In most cases, Interface Builder and the Interface Builder Services interface can handle the creation and control of the basic user interface. However, to accomplish more esoteric tasks, you may need to call additional functions in one of these so-called Human Interface Toolbox interfaces:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Recap
We introduced Carbon, the C programming interface that lets you take advantage of features in Mac OS X, such as preemptive multitasking and protected memory. Carbon is a synthesis of old and new Mac OS technologies. Although there are many interfaces in Carbon, in most cases only a subset is essential for all applications. Others may be useful only for specialized needs or to support the porting of legacy applications. Of the numerous development environments available to build Carbon applications, this book will use Project Builder and Interface Builder, which are specifically designed for building applications on Mac OS X.
Next, we will design the application, a moon travel planning guide, that we will use to illustrate major Carbon programming concepts and methods.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Specifying a Carbon Application: Moon Travel Planner
Specifying a Carbon application is similar to specifying any application. You need to define the goal of the application, sketch out the interface, define the behavior of the interface, and outline the implementation details. Before you start creating the application, it's helpful to sort out what needs to be done in Interface Builder and what complementary things need to be done in Project Builder. Although you'll find yourself switching back and forth between the two development tools, once you get the hang of it, you'll see it's fairly easy and fast to create an application with a great looking interface.
You'll create a sample specification that shows:
  • Aspects of the interface that need to be created in Interface Builder and what needs to be done in Project Builder to support the interface
  • Other code that needs to be written in C using Project Builder
  • Items that should be created as a localizable file or other resource
  • Tasks taken care of by the operating system
You'll create the Moon Travel Planner application that's specified in this chapter throughout the course of the book. Once you define the goals of the sample application, the specification progresses according to what the user will see in the interface.
Windows and menus are the two basic elements users see in any interface. So you'll sketch out each window and menu, describe its behavior, and outline the implementation details. This chapter includes cross references to the chapters in which you'll actually implement the details.
You'll need a window to give the user an idea, in practical terms, of how far away the moon is from the earth. Let's call it the Moon Travel Planner window. You'll let the user compute the travel time to the moon for various modes of transportation. Figure 2.1 shows a sketch of what the main window of the application should look like. You'll use this sketch as a model when you actually create the interface.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Moon Travel Planner Window
You'll need a window to give the user an idea, in practical terms, of how far away the moon is from the earth. Let's call it the Moon Travel Planner window. You'll let the user compute the travel time to the moon for various modes of transportation. Figure 2.1 shows a sketch of what the main window of the application should look like. You'll use this sketch as a model when you actually create the interface.
Figure 2.1: The Moon Travel Planner window
The Moon Travel Planner window will display an image of the moon, a list of modes of transportation, a field that shows computed travel time, and two buttons. One button will compute travel time, and the other will quit the application. The window's title bar will display the words "Moon Travel Planner."
The window opens when the application launches and closes when the application quits. The user will be able to minimize the window so its icon displays in the Dock. The user should be able to quit the program by clicking the Quit button.
The Dock is a feature of Mac OS X that appears at the bottom of the monitor. The Dock displays an icon for each open application and minimized document, as well as web site links and commonly used items, such as System Preferences and Trash. It's designed to help combat onscreen clutter and to aid in organizing work.
When the user clicks the minimize button on a window, the window shrinks and moves to the Dock. If the user clicks the miniaturized window in the Dock, the window expands to full size.
The window should be movable, but it won't be resizable. It will become inactive when other windows are open.
When the pointer is placed over the graphic in the window, a help tag appears.
For the Moon Travel Planner, you'll need to use Interface Builder to:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Menu Bar
You'll need to use these standard Mac OS X menus: Application, File, Window, and Help. In the application menu, you'll use the About and Quit menu items, but you'll customize the About menu item for the Moon Travel Planner application.
There are five items in the File menu you'll need: Open, Close, Save As, Page Setup, and Print. The only kind of file the Moon Travel Planner will open is a special file you'll create that contains an itinerary. So you'll need to customize Open so it says Open Itinerary, and Save As so it says Save Itinerary As.
The Minimize item is the only item you'll need in the Window menu. You'll need one item in the Help menu—Moon Travel Planner Help.
You'll also need an application-specific menu you'll call Moon. The Moon menu needs two commands—one to open a window that shows information about the moon as a travel destination, and another to compute travel time. The sketch in Figure 2.2 shows the application-specific menu and menu items you'll need.
Figure 2.2: The menu bar for the Moon Travel Planner application
When a user presses a menu name, the menu should open and stay open as long as the user holds down the mouse button. When the user selects a menu item, a command will be issued and something will happen. Table 2.1 lists the menus and menu items you'll use in the Moon Travel Planner application and the action each should take.
Table 2.1: Menus, Menu Items, and Actions
MenuMenu ItemAction
ApplicationAbout Moon Travel Planner
Opens a window that shows version information.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The About Window
You'll need an About window to display version information for the application. Inside Mac OS X: Aqua Human Interface Guidelines (listed in Appendix A) contains specific guidelines for what should be in an About window, so you'll need to follow those. Figure 2.3 shows the minimum items you need to display—the application icon and version and copyright information for the application.
Figure 2.3: The About window for the Moon Travel Planner application
The window will open when the user chooses About Moon Travel Planner from the Moon Travel Planner application menu. Its title bar should display the words "About Moon Travel Planner." The user will be able to close the window. The user won't be able to modify or copy the text or change the size of the window.
In Interface Builder, you'll need to:
  • Create the window; define the window size, background, and title; add a static text field; adjust layout of the window; add an image resource for the application icon to the window. See Chapter 5 for details.
In Project Builder, you'll need to:
  • Add code to the main function to create the window from the Interface Builder file. See Chapter 6 for details.
  • Add version and application information to the project. See Chapter 10 for details.
  • Add an application icon file to your project. See Chapter 13 for details.
  • Write a handler that closes the About window when the user clicks the close button. See Chapter 10 for details.
You'll also need to use Icon Composer to create an icon suite for your application. See Chapter 13 for details.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Facts for the Traveler Window
You'll need a window to display some interesting facts for the prospective moon traveler. Figure 2.4 shows a sketch of what you'll create in the Moon Travel Planner application. You'll display the facts in a window that has an attractive border.
Figure 2.4: The Facts for the Traveler window for the Moon Travel Planner application
The window will open when the user chooses Show Facts from the Moon menu. The window's title bar should display the words "Facts for the Traveler." The user will be able to close and minimize the window. The user won't be able to modify or copy the text displayed in the window or to resize the window. The window should be movable and will become inactive when the user makes the main or itinerary window active.
Except where indicated, everything you need to implement the Facts for the Traveler window is described later, in Chapter 8. In Interface Builder, you'll need to:
  • Create the window; define the window size, background, and title.
  • Add a text field; assign an ID and signature to the text field; adjust the layout of the window.
In Project Builder, you'll need to:
  • Create content to display in the text field.
  • Add code to the main function to create the window from the nib file.
  • Write a function that gets the ID and signature of the text field, reads text from a localizable file, and displays the text in the text field.
  • Write a handler that closes the window when the user clicks the close button and one that responds to the Page Setup and Print commands by calling your functions for page setup and printing.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Itinerary Window
No travel planning application would be complete without providing the user with a few suggested itineraries. You'll need to create a window so the Moon Travel Planner application can display an itinerary of suggested activities for the moon tourist. Figure 2.5 shows an idea for one itinerary. You'll use a plain document window to display the contents of itinerary files provided with the Moon Travel Planner application.
The itinerary window opens when the user chooses an itinerary file from Open Itinerary under the File menu. It closes when the user clicks the Close button or chooses Close from the File menu. The user should save the itinerary under a new name.
Everything you need to implement for the itinerary window is described later, in Chapter 11. In Interface Builder, you'll need to:
  • Create an itinerary window in a new Interface Builder file.
In Project Builder, you'll need to:
  • Write functions to create the window from the Interface Builder file and dispose of it when it is no longer needed.
  • Write functions to allow the user to open and close an itinerary file and to save the file under a different name.
You won't need to write code to minimize the window. The operating system takes care of that.
Figure 2.5: The Itinerary window for the Moon Travel Planner application
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Recap
We've sketched the interface for the Moon Travel Planner application, detailed its behavior, and listed what you need to do to create the specified application. As you create the Moon Travel Planner in the rest of this book, you'll use this specification as your blueprint. You will rely on two tools—Interface Builder to create the interface and Project Builder to create the code. As you can see from the implementation details, when you create objects in Interface Builder you often need to do complementary tasks in Project Builder, such as write the supporting code for a menu command.
With specification in hand, you are ready to build the Moon Travel Planner application. You'll start in Chapter 3 by creating a skeletal application using Project Builder. Once you've had an opportunity to use Project Builder, you'll move on and create the interface using Interface Builder.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Project Builder Projects
Project Builder is an application that manages software development projects. It's Apple's integrated development environment (IDE) for Mac OS X, which provides a project browser, a full-featured code editor, language-savvy symbol recognition, advanced project-searching capabilities, documentation access, build and debugging support, and other features that can streamline the development process. With it, you can create such Mac OS X software projects as:
  • An application, which is a bundle that contains all the resources necessary to launch the application, including the application's executable files. A bundle is a folder packaged to look like a single file.
  • Frameworks, which are bundles that contain a dynamic shared library and all the resources that go with that library, such as header files, images, and documentation.
  • Kernel extensions, which are bundles the operating system loads into the kernel environment.
  • Libraries, which are code and resources that can't execute on their own, but that export functions and global variables for others to use; usually linked to an application when the application runs instead of when it's compiled.
  • Plug-ins, which are bundles that contain executable code and associated resources that must be loaded into a running application.
This chapter shows you how to create one type of software project—a Carbon application. You'll use the Carbon programming interfaces and the C language from within Project Builder's development environment to:
  • Look at the components of a Carbon application project
  • Examine the code you get "for free" with the Carbon application template
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Carbon Application Project
Before you start building your own application, let's take a tour of Project Builder. When Project Builder opens a new project for a Carbon application, you'll see a window similar to what's shown in Figure 3.1. The area near the top of the window contains buttons for building, cleaning (that is, deleting the current build products and intermediate products), running, and debugging. The Run and Debug buttons remain dimmed until you build a project.
Figure 3.1: A new project window for a Carbon application
The left side of Figure 3.1—Groups & Files—shows a list of file references. The right side of the figure shows the contents of the most recent Project Builder release notes. The vertical tabs let you switch between views of the project's files, bookmarks you save, and targets (should your project have more than one target). Let's look a bit more closely at file references and targets.
File references refer to the source files, resource files, libraries, and frameworks in your project. The important thing to remember is that, although the Groups & Files list shown in Figure 3.2 may look like a directory listing, the items in the list are references to files or folders on your hard disk; they are not the files or folders themselves.
Project Builder organizes the project's file references into four groups: Sources, Resources, External Frameworks and Libraries, and Products. You can move a file reference into any group you want. You can also add your own groups. Groups are there solely for your convenience and do not affect Project Builder's ability to find or compile the files. It's easier to manage large projects if you keep related files together. Let's take a closer look at what each group normally contains.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Moon Travel Planner: Creating a Project
Let's get some practice with Project Builder by creating a project from a Carbon application template, then building and running it. You'll create a new project for the Moon Travel Planner application we specified in Chapter 2. When you're done, you'll have an application that displays an empty window and lets you quit.
To create the Moon Travel Planner project, do the following:
  1. Double-click the Project Builder icon located in Mac OS X in the directory /Developer/Applications. The first time you open Project Builder, the Project Builder Assistant opens. You'll need to complete the setup process before you can proceed with the next step.
  2. Choose New Project from the File menu. A dialog opens with a list of template objects, as shown in Figure 3.12.
    Figure 3.12: Choosing the type of project
  3. Select Carbon Application (Nib Based), then click Next. Nib refers to a project that uses Interface Builder to create user interface resources. You'll use Interface Builder later to modify the default interface you get with the project.
  4. Type Moon Travel Planner as the project name (as shown in Figure 3.13) and click Set to choose a location to store the project. A sheet appears that lets you navigate to the location you want to store the project.
  5. Click Finish. The main window for Project Builder opens, with files for our new application in the Groups & Files list. Believe it or not, you now have a complete, although skeletal, application!
  6. Take a look at the main function by clicking main.c in the Groups & Files list. If you can't see the main.c file, click the Files tab and open the Sources group. You should see the same code shown in Example 3.1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Recap
At this point, you've gotten familiar with Project Builder, and you've created a skeletal Carbon project, built it, and run the built application. In the next chapter, you'll be introduced to Interface Builder and use it to create some of the interface objects you'll need for the Moon Travel Planner application.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Interface Builder: Nibs and Windows
Interface Builder is a WYSIWYG tool that lets you lay out user interfaces in a simple, intuitive manner. The interfaces you create are stored in a file called a nib file, which your application can then access to create its windows, menus, and other elements. Interface Builder provides you with:
  • Palettes to add interface elements
  • Menus that help you align and lay out the interface
  • Info windows to set up the behavior of interface elements
You can do so much with Interface Builder that it will take a couple of chapters to explore its features. In this chapter you'll:
  • Look at the components of a nib file
  • Check out what you can do with Info windows
  • Take a look at the types of windows you can create in Interface Builder
  • Use Interface Builder to modify a window
Then, you'll look at palettes and layout tools in Chapter 5 where you'll add controls to a window. In Chapter 7 you'll take a close look at the default menu bar provided by Interface Builder.
In the last chapter you saw that when Project Builder creates a Carbon (nib based) application, it provides a file named main.nib and puts it in the Resources group of the project. As you recall, the nib file contains the application's interface-based resources. It's an Interface Builder file (the "ib" in "nib" stands for Interface Builder) that contains descriptions of the interface elements in your application. These descriptions use Extensible Markup Language (XML).
In earlier versions of the Mac OS, developers created resources using either a resource compiler (such as Rez) or a utility program called a resource editor (such as Apple's ResEdit). The resources contained in a nib file are not the same as those contained in these old-style resources. In other words, you can't use Interface Builder to create old-style resources.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Carbon Nib File
In the last chapter you saw that when Project Builder creates a Carbon (nib based) application, it provides a file named main.nib and puts it in the Resources group of the project. As you recall, the nib file contains the application's interface-based resources. It's an Interface Builder file (the "ib" in "nib" stands for Interface Builder) that contains descriptions of the interface elements in your application. These descriptions use Extensible Markup Language (XML).
In earlier versions of the Mac OS, developers created resources using either a resource compiler (such as Rez) or a utility program called a resource editor (such as Apple's ResEdit). The resources contained in a nib file are not the same as those contained in these old-style resources. In other words, you can't use Interface Builder to create old-style resources.
Example 4.1 shows what's needed to create a File menu using old-style resources that rely on text-based descriptions. Interface Builder automatically provides the File menu for you and lets you customize this and other menus it provides using WYSIWYG tools. You don't need to know anything about old-style resources to create a Carbon application; we've provided the listing just so you can see how this style of resource compares to Interface Builder.
Example 4.1. Defining a Menu Using Text-Based Resources
resource 'MENU' (kFileMenuID, "File menu") 
   {
      kFileMenuID,               // Menu ID
      textMenuProc,              // Menu definition procedure
      0x7FFFFFFF,                // Enable/disable flags for menu items
      enabled,                   // Enable/disable flag for menu
      kMenuTitleFile,            // Menu title
      {
         kItemNameClose, noIcon,            // Close command
            kItemKeyClose, noMark, plain,

         "-", noIcon, noKey, noMark, plain, // Separator

         kItemNameQuit, noIcon,             // Quit command
            kItemKeyQuit, noMark, plain 
      }
   };
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Moon Travel Planner: Modifying the Default Window
The main window for the Moon Travel Planner application you created in Chapter 3 is rather boring at this point. It shows nothing and is named Window. It will take a few chapters to whip this window into shape so it looks like the sketch in Chapter 2. In this section we'll get started by doing the following:
  1. Open Interface Builder.
  2. Revise the window title so it says something other than "Window."
  3. Set Window Class, Controls, and Attributes.
  4. Set the window's size.
  5. Build and run the application to make sure it still works after our modifications.
The Interface Builder application is located in the /Developer/Applications folder. Although you can double-click the Interface Builder icon to open it, we'll open Interface Builder from within Project Builder. Most of the time you'll have both open and move between them as you modify the interface and add code.
To open Interface Builder from within Project Builder:
  1. Open the Moon Travel Planner project if it is not already open.
  2. Double-click the main.nib file, located in the Resources group.
The window's title is the text shown in the title bar (see Figure 4.6). You should change the title from Window to Moon Travel Planner:
  1. Double-click the MainWindow icon in the Instances pane.
  2. Choose Show Info from the Tools menu.
  3. Type Moon Travel Planner in the Title text field, as shown in Figure 4.9 and press Return.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Interface Builder: Toolsand Controls
Interface Builder provides palettes rich with controls and other items—such as push buttons, radio buttons, text labels, graphics, data browsers, and menus—you can add to your application's interface. Because Interface Builder uses graphical tools, it's fairly easy to create and lay out items in a window. The tricky part is to associate code with the controls so that when the user manipulates a control, the application responds.
You'll use Interface Builder in this chapter to:
  • Take a close look at the objects you can add to an interface using Interface Builder palettes
  • Check out the tools you can use to align interface objects in a window
  • Add controls and other objects to the main window of the Moon Travel Planner application
Then, in Chapter 6, you'll see how to write code that makes the controls spring to life.
To create an interface, you simply select the objects you want in the interface from one of Interface Builder's palettes, drag them to the appropriate location (a window, a menu, the desktop), and make sure the objects are arranged aesthetically, using Inside Mac OS X: Aqua Human Interface Guidelines as a guide. The guidelines are in Carbon Help (available in the Project Builder Help menu). For static objects, the job of adding them to the interface is done. For dynamic objects, you'll need to do a few more things.
Static objects include such things as a separator line in a menu, a text label, and a graphic. Dynamic objects include anything that changes, either because of a user's action or your application's. Some examples of dynamic objects include a window in which the user can edit text, a button the user can click, and a text field in which your application displays a computational result. Any interface you create will likely be a combination of both types of objects.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Palettes and Layout Tools
To create an interface, you simply select the objects you want in the interface from one of Interface Builder's palettes, drag them to the appropriate location (a window, a menu, the desktop), and make sure the objects are arranged aesthetically, using Inside Mac OS X: Aqua Human Interface Guidelines as a guide. The guidelines are in Carbon Help (available in the Project Builder Help menu). For static objects, the job of adding them to the interface is done. For dynamic objects, you'll need to do a few more things.
Static objects include such things as a separator line in a menu, a text label, and a graphic. Dynamic objects include anything that changes, either because of a user's action or your application's. Some examples of dynamic objects include a window in which the user can edit text, a button the user can click, and a text field in which your application displays a computational result. Any interface you create will likely be a combination of both types of objects.
When you add a dynamic object to the interface, you'll need to assign it a control ID or a command signature. You'll assign these in Interface Builder, then you'll use these same values in your code to get and set control states, to identify a command issued from a menu, and to display information in a control or a window.
A command signature is a four-character sequence that uniquely identifies a command to the Finder and your application. Signatures for commands defined by Apple (such as redo, undo, copy) contain all lowercase characters. To avoid any possible conflicts with any Apple commands, you should use at least one uppercase character in the command signatures you define.
A control ID consists of a signature (a four-character sequence) and an ID (a 32-bit integer) that you assign to a control so that you can identify and address the control when your application runs. To avoid confusion with a control ID from another application or plug-in, a control ID should be unique. The best way to assure it is unique is to use the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Moon Travel Planner: Adding Objectsto the Main Window
In the last chapter, you set up the main window for the Moon Travel Planner application. Now, you'll add objects to the main window so the window looks like the one we specified in Chapter 2. You'll need to do the following:
  1. Open the nib file.
  2. Add an item from the Enhanced Controls palette.
  3. Add items from the Controls palette.
  4. Add a PICT resource to the project.
  5. Align objects.
  6. Check the interface.
As you did in the last chapter, you'll open the nib file from the Moon Travel Planner project window:
  1. If it is not already open, open the Moon Travel Planner project.
  2. Double-click main.nib in the Resources group in the project window.
  3. In Interface Builder, double-click the MainWindow icon in the Instances pane.
As you recall, our sketch of the main window in Chapter 2 shows a graphic image at the top of the window, so let's start with that. To accomplish this, you'll add one object from the Enhanced Controls palette—a PICT control. A PICT control is really just a container for an image; you use it to lay out the interface. Later, you'll drag the image you want to appear in the interface on top of the PICT control.
  1. Choose Palettes from the Palettes submenu in the Tools menu.
  2. Click the Enhanced Controls button in the palette toolbar.
  3. Add a PICT control to the top center of the interface. This is a container for the image of the moon. Drag a PICT box from the Enhanced Controls palette to the top center of the Moon Travel Planner window. Just use the "eyeball" method to place the PICT in the middle, but make sure it is no higher than what the blue Aqua guide (shown in Figure 5.7) suggests. We'll explain how to lay out the interface later, in Section 5.2.5.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: Carbon Events
Everything a typical Carbon application does, whether interacting with the user or communicating with the system, takes place in response to an event sent to the application by the operating system. Events include any activity that requires a response by the application—user actions, changes in processing status, hardware activity, and other occurrences. The core task of any Carbon application is to respond to events.
Carbon supports two event-handling models, although only one is recommended. The first is the legacy Mac OS Event Manager model, referred to as the classic Event Manager. The second is the Carbon Event Manager model. It's the one we'll cover in this chapter, and the event model your Carbon application should use. An application that uses this model tells the Carbon Event Manager what events are of interest. Then the application doesn't do anything until the Carbon Event Manager detects one of the events the application wants to handle. So, when someone using your application is asleep at the keyboard, your application is simply waiting. No processing cycles are wasted; it's a very efficient model.
Another big advantage to using the Carbon Event Manager is that it greatly reduces the amount of code needed to write a basic application. It provides standard handlers for most types of user interaction, so you can concentrate on writing code that's unique to your application.
In this chapter, you'll look at Carbon events and how to handle them. In particular, you'll:
  • Get an overview of how events are handled with the Carbon Event Manager
  • Learn the essential terminology—event targets, types, and references
  • See what default handlers can do for you
  • Write a Carbon event handler
Let's follow a typical user event—a mouse click-through the system. The user clicks a button in the interface. The action of the user pressing a mouse button sets off a low-level event from the device driver that controls the mouse. The I/O Kit, which forms the foundation of all device drivers on Mac OS X, creates the event, puts it in the window server's event queue, and notifies the window server. (The window server is a core service that manages windows. All user actions occur in a window or in a menu associated with a window.) The window server takes the event off the queue, consults a database of open windows, then sends the event to the process that owns the window in which the event occurred. The Carbon Event Manager gets the event from the window server, packages it in an appropriate form, and passes it to the event-handler mechanism specific to the application. This mechanism ensures that the event is handled by the function associated with the control the user clicked. Figure 6.1 depicts the subsystems that generate, repackage, and forward an event to its destination.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Carbon Event Handling
Let's follow a typical user event—a mouse click-through the system. The user clicks a button in the interface. The action of the user pressing a mouse button sets off a low-level event from the device driver that controls the mouse. The I/O Kit, which forms the foundation of all device drivers on Mac OS X, creates the event, puts it in the window server's event queue, and notifies the window server. (The window server is a core service that manages windows. All user actions occur in a window or in a menu associated with a window.) The window server takes the event off the queue, consults a database of open windows, then sends the event to the process that owns the window in which the event occurred. The Carbon Event Manager gets the event from the window server, packages it in an appropriate form, and passes it to the event-handler mechanism specific to the application. This mechanism ensures that the event is handled by the function associated with the control the user clicked. Figure 6.1 depicts the subsystems that generate, repackage, and forward an event to its destination.
Figure 6.1: A mouse click handled by Mac OS X and the Carbon Event Manager
Carbon uses a callback mechanism to handle events. You define your application's response to various types of events by writing event handler functions and registering them with the Carbon Event Manager. Then, each time an event occurs, the Carbon Event Manager calls back the handler function you installed for that type of event.
Implementing handler-based event management in your application is fairly straightforward. It involves these steps:
  1. Identify the events your application must handle.
  2. Write handlers (functions) to respond to the events.
  3. Install the handlers. This informs the Carbon Event Manager of the events your application handles and which handlers respond to those events.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
MoonTravel Planner: Writing an Event Handler
Content preview·Buy PDF of this chapter|