Read it Now!
Reprint Licensing

Palm Programming: The Developer's Guide
Palm Programming: The Developer's Guide

By Neil Rhodes, Julie McKeehan

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: The Palm Solution
Palm Computing has single-handedly defined the handheld market with the PalmPilot and Palm III pocket organizers—people just go nuts over them. The question is why. Why did this little company succeed when so many giants failed? The answer is that they got the magic formula right—they figured out what customers really wanted and how much they were willing to pay for it.
Understanding how to design an application for this platform requires a bit of backpedaling and a look at the history of these devices. Helping you understand that history and what made Palm such a skyrocketing success will help you know how to design good applications for them. We want you to attack the design of your application with the same magic formula that Palm Computing used. Design does not happen in a vacuum. If you ignore the features and characteristics that made Palm a success, your application will bomb.
Not everybody knows that the PalmPilot was hardware born out of software, and not even system software, at that. Its origins are in Graffiti, the third-party handwriting recognition software developed for Newton and other Personal Digital Assistants (PDAs).
In 1994, Palm Computing came out with some handwriting-recognition software that promised accuracy and speed in recognition on PDAs at the price of a little bit of shorthand. Many industry experts thought such software was doomed to fail, as it required too much work from the user. They were proved wrong. Speed and accuracy were more important—Graffiti was able to offer enough to compensate for the relatively minor work required to learn the new strokes.
Buoyed by its success with Graffiti and frustrated by other companies' inability to get the platform right, Palm Computing decided to create its own handhelds. The result was the release of the Pilot 1000 in mid-1996. It and its closely following mate, the Pilot 5000, rapidly made headway. So popular was this product that with the release of its next device 18 months later, the company topped the 1-million-unit mark and clearly dominated the market.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why Palm Succeeded Where So Many Failed
Not everybody knows that the PalmPilot was hardware born out of software, and not even system software, at that. Its origins are in Graffiti, the third-party handwriting recognition software developed for Newton and other Personal Digital Assistants (PDAs).
In 1994, Palm Computing came out with some handwriting-recognition software that promised accuracy and speed in recognition on PDAs at the price of a little bit of shorthand. Many industry experts thought such software was doomed to fail, as it required too much work from the user. They were proved wrong. Speed and accuracy were more important—Graffiti was able to offer enough to compensate for the relatively minor work required to learn the new strokes.
Buoyed by its success with Graffiti and frustrated by other companies' inability to get the platform right, Palm Computing decided to create its own handhelds. The result was the release of the Pilot 1000 in mid-1996. It and its closely following mate, the Pilot 5000, rapidly made headway. So popular was this product that with the release of its next device 18 months later, the company topped the 1-million-unit mark and clearly dominated the market.
Not only that, but Palm Computing has since been acquired by U.S. Robotics and then again by 3Com. Not to undercut 3Com's new ownership of the Palm OS, but we will continue to refer to the makers of the Palm platform as Palm Computing.
It would be good to stop at this point and ask yourself why this company succeeded when so many other companies failed. How was it alone able to produce a successful handheld? It wasn't experience in hardware design—companies like Apple, Casio, and Hewlett-Packard clearly have more. It wasn't breadth of features—Windows CE and Newton devices have more. It wasn't price—Texas Instruments's Avigo is cheaper. So what does the Palm offer that all these other companies weren't providing? The answer to this question (because Palm Computing figured out what customers wanted) is simple to articulate, but complex to understand. Some insight can be gained by looking at the evolution of Palm devices and their OS relative to other handhelds.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Designing Applications for Palm Devices
As you can see from the way its handhelds are designed, Palm Computing was convinced that a handheld device will be successful if it is:
  • Small (fits into a shirt pocket)
  • Inexpensive (doesn't cost more than a few hundred bucks)
  • Able to integrate seamlessly with a desktop computer by placing the handheld in a convenient cradle
These design decisions are only one part of the solution, however. The other part is the software. Palm devices are popular because they contain useful, fast applications and because they are extensible. There were lots of personal organizers before Palm Computing came along. The difference is that those old devices weren't easily extensible—third-party applications couldn't be added. The magic of Palm devices is therefore two-fold. The built-in applications cover a wide range of general activities, giving users access to names, a date book, a to do list, and so on. Crucial, however, is the second part: the platform is also open to other developers. Knowing how important other applications were, Palm provided tools and enough material to gain a wide developer following. These developers, in turn, have added lots of specialized applications. Everybody—Palm, developers, users—benefits.
We spent so much time discussing the history of Palm devices, what makes them popular, and features they don't have because these issues are crucial to your understanding of the design philosophy behind a Palm OS application. These are the essential elements in a Palm application:
  • It needs to take into account small screen size.
  • It needs to limit text input on the handheld.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Elements in a Palm Application
Now that you know how to design a Palm application, let's describe its two components. After that we will look at how they communicate with each other.
Most Palm solutions are composed of a handheld application and desktop conduit:
The handheld portion
The portion that resides on the handheld and allows the user to view and manipulate data. Part II, deals with the creation of this part.
The conduit portion
Here you have code that handles syncing the data with a desktop application. Part III, shows you how to create this part.
The handheld portion has an icon that is displayed in the application list. Users will usually use the Palm Install Tool from a Windows or Macintosh machine to install your application (it'll be installed on the next synchronization).
When a user puts a Palm OS device in its cradle and presses the HotSync button, the handheld application begins communicating with the desktop conduit. For example, the Address Book has a built-in conduit that synchronizes the address book information on the handheld with the address book information in the Palm Desktop PIM. If a new entry has been made in either place, it is copied to the other. If an entry has been modified either place, it is copied to the other. If an entry has been deleted in one place, it is usually deleted in the other.
Third parties provide other conduits that replace the Address Book conduit so that the device's address book synchronizes with other PIMs (Microsoft Outlook, for example). You'll usually want to write a conduit for your application's database that will upload/download information in a manner appropriate for your 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!
Summary
In this chapter, we have described Palm devices, the circumstances that governed their design, and the history of Palm Computing's success with this combination. Then we discussed application design in light of the devices' history, design, and future directions. Last, we discussed the important elements in a Palm application and gave you some rules to help you in application design.
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: Development Environments and Languages
This chapter deals with the what and the how of things. First, we show you what you're programming for—the nuts and bolts of the Palm OS. Then we show you how to do it—the available development environments. By the time we are through, you should have a good idea of the range of applications you can create for the Palm OS, the coding requirements, and which development environment you want to use.
Developing for the Palm OS is in some ways similar to other platforms and in other ways strikingly different. Two important similarities are:
  • Applications are event driven.
  • You can use anything from standard C code to assembler to scripting.
Differences tend to center around features crucial to the device size and purpose. These include how the Palm OS handles:
  • Memory requirements
  • Application and data storage
  • Connectivity of the device to the desktop
Most important, you should remember that the relationship between the device and the OS is extremely tight. Everything has been built on the premise that the handheld is an extension of the desktop and that it must be responsive to the user.
Let's look in more detail at this tight interaction of the OS and the applications on the handheld. The Palm OS runs on top of a preemptive multitasking kernel. One task runs the user interface. Other tasks handle things like monitoring input from the tablet.
The user interface permits only one application to be open at a time. Thus, when your application is open, it (more or less) has control of the entire screen.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Overview
Developing for the Palm OS is in some ways similar to other platforms and in other ways strikingly different. Two important similarities are:
  • Applications are event driven.
  • You can use anything from standard C code to assembler to scripting.
Differences tend to center around features crucial to the device size and purpose. These include how the Palm OS handles:
  • Memory requirements
  • Application and data storage
  • Connectivity of the device to the desktop
Most important, you should remember that the relationship between the device and the OS is extremely tight. Everything has been built on the premise that the handheld is an extension of the desktop and that it must be responsive to the user.
Let's look in more detail at this tight interaction of the OS and the applications on the handheld. The Palm OS runs on top of a preemptive multitasking kernel. One task runs the user interface. Other tasks handle things like monitoring input from the tablet.
The user interface permits only one application to be open at a time. Thus, when your application is open, it (more or less) has control of the entire screen.
Applications run within the single-user interface thread and therefore can't themselves be multithreaded.

Section 2.1.1.1: Memory

Memory is handled in an unusual fashion. The RAM on a Palm OS device is used for two purposes:
For dynamic memory allocation
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Handheld Development
Many different development tools are available for Palm programming. There is everything from a collection of tools that let you write C code to polished forms based packages that require only modest amounts of scripting. From this gamut of choices, you should be able to pick the right tool for the type of application you want to create. Before we discuss the advantages and disadvantages of each choice, however, it's worth looking at a description of each option.
For the development of the handheld portion of your Palm application, you can write code on Windows 95/98/NT, Unix, or Macintosh platforms. Palm's official development environment, CodeWarrior, is available for both Windows and Macintosh. Unix and Windows programmers have access to the free set of tools—GNU C compiler, or GCC—and there are two packages for Windows-based forms development. Last, but not least, Windows programmers can also program in 68K assembler or use a proprietary language called CASL.
The official development environment for the Palm OS is Metrowerks's CodeWarrior for Palm OS. This commercial development environment allows you to create ANSI C and C++ programs on either Windows 95/98/NT or Macintosh systems. It currently includes Palm's Conduit Software Development Kit, and Palm's own documentation assumes that you are using it. CodeWarrior for Palm OS is available on a subscription basis with one year of free updates. It costs approximately $369. Here is a description of the tools that CodeWarrior gives you for Palm OS development:
Metrowerks's Constructor
Constructor is a graphical resource editor (see Figure 2.2) that you use to create the user interface elements of your 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!
Alternative Development Environments
The following sections describe several useful alternative development environments for the Palm OS.
This SDK allows development of applications written in Motorola 68K assembler. It includes Pila (Pilot Assembler). To us this would be sheer agony, but apparently some developers enjoy writing applications in assembly language. To each their own poison. You certainly can't beat the price—it's free.
For more information, see Darren Massena's web site (http://www.massena.com), which is an indispensable Palm developer resource in its own right.
This novel environment allows you to write your application in Java using a Palm class library and your favorite Java development environment. Jump then compiles the resulting Java .class files into Motorola 68K code. Jump includes a very small runtime library that provides crucial Java support like garbage collection.
The only disappointing aspect of Jump is that the Palm OS is not completely supported. For example, any calls that require a callback function as a parameter (such as LstSetDrawFunction and FrmSetEventHandler) won't work.
This development environment is free, and source code is provided. Jump is the brainchild of Greg Hewgill; you can get it from http://www.hewgill.com.
This commercial package provides cross-platform support. You write an application once in the CASL language (a BASIC-like proprietary language) and then deploy it on Palm OS or on other operating systems. This approach offers you ease of cross-platform dispersion as you write your applications in one language for multiple platforms. The code is compiled into a p-code for a virtual machine. There is a virtual machine for Palm OS, and one will be available for Windows CE in 1998. You can test your applications under Windows, as well. Figure 2.7 shows an example of application development using CASL. As you can see, development is simpler than directly using C or C++.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
High-Level Forms Development
Palm devices are so numerous and applications so popular that there are even a couple of third-party development environments specifically for creating specialized forms-based Palm applications.
This Windows application provides a very easy way to create simple multipage forms that contain text fields, checkboxes, radio buttons, etc.
Pendragon Forms also provides a conduit that automatically uploads information into comma-separated values (CSV) files. These files can then be easily imported into spreadsheet or database programs. Looking at Figure 2.8, you can see how simple it is to make the form being displayed on the Palm device in Figure 2.9.
Figure 2.8: Developing a form using Pendragon Forms
Figure 2.9: Running an application created with Pendragon Forms
Pendragon Forms is $50, and, nicely enough, there is no runtime fee necessary for deploying forms. See http://www.pendragon-software.com for further details.
Satellite Forms, by Puma Technology, is an environment for creating very sophisticated Palm OS applications. In Satellite Forms, your application consists of a number of database tables and forms. Each form is tied to a specific table and can display elements of that table. Figure 2.10 shows an example table in Satellite Forms. Figure 2.11 shows an example form. Figure 2.12 shows the resulting form on a Palm device.
Figure 2.10: Creating a table in Satellite Forms
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conduit Development
If you are creating a conduit for your Palm application, you need to do so on Macintosh or Windows using Palm's Conduit SDK. The Conduit SDK comes with:
  • Header files
  • Debug and nondebug libraries
  • Source code for sample conduits
Under Windows, a conduit is a Dynamic Link Library (DLL) that is called as HotSync occurs. An install DLL is provided with which you register your conduit with HotSync. On Mac OS, a conduit is a shared library.
Conduits have access to databases on the Palm OS. The Conduit Manager handles the complexities of communication; it is not your concern. You simply call routines to read and write records in the database. The Conduit Manager handles the communication protocol.
In order to develop conduits for Windows, you must use Visual C++ 5.0 (or later). For Mac OS, you can use any development environment that has the ability to create shared libraries (CodeWarrior for Mac OS is a likely candidate).
C++ classes that simplify creating a synchronization conduit are provided by Palm (frequently referred to by the names basemon and basetbl ). These C++ classes are the basis of the conduits for the built-in applications. If your application's synchronization needs are similar to those of the built-in applications, then these C++ classes work well. As your application's sync needs differ, the C++ classes become less useful, and you might wish to consider reverting to the underlying C/C++ Conduit Manager API to make things work properly. You do, however, have another alternative.
There are other C++ classes recently provided by Palm to aid in the creation of conduits. These classes (called Generic Conduit) are not officially supported by Palm (at the time of this book's writing), but they do offer an alternative—in many ways easier—method of conduit creation.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conclusion
You should now have a good idea of which development environment you want to use to write your Palm OS applications. You should also know enough about the features in the Palm OS and of the devices to make intelligent decisions about the types of applications that you can create for Palm devices. Next, we discuss the sample application that we are developing throughout this book.
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: Designing a Solution
Now that you know about the features of the Palm OS and you have figured out what development environment you are going to use, it is time to create a new application. To do this, you first need to know what the Palm OS provides in the way of user interface elements. Second, you need a description of the elements common to every application.
From this general overview, we move to a concrete example. For this purpose, we discuss a sample application that we are going to create and then dissect in this book. We show you its design, what actions the user performs, how we prototyped it, and the design complications we encountered. Once we've covered the handheld portion of the application, we turn to a description of the conduit.
The Palm OS provides you with an abundance of user interface elements. The following is a description of these elements. We also show you some common examples of each type.
Figure 3.1 contains an example of a typical alert. It is simply a modal dialog that displays a title, a message, an icon, and one or more buttons. You are responsible for setting the text of the title, the message, and the button(s). You also specify the type of alert. It can be any of the following types (ordered from mildest in consequence to most severe):
Information
This has an "i" icon. The alert provides to the user some information (for example, that an action can't be completed). No data loss has occurred.
Confirmation
This has a "?" icon. The alert asks the user a question, asking the user to confirm an action or to choose from possibilities.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
User Interface Elements in an Application
The Palm OS provides you with an abundance of user interface elements. The following is a description of these elements. We also show you some common examples of each type.
Figure 3.1 contains an example of a typical alert. It is simply a modal dialog that displays a title, a message, an icon, and one or more buttons. You are responsible for setting the text of the title, the message, and the button(s). You also specify the type of alert. It can be any of the following types (ordered from mildest in consequence to most severe):
Information
This has an "i" icon. The alert provides to the user some information (for example, that an action can't be completed). No data loss has occurred.
Confirmation
This has a "?" icon. The alert asks the user a question, asking the user to confirm an action or to choose from possibilities.
Warning
This has a "!" icon. You are asking the user if the action is really intentional. Data loss could occur if the action is completed. The Memo Pad uses a confirmation alert for deleting memos, since the user can choose to save an archive on the PC (thus the data is not lost). However, the system uses a warning dialog when the user chooses to delete an application, since after the delete, the application is completely gone. Figure 3.1 is a warning alert.
Error
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
General Design of a Palm Application
Most applications will contain a certain core number of user interface elements. Even the simplest application will, at the very least, need a form and some controls. Most applications go well beyond the minimal number of features and have multiple menus, forms, and dialogs as well.
When you sit down to design your application, you'll need to ask yourself the following questions and come up with some reasonable answers to them:
What tasks does the application accomplish?
Obviously, this is a question one would ask about any application on any platform. That doesn't make it any less relevant here. You need to lay out as clearly as possible what the user can do with your application, what tasks the user can perform. Just as importantly, you should have a clear idea of possible tasks that the user can't do.
The essence of the Palm OS and the handhelds is speed and accessibility. Putting a possible feature on the chopping block because it ruins either of these is something to be proud of and is terribly difficult to do in this era of "kitchen sink" applications.
What forms does the application have?
There is minimally a startup form that the user sees when tapping the application icon. Every dialog (other than an alert) or other data view is also a new form. A good rule of thumb is that you will have one form for every view of data. Forms add up fast when you count this way.
What menus does the application have?
Commonly, you will support the Record, Edit, and Option menus. They will be similar to those found in the built-in applications with the same menu items. Often custom menus are also a part of the 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!
How the Sample Applications Are Useful
Some of you may be wondering how useful the Sales application will be to you. Does it show you how to implement all the APIs? Does it contain the essential components of most Palm applications? Here are some answers. The Sales application uses most of the Palm API (except for Category UI) and to that extent offers a broad treatment. Because it isn't an exact clone of the built-in apps, you also see some new design issues and code. It also covers databases, beaming, menus, dialog boxes, and Find. Another crucial component is the detailed description of its conduit. We hope that much of what is mystifying about conduits is clarified in our descriptions and the code we create.
We also cover some Palm OS features in smaller sample applications. We handle tables, barcoding, serial, and TCP/IP in this manner. The bad news is that the Palm OS is so feature-rich that there are indeed some other areas we don't cover in this detail. We hope there are no glaring omissions. Our goal was not to cover every topic but only the most difficult or important ones. Our examples are created with this goal in mind. (If we goofed, let us know and we will try to correct it in the future.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
User Interface of the Sales Application
The sample application we are creating is a forms-based application that will be used to record orders. This application is for a person who sells toys to stores.
This sample application will be used as a basis for our code discussions throughout the book.
These are the activities we want the salesperson to be able to accomplish in the application:
  • Modify, delete, or create a new customer
  • Create a new order for a customer
  • Delete an order
  • Delete or modify items in an order
  • Beam a company to another device
The user starts the application and picks a customer from a list Figure 3.5.

Section 3.4.1.1: The customer list

This is the startup form of the application. It is a list of all the customers that our salesperson normally sells toys to during that selling period. The user can tell which customers already have orders because those without orders are in bold.
We admit that bolding an item to indicate status is a subtle, if not obscure, design element. Its presence is reasonable when you remember the audience of this application. The same user will use it day in and day out for taking orders. The bolding of an item in a constantly used application may be warranted, while it may not be in a more general purpose application. In any case, a user who doesn't know what the bold is for is not hurt—it's just a shortcut for the experienced user.
When a name is selected from the customer list (see Figure 3.5), the individual Customer form is opened.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Developing a Prototype
Now that we've shown you the application in its final form, let's back up and show you the process and decisions we made to get there. First, let's look at how we prototyped it.
Our prototype design was a mock-up of the basic views that we wanted to have in the application. We came up with those views by listing the actions we wanted the user to be able to do and the order in which we thought they would occur; we discussed the flow of events. Our strategy was to optimize the application so that the more frequent the action the fewer steps it took to complete. We also wanted to emulate the design of the built-in applications wherever possible.
The first and most important view to create well is the start screen—what your user sees when the application is launched. In the Sales application, the place to start seemed straightforward—with a list of the salesperson's customers. This is a list that can be modified on the handheld, but ordinarily would be created on the desktop. The desktop application should be clever about culling customers from the list if the salesperson isn't visiting them on this trip. It might also want to order the customers either alphabetically or by visit (as the salesperson prefers).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Design Tradeoffs in the Sample Application
As with any design, we made some modifications that changed the look and functionality of this application. We think it will be useful to you to explain how we meandered about with these decisions.
There are a couple of things to notice about the design that we ended up with for this action (see Figure 3.19). When the user taps on the customer name, an order form immediately presents itself. As this is the most common action, we focused on minimizing the steps necessary to complete it. In our final design, we managed to reduce the number of steps required to take an order by one. Look at two possible designs in Figure 3.19, and you will see where we saved a step. The example on the left requires the user to first select the customer name and then tap the New Order button below the list (two actions). The example on the right brings the order forward with one less action.
Figure 3.19: Two ways to design the selection of a new order
The tradeoff here affects two things. We can make an order easier to create (our solution) or make customers easier to create and edit. For us the choice is obvious; we assume that the salesperson rarely adds new customers or modifies old ones. This is the standard list of customers that our user always deals with when selling toys. In a world where customers came and went more often, we might have chosen differently.
The next design issue we tackled was how the user accesses, modifies, and deletes customer information. Menu items or buttons could go either in the startup screen or in the order form. Both choices carry their own set of advantages and disadvantages. Before showing you the logic of our choices, back up and look again at what we want the user of the Palm device to be able to do:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Designing for a Small Screen
One of the biggest challenges you face as a handheld application designer is how to fit data in the screen space on a Palm device. In the Sales application, this challenge happens when we are trying to figure out the right way to select a toy. We assume that there are more toys than would fit on one list on the screen. One approach might have been to have one long scrolling list—the least favorable solution. Toys, like many other types of items, naturally fall into obvious groups. We chose to take advantage of this by first putting the toys into categories.
Table 3.2 contains three ways that we could have organized the items. Our solution was to go with a category organization. This makes things like special sales promotional items easy to handle. A fast-food restaurant might use a similar approach for taking orders. In both cases, the customer is going to go through categories in certain obvious groupings.
Organizing things alphabetically is another possibility, but one that doesn't make as much sense for our application. Neither the customer nor the salesperson is likely to think about the toys in this way.
Organizing the items by number might have been a good choice from the salesperson's point of view. It is not uncommon to memorize part numbers of items you work with all the time; however, where this organization strategy breaks down is from the customer's point of view. The customer is not necessarily going to request items by number. We imagine the customer thinks in terms of the store's shelves which are themselves organized by category. Our strategy is to match the customer's organizational model. Doing so minimizes the number of steps required to add an item to the order (less category switching).
Table 3.2: Ways of Categorizing Toys
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Designing the Databases
Once you have figured out how to organize the data, your next big decision is to determine the number of databases you should use. We settled on four databases in the Sales application; they are customers, products, orders, and categories.
Customers
The customer database contains the information about the customers. Each customer record contains five items:
Customer ID
A unique customer code assigned at corporate headquarters. If a new customer is created on the handheld, it is assigned a temporary negative customer ID. Corporate headquarters is responsible for assigning a permanent ID after a HotSync.
Name
A string.
Address
A string.
City
A string.
Phone
A string.
The order in the database is the order in which they are displayed in the list. New customers are added at the beginning. There are at least two possible ways to reasonably organize the customer database—alphabetically or by visit order (the first name is the first customer the salesperson visits, the second name is the second visit, and so on).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Designing the Conduit
A conduit is a desktop application made in a desktop development environment. It uses HotSync synchronization to connect the desktop to the handheld; conduits are responsible for the transfer of data to and from the handheld and the desktop. The user views the data using some application (a spreadsheet, for example, for viewing expense report items). The conduit needs to make sure that this desktop application has the data it needs to handle processor-intensive tasks. Before looking at the design of the Sales application conduit, let's examine this issue of off-loading processor-intensive tasks.
Using the conduit to transfer the data, move processor-intensive tasks onto the PC and off of the handheld. If you can't move tasks, you should almost always get rid of them.
Palm devices are noted for being both fast and cheap—two of the key features that have made them so popular. One of the reasons they are cheap is they have little bitty processors that don't have much horsepower. Your job as a good application designer is to avoid taxing the handheld's processing abilities. Don't turn it into a slow device—there are already plenty of those around. This means that you may end up making design decisions about your database that don't make sense from a desktop database designer's point of view, but do make sense when you take into account the desktop's superior processing abilities. Here is an example.
Recently, we were involved in porting an application from another handheld platform (with a fast processor) to the Palm platform. This is an application that keeps track of a bunch of vending machines: when they need filling, what products go in what slots, how much money is collected, and so on. The account screen provides a summary of the machines that belong in that account (an account could have many machines or just a few). The machine screen provides a summary of items for that particular machine. In the original platform, as we entered an account screen at runtime, we'd run through the database, summarizing and totalling (for instance, we'd total how many machines needed to be serviced for an account, along with how many total machines an account had).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Design Summary
By now, you should have a good feel for how to design a Palm application and conduit. You also know about the range and types of tools available to help you with this project. You should also have a good feeling for what types of applications will work well on a Palm device and the types of user interface elements you can easily add to them. Now it is time to turn away from design issues and to the code you need to write to create your 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: Structure of an Application
The overall flow and content of a Palm OS application is the subject of this chapter. You will learn:
  • The standard code routines found in every Palm application
  • All about the application's lifecycle—its starting, running, and closing
  • How the application processes each event and hands it off to the appropriate manager
  • How memory is organized on a Palm device; how the application can use it
  • All the times that an application needs to be available to the system and how these instances are handled in the code
Like every operating system and coding interaction, the Palm OS has it own set of necessary terminology for you to learn. Much of it may already be familiar to you from other applications you have written. We suggest that you skim through this list and concentrate on the items that are new to you. New and unique terminology is listed first.
Form
An application window (what many people would think of as a view) that usually covers the entire screen. A form optionally contains controls, text areas, and menus. In a Palm OS application, there is only one active form allowed at a time. Chapter 5, covers forms in detail.
Window
A rectangular area in which things like dialogs, forms, and menus are drawn by the application. The Window Manager makes sure that windows properly display relative to each other (for example, it has the ability to restore the old contents when a window is closed). Note in a rather Shakespearian twist of logic that all forms are windows, even though all windows are not forms.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Terminology
Like every operating system and coding interaction, the Palm OS has it own set of necessary terminology for you to learn. Much of it may already be familiar to you from other applications you have written. We suggest that you skim through this list and concentrate on the items that are new to you. New and unique terminology is listed first.
Form
An application window (what many people would think of as a view) that usually covers the entire screen. A form optionally contains controls, text areas, and menus. In a Palm OS application, there is only one active form allowed at a time. Chapter 5, covers forms in detail.
Window
A rectangular area in which things like dialogs, forms, and menus are drawn by the application. The Window Manager makes sure that windows properly display relative to each other (for example, it has the ability to restore the old contents when a window is closed). Note in a rather Shakespearian twist of logic that all forms are windows, even though all windows are not forms.
Database
A collection of persistent memory chunks. There are two kinds: resource and record databases.
Resource
A piece of data stored in a resource database. Each resource is identified by a resource type and number. A Palm application is a collection of resources. Section 5.1 covers resources in more detail.
Record
A data structure identified by a unique record ID. Applications typically store data in record databases.
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 Simple Application
Creating a small application before tackling a more complex one is a good way to gain familiarity with a new coding challenge. First, we tell you what our little application does and show you the code for it. After that we do a code walkthrough and point out important elements.
Our Hello World application displays the words "Hello World" and provides a button to press. Pressing the button displays an alert, as shown in Figure 4.1, which is dismissed by tapping OK. There are two menus, each with one menu item (see Figure 4.2). As this is a very simple application, you just get a beep when you choose either menu item.
Figure 4.1: Dialog shown after tapping the button
Figure 4.2: The menus of Hello World
Now that you have an idea of what the application can do, look at Example 4.1 to see the code that produces it. Once you have looked through it for yourself, we will discuss it.
Example 4.1. The Hello World Source Code
#include <Pilot.h>  
#ifdef _     _GNUC_     _
#include "Callback.h"
#endif
#include "HelloWorldRsc.h"    

static Err StartApplication(void)
{
  FrmGotoForm(HelloWorldForm);
  return 0;
}

static void StopApplication(void)
{
}

static Boolean MyFormHandleEvent(EventPtr event)
{
  Boolean    handled = false;

#ifdef _     _GNUC_     _
   CALLBACK_PROLOGUE
#endif
   switch (event->eType) {
   case ctlSelectEvent:  // A control button was pressed and released.
      FrmAlert(GoodnightMoonAlert);
      handled = true;
      break;
    
   case frmOpenEvent:  
      FrmDrawForm(FrmGetActiveForm());
      handled = true;
      break;
      
   case menuEvent:    
      if (event->data.menu.itemID == FirstBeep)
         SndPlaySystemSound(sndInfo);
      else
         SndPlaySystemSound(sndStartUp);
      handled = true;
      break;
   }
#ifdef _     _GNUC_     _
   CALLBACK_EPILOGUE
#endif
   return handled;
}

static Boolean ApplicationHandleEvent(EventPtr event)
{
   FormPtr  frm;
   Int    formId;
   Boolean  handled = false;

   if (event->eType == frmLoadEvent) {
      //Load the form resource specified in the event then activate it
      formId = event->data.frmLoad.formID;
      frm = FrmInitForm(formId);
      FrmSetActiveForm(frm);

      // Set the event handler for the form.  The handler of the currently 
      // active form is called by FrmDispatchEvent each time it is called 
      switch (formId) {
      case HelloWorldForm:
         FrmSetEventHandler(frm, MyFormHandleEvent);
         break;
      }
      handled = true;
   }
  
   return handled;
}

static void EventLoop(void)
{
   EventType  event;
   Word      error;
  
   do {
    EvtGetEvent(&event, evtWaitForever);
    if (! SysHandleEvent(&event))
       if (! MenuHandleEvent(0, &event, &error))
          if (! ApplicationHandleEvent(&event))
             FrmDispatchEvent(&event);
   } while (event.eType != appStopEvent);
}

DWord PilotMain(Word launchCode, Ptr cmdPBP, Word launchFlags)
{
  Err err = 0;    
  
  if (launchCode == sysAppLaunchCmdNormalLaunch) { 
     if ((err = StartApplication()) == 0) {
        EventLoop();
        StopApplication();
     }
   }

   return err;
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Scenarios
Now that you have a better understanding of the code in the Hello World application, let's take a close look at what happens as events are passed from the event queue into the event loop. Unlike our earlier example, where we hand-waved through the technical parts of what happens when a menu was chosen, we will now look with great detail at three different user actions and the flow through the code as these scenarios occur.
This first code excerpt shows what happens when a user opens the application by tapping on the application's icon. Example 4.9 shows the flow of events. Pay particular attention to the frmLoadEvent , which is handled by ApplicationHandleEvent , and the frmOpenEvent, which is handled by MyFormHandleEvent.
Example 4.9. Flow of Control as Hello World Application Is Opened
PilotMain (enter)
  StartApplication (enter)
    FrmGotoForm(HelloWorldForm)                  open the HelloWorldForm
  StartApplication (exit)                        returns 0 (proceed)
  EventLoop (enter)
  EvtGetEvent                                    returns frmLoadEvent (formID 
                                                     HelloWorldForm)
    SysHandleEvent                               returns false
    MenuHandleEvent                              returns false
    ApplicationHandleEvent (enter)
      FrmInitForm(HelloWorldForm)                load the form
      FrmSetActiveForm(frm)                      activate the form
      FrmSetEventHandler(frm, MyFormHandleEvent) set the event handler
    ApplicationHandleEvent (exit)                returns true
  EvtGetEvent                                    returns frmOpenEvent
  SysHandleEvent                                 returns false
  MenuHandleEvent                                returns false
  ApplicationHandleEvent                         returns false
  FrmDispatchEvent (enter)                       calls form's event handler
    MyFormHandleEvent (enter)
      FrmDrawForm(FrmGetActiveForm())            
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Memory Is Extremely Limited
Now that you have an idea of how the system hands events off to the application, it's time to look at how memory is handled. To start off, it will help if you remember one crucial point: memory is an extremely limited resource on Palm OS devices. Because of this, Palm OS applications need to be written with careful attention to memory management.
To that end, let's examine the memory architecture on Palm devices. RAM is divided into two areas: storage and dynamic (see Figure 4.5). The storage area of memory is managed by the Database Manager, which we discuss in Chapter 6. It is dynamic memory, which is handled by the Memory Manager, that we discuss here.
Figure 4.5: Memory map
The dynamic memory is used for Palm OS globals, Palm OS dynamic allocations, your application's global variables (note that C statics are a form of globals), your application's stack space, and any dynamic memory allocations you make. As you can see in Table 4.1, the size available depends on the operating system and on the amount of total memory on the device.
Table 4.1: Dynamic Memory Usage for Various Palm OS Configurations
System Resources
OS 3.0 (>1 MB)
OS 2.0 (1 MB; has TCP/IP)
OS 2.0 (512 KB; no TCP/IP)
System Globals
6KB
2.5KB
2.5KB
System dynamic allocation
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Other Times Your Application Is Called
Content preview·