Documentation  |   Table of Contents   |  < Previous   |  Next >   |  Index

1    Programming Palm OS in a Nutshell

Palm OS® Programmer's Companion

Volume I

     

This chapter is the place to start if you're new to Palm programming. It summarizes what's unique about writing applications for Palm Powered handhelds and tells you where to go for more in-depth information. It covers:

Read this chapter for a high-level introduction to Palm programming. The rest of this book provides the details.

Why Programming for Palm OS Is Different ^TOP^

Like most programmers, you have probably written a desktop application—an application that is run on a desktop computer such as a PC or a Macintosh computer. Writing applications for handhelds, specifically Palm Powered handhelds, is a bit different from writing desktop applications because the Palm Powered handheld is designed differently than a desktop computer. Also, users simply interact with the handheld differently than they do desktop computers.

This section describes how these differences affect the design of a Palm OS® application.

Screen Size ^TOP^

Most Palm Powered handheld screens are only 160x160 pixels, so the amount of information you can display at one time is limited.

For this reason, you must design your user interface carefully with different priorities and goals than are used for large screens. Strive for a balance between providing enough information and overcrowding the screen. See the book Palm OS User Interface Guidelines for more detailed guidelines on designing the user interface.

Note that screen sizes of future Palm Powered handhelds may vary. The Sony Clie already has a different screen resolution (320 X 320 pixels) than other Palm Powered handhelds although its screen is still the same size as other handhelds. The HandEra 330 has introduced the ability to rotate the display and the ability to collapse the input area. If the user collapses the input area, there is more space available to the application.

Quick Turnaround Expected ^TOP^

On a PC, users don't mind waiting a few seconds while an application loads because they plan to use the application for an extended amount of time.

By contrast, the average handheld user uses a handheld application 15 to 20 times per day for much briefer periods of time, usually just a few seconds. Speed is therefore a critical design objective for handhelds and is not limited to execution speed of the code. The total time needed to navigate, select, and execute commands can have a big impact on overall efficiency. (Also consider that Palm OS does not provide a wait cursor.)

To maximize performance, the user interface should minimize navigation between windows, opening of dialogs, and so on. The layout of application screens needs to be simple so that the user can pick up the product and use it effectively after a short time. It's especially helpful if the user interface of your application is consistent with other applications on the handheld so users work with familiar patterns.

The Palm OS development team has put together a set of design guidelines that were used as the basis for the applications resident on the handheld (Memo Pad, Address Book, and so on). These guidelines are summarized in the book Palm OS User Interface Guidelines.

PC Connectivity ^TOP^

PC connectivity is an integral component of the Palm Powered handheld. The handheld comes with a cradle that connects to a desktop PC and with software for the PC that provides "one-button" backup and synchronization of all data on the handheld with the user's PC.

Many Palm OS applications have a corresponding application on the desktop. To share data between the handheld's application and the desktop's application, you must write a conduit. A conduit is a plug-in to the HotSync® technology that runs when you press the HotSync button. A conduit synchronizes data between the application on the desktop and the application on the handheld. To write a conduit, you use the Conduit SDK, which provides its own documentation.

Input Methods ^TOP^

Most users of Palm Powered handhelds don't have a keyboard or mouse. Users enter data into the handheld using a pen. They can either write characters in the input area or use the keyboard dialog provided on the handheld.

While Graffiti® or Graffiti® 2 strokes and the keyboard dialog are useful ways of entering data, they are not as convenient as using the full-sized desktop computer with its keyboard and mouse. Therefore, you should not require users to enter a lot of data on the handheld itself.

Many Palm Powered handhelds support external keyboards, which are sold separately. Do not rely on your users having an external keyboard.

Power ^TOP^

Palm Powered handhelds run on batteries and thus do not have the same processing power as a desktop PC. The handheld is intended as a satellite viewer for corresponding desktop applications.

If your application needs to perform a computationally intensive task, you should implement that task in the desktop application instead of the handheld application.

Memory ^TOP^

Palm Powered handhelds have limited heap space and storage space. Different versions of the handheld have between 512K and 8MB total of dynamic memory and storage available. The handheld does not have a disk drive or PCMCIA support.

Because of the limited space and power, optimization is critical. To make your application as fast and efficient as possible, optimize for heap space first, speed second, code size third.

File System ^TOP^

Because of the limited storage space, and to make synchronization with the desktop computer more efficient, Palm OS does not use a traditional file system. You store data in memory chunks called records, which are grouped into databases. A database is analogous to a file. The difference is that data is broken down into multiple records instead of being stored in one contiguous chunk. To save space, you edit a database in place in memory instead of creating it in RAM and then writing it out to storage.

Backward Compatibility ^TOP^

Different versions of Palm Powered handhelds are available, and each runs a different version of Palm OS. Users are not expected to upgrade their versions of Palm OS as rapidly as they would an operating system on a desktop computer. Updates to the OS are designed in such a way that you can easily maintain backward compatibility with previous versions of the OS, and thus, your application is available to more users. See "Making Your Application Run on Different Devices" for details.

Palm OS Programming Concepts ^TOP^

Palm OS applications are generally single-threaded, event-driven programs. Only one program runs at a time. To successfully build a Palm OS application, you have to understand how the system itself is structured and how to structure your application.

  • Each application has a PilotMain function that is equivalent to main in C programs. To launch an application, the system calls PilotMain and sends it a launch code. The launch code may specify that the application is to become active and display its user interface (called a normal launch), or it may specify that the application should simply perform a small task and exit without displaying its user interface.

    The sole purpose of the PilotMain function is to receive launch codes and respond to them. (See Chapter 2, "Application Startup and Stop.")

  • Palm OS is an event-based operating system, so Palm OS applications contain an event loop; however, this event loop is only started in response to the normal launch. Your application may perform work outside the event loop in response to other launch codes. Chapter 3, "Event Loop," describes the main event loop.
  • Most Palm OS applications contain a user interface made up of forms, which are analogous to windows in a desktop application. The user interface may contain both predefined UI elements (sometimes referred to as UI objects), and custom UI elements. (See Chapter 4, "User Interface.")
  • All applications should use the memory and data management facilities provided by the system. (See Chapter 5, "Memory," and Chapter 6, "Files and Databases.")
  • You implement an application's features by calling Palm OS functions. Palm OS consists of several managers, which are groups of functions that work together to implement a feature. As a rule, all functions that belong to one manager use the same prefix and work together to implement a certain aspect of functionality.

    Managers are available to, for example, generate sounds, send alarms, perform network communication, and beam information through an infrared port. A good way to find out the capabilities of the Palm OS is to scan the Table of Contents of both this book and Palm OS Programmer's Companion, vol. II, Communications.


IMPORTANT: The ANSI C libraries are not part of the Palm development platform. In many cases, you can perform the same function using a Palm OS API call as you can with a call to a ANSI C function. For example, the Palm OS provides a string manager that performs many of the string functions you'd expect to be able to perform in an ANSI C program. If you do use a standard C function, the code for the function is linked into your application and results in a bigger executable.

API Naming Conventions ^TOP^

The following conventions are used throughout the Palm OS API:

  • Functions start with a capital letter.
  • All functions belonging to a particular manager start with a two- or three-letter prefix, such as "Ctl" for control functions or "Ftr" for functions that are part of the Feature Manager.
  • Events and other constants start with a lowercase letter.
  • Structure elements start with a lowercase letter.
  • Global variables start with a capital letter.
  • Typedefs start with a capital letter and end with "Type" (for example, DateFormatType, found in DateTime.h).
  • Macintosh ResEdit resource types usually start with a lowercase letter followed by three capital letters, for example tSTR or tTBL. (Customized Macintosh resources provided with your developer package are all uppercase, for example, MENU. Some resources, such as Talt, don't follow the conventions.)
  • Members of an enumerated type start with a lowercase prefix followed by a name starting with a capital letter, as follows:

    enum formObjects { 
    frmFieldObj, 
    frmControlObj, 
    frmListObj, 
    frmTableObj, 
    frmBitmapObj, 
    frmLineObj, 
    frmFrameObj, 
    frmRectangleObj, 
    frmLabelObj, 
    frmTitleObj, 
    frmPopupObj, 
    frmGraffitiStateObj, 
    frmGadgetObj 
    }; 
    typedef enum formObjects FormObjectKind; 
    

Integrating Programs with the Palm OS Environment ^TOP^

When users work with a Palm OS application, they expect to be able to switch to other applications, have access to Graffiti or Graffiti 2 power writing software and the onscreen keyboard, access information with the global find, receive alarms, and so on. Your application will integrate well with others if you follow the guidelines in this section. Integrate with the system software as follows:

  • Handle sysAppLaunchCmdNormalLaunch
  • Handle or ignore other application launch codes as appropriate. For more information, see the next chapter, Chapter 2, "Application Startup and Stop."
  • Handle system preferences properly. System preferences determine the display of
    • Date formats
    • Time formats
    • Number formats
    • First day of week (Sunday or Monday)

      Be sure your application uses the system preferences for numeric formats, date, time, and start day of week. See "Accessing System Preferences" for instructions on how to do so.

  • Allow the system to post these messages:
    • alarms
    • low-battery warnings
    • system messages during synchronization

      The normal event loop used by virtually all Palm OS applications allows ample time for the system to post messages and handle necessary events. You only need to take special care if your application performs a lengthy computational task. For example, if your application has a large database with greater than 20,000 records and it must search through each of these database records, you might want to check for system events every so often during this loop.

  • Be sure your application does not obscure or change the input area, input area icons, and power button.
  • Don't obscure shift indicators.

In addition, follow these rules:

  • Store state information in the application preferences database, not in the application record database. See "Setting Application-Specific Preferences" for more information.
  • If your application uses the serial port, be sure to close the port when you no longer need it so that the HotSync application can use it.
  • Ensure that your application properly handles the global find. Generally, searches and sorts aren't case sensitive.
  • If your application supports private records, be sure they are unavailable to the global find when they should be hidden.
  • Integrate with the Launcher application by providing an application name, two application icons, and a version string as described in "Application Launcher".
  • Follow the guidelines detailed in the book Palm OS User Interface Guidelines.
  • Ensure that your application properly handles system messages during and after synchronization.
  • Ensure that deleted records are not displayed.
  • Ensure that your application doesn't exceed the maximum number of categories: 15 categories and the obligatory category "Unfiled" for a total of 16.
  • Ensure that your application uses a consistent default state when the user enters it:
    • Some applications have a fixed default; for example, the Date Book always displays the current day when launched.
    • Other applications return to the place the user exited last. In that case, remember to provide a default if that place is no longer available. Because of HotSync operations and Preferences, don't assume the application data is the same as it was when the user looked at it last.
  • If your application uses sounds, be sure it uses the Warning and Confirmation sounds properly.

Writing Robust Code ^TOP^

To make your programs more robust and to increase their compatibility with the next generation of Palm OS products, it is strongly recommended that you follow the guidelines and practices outlined in this section.

  • Check assumptions

    You can write defensive code by adding frequent calls to the ErrNonFatalDisplayIf function, which enables your debug builds to check assumptions. Many bugs are caught in this way, and these "extra" calls don't weigh down your shipping application. You can keep more important checks in the release builds by using the ErrFatalDisplayIf function.

  • Avoid continual polling

    To conserve the battery, avoid continual polling. If your application is in a wait loop, poll at short intervals (for example, every tenth of a second) instead. The event loop of the Hardball example application included with your Palm OS SDK illustrates how to do this.

  • Avoid reading and writing to NULL (or low memory)

    When calling functions that allocate memory (MemSet, MemMove and similar functions) make sure that the pointers they return are non-NULL. (If you can do better validation than that, so much the better.) Also check that pointers your code obtains from structures or other function calls are not NULL. Consider adding to your debug build a #define that overrides MemMove (and similar functions) with a version that validates the arguments passed to it.

  • Use dynamic heap space frugally

    It is important not to use the extra dynamic heap space available on Palm units running 2.0 and higher unless it is truly necessary to do so. Wasteful use of heap space may limit your application to running only on the latest handhelds—which prevents it from running on the very large number of units already in the marketplace.

    Note that some system services, such as the IrDA stack or the Find window, can require additional memory while your application is running; for example, if the unit starts to receive a beam or other external input, the system may need to allocate additional heap space for the incoming data. Don't use all available dynamic memory just because it's there; instead, consider using the storage heap for working with large amounts of temporary data.

  • Check result codes when allocating memory

    Because future handhelds may have larger or smaller amounts of available memory, it is always a good idea to check result codes carefully when allocating memory. It's also good practice to use the storage heap (and possibly file streams) to work with large objects.

  • Avoid allocating zero-length objects

    It's not valid to allocate a zero-byte buffer, or to resize a buffer to zero bytes. Palm OS 2.0 and previous releases allowed this practice, but later revisions of the OS do not permit zero-length objects.

  • Avoid making assumptions about the screen

    The location of the screen buffer, its size, and the number of pixels per bit aren't set in stone—they might well change. Don't hack around the windowing and drawing functions. If you are going to hack the hardware to circumvent the APIs, save the state and return the system to that saved state when you quit.

  • Don't access globals or hardware directly

    Global variables and their locations can change; to avoid mishaps, use the documented API functions and disable your application if it is run on anything but a tested version of the OS. Future handhelds might run on a different processor than the current one.

    Similarly, don't hardcode references to cards. Although current Palm OS hardware provides only a single card slot, this may not always be the case. Thus, when calling functions that manipulate cards, such as Data Manager and file streaming functions, pass a variable that references the target card, rather than passing a hardcoded reference to card 0.

  • Built-in applications can change

    The format and size of the preferences (and data) for the built-in applications is subject to change. Write your code defensively, and consider disabling your application if it is run on an untested version of the OS.

Assigning a Database Type and Creator ID ^TOP^

Each Palm OS application is uniquely identified by a four-byte creator ID. Assigning this same creator ID to all of the databases related to an application associates those databases with the application. The OS takes advantage of this; for instance, the launcher's Info panel uses the creator ID to calculate the total memory used by each application.

Each database on the Palm Powered handheld has a type as well as a creator ID. The database type allows applications and the OS to distinguish among multiple databases with the same creator ID. For applications, set the database type to sysFileTApplication ('appl'). For each database associated with an application, set the database type to any other value (as long as it isn't composed entirely of lowercase letters, since those are reserved by Palm). Certain predefined types—such as 'appl' (application) or 'libr' (library)—have special meaning to Palm OS. For instance, the launcher looks at the database type to determine which databases are applications.

Types and creator IDs are case-sensitive, and are composed of four ASCII characters in the range 32-126 (decimal). Types and creator IDs consisting of all lowercase letters are reserved for use by Palm Inc., so any type or creator ID that you choose must contain at least one uppercase letter, digit, or symbol1.

To protect your application from conflicting with others, you need to register your creator ID with Palm, which maintains a database of registered IDs. To choose and register a creator ID, see this web page:

http://www.palmos.com/dev/creatorid/

Note that you don't need to register database types as you do creator IDs. Each creator ID in effect defines a new space of types, so there is no connection between two databases with type 'Data' but with different creator IDs.


IMPORTANT: Applications with identical creator IDs cannot coexist on the same handheld; during installation the new application will replace the existing application that possesses the same creator ID. Further, the new application could well corrupt any databases that were associated with the preexisting application. For this reason, all applications should have their own unique creator ID.

Finally, creator IDs aren't used only to identify databases. They are also used, among other things, when getting or setting application preferences, to register for notifications, and to identify features.

Making Your Application Run on Different Devices ^TOP^

There are many different handhelds that run Palm OS, and each may have a different version of the OS installed on it. Users are not expected to upgrade the Palm OS as frequently as they would an OS on a desktop computer. This fact makes backward compatibility more crucial for Palm OS applications.

This section describes how to make sure your application runs on as many handhelds as possible by discussing:

Running New Applications on an Older Device ^TOP^

Releases of the Palm OS are binary compatible with each other. If you write a brand new application today, it can run on all versions of the operating system provided the application doesn't use any new features. In other words, if you write your application using only features available in Palm OS 1.0, then your application runs on all handhelds. If you use 2.0 features, your application won't run on the earliest Palm Powered handhelds, but it will run on all others, and so on.

How can you tell which features are available in each version of the operating system? There are a couple of way to do so:

  • The Palm OS Programmer's API Reference has a "Compatibility Guide" appendix. This guide lists the features and functions introduced in each operating system version greater than 1.0.
  • The header file SysTraps.h (or CoreTraps.h on Palm OS 3.5 and higher) lists all of the system traps available. Traps are listed in the order in which they were introduced to the system, and comments in the file clearly mark where each operating system version begins.

Programmatically, you can use the Feature Manager to determine which features are available on the system the application is running on. Note that you can't always rely on the operating system version number to guarantee that a feature exists. For example, Palm OS version 3.2 introduces wireless support, but not all Palm Powered handhelds have that capability. Thus, checking that the system version is 3.2 does not guarantee that wireless support exists. Consult the "Compatibility Guide" in the Palm OS Programmer's API Reference to learn how to check for the existence of each specific feature.

Backward Compatibility with PalmOSGlue ^TOP^

The PalmOSGlue library can help you maintain backward compatibility with earlier releases while still allowing you to use the latest set of APIs. PalmOSGlue provides backward compatibility for some of the user interface manager calls and the managers that enable localization and internationalization.

PalmOSGlue can be used in any application that runs on Palm OS 2.0 and later. The library provides the latest support for localization features and for accessing internal UI data structures. Link your application with the library PalmOSGlue (PalmOSGlue.lib or libPalmOSGlue.a).

When you use PalmOSGlue, you use the functions in the same way as described in the Palm OS Programmer's API Reference, but their names are different. For example, TxtFindString is named TxtGlueFindString in PalmOSGlue. When you make a call to a glue function (for example, TxtGlueFunc, FntGlueFunc, or WinGlueFunc), the code in PalmOSGlue either uses the appropriate function found in the ROM or, if the function don't exist, executes a simple equivalent of the function.

To see a complete list of functions in PalmOSGlue, see the chapter "PalmOSGlue Library" of the Palm OS Programmer's API Reference.

PalmOSGlue is a linkable library that is bound to your project at link time. It is not a shared library. PalmOSGlue will increase your application's code size. The exact amount by which your code size increases depends on the number of library functions you call; the linker strips any unused routines and data.

Compiling Older Applications with the Latest SDK ^TOP^

As a rule, all Palm OS applications developed with an earlier version of the Palm OS platform SDK should run error-free on the latest release.

If you want to compile your older application under the latest release, you need to look out for functions with a changed API. For any of these functions, the old function still exists with an extension noting the release that supports it, such as V10 or V20.

You can choose one of two options:

  • Change the function name to keep using the old API. Your application will then run error free on the newer handhelds.
  • Update your application to use the new API. The application will then run error free and have access to some new functionality; however, it will no longer run on older handhelds that use prior releases of the OS.

NOTE: If you want to compile a legacy application with the Palm OS 3.5 or later SDK, note that some header file names have changed, and the names used for basic types have changed. For example, parameters previously declared as Word are now UInt16 or Int16. To compile existing applications, you'll need to make these changes in your code or include the header file PalmOSCompatibility.h. See the "Compatibility Guide" in the Palm OS Programmer's API Reference for further details.

Programming Tools ^TOP^

Several tools are available that help you build, test, and debug Palm OS applications.

Palm OS Developer Suite ^TOP^

Palm OS Developer Suite is an Eclipse-based integrated tool chain that provides Palm OS software developers with an easy and fast path for creating Palm OS applications. Palm OS Developer Suite enables development of both ARM-native Palm OS Protein applications and legacy 68K applications, all within a single IDE. Palm OS Developer Suite can be freely downloaded from the PalmSource, Inc. website, at http://www.palmos.com/dev/tools/dev_suite.html.

CodeWarrior ^TOP^

CodeWarrior Development Studio for Palm OS Platform is one of the industry's most complete programming tools. It is available for Windows and Mac OS platforms. For more information, see the Metrowerks website at http://www.metrowerks.com/MW/Develop/Desktop/PalmOS/Default.htm.

Palm OS Emulator ^TOP^

The Palm OS Emulator is software that emulates the hardware of the various models of Palm OS platform devices on Windows or Mac OS computers. Palm OS Emulator simulates Palm Powered devices running Palm OS 4.x and earlier only.

Palm OS Simulator ^TOP^

The Palm OS Simulator is Palm OS Cobalt or Palm OS Garnet running native on a Windows machine. Currently it is the easiest and best way to test your application for Palm OS Cobalt or Palm OS Garnet compatibilty. It is available as part of the Palm OS Developer Suite download and as a stand alone download via the PalmSource, Inc. web page.

See http://www.palmos.com/dev/tools/ for information about these and other development tools.

Where to Go from Here ^TOP^

This chapter provided you only with a general outline of the issues involved in writing a Palm OS application. To learn the specifics, refer to the following resources:

  • This book

    The rest of this book provides details on how to implement common application features using the Palm OS SDK. If you're new to Palm OS programming, you need to read the next two chapters to learn the principles of Palm OS application design, how to implement the main function, and how to implement the standard event loop. The remaining chapters you can read on an as-needed basis.

  • Example applications

    The actual source code for the applications on the Palm Powered handheld is included with your SDK as examples. The code can be a valuable aid when you develop your own program. The software development kit provides a royalty-free license that permits you to use any or all of the source code from the examples in your application.

  • Palm OS Programming Development Tools Guide

    The Palm OS Programming Development Tools Guide provides more details on using the tools to debug programs. (You might also be interested in the "Debugging Strategies" chapter in this book, which describes programmatic debugging solutions.)

  • Palm OS Programmer's API Reference

    The reference book provides the details on all of the public data structures and API calls.

  • Palm OS User Interface Guidelines

    The Palm OS User Interface Guidelines provides detailed guidelines for creating a user interface that conforms to Palm standards. You should read this book before you begin designing your application's interface.

  • Conduit Development Kits and documentation

    If you need to write a conduit for your application, see the documentation provided with the Conduit Development Kits.


1. Palm has also reserved 'pqa '.