Learning WML & WMLScript
Martin Frost
First Edition, October 2000
ISBN: 1-56592-947-0, 200 pages
The next generation of mobile communicators is here, and delivering content will mean programming in WML and WMLScript. Learning WML & WMLScript gets developers up to speed quickly on these technologies, mapping out in detail the Wireless Application Development (WAE), and its two major components: Wireless Markup Language (WML), and WMLScript. With these two technologies, developers can format information in almost all applications for display by mobile devices
Preface The WAP Stack From Server to Client This Book Conventions Used in This Book Comments and Questions Acknowledgments
1
1
Introduction to WML 1.1 A Complete Example 1.2 Cards 1.3 Empty-Element Tags 1.4 Elements 1.5 Attributes 1.6 Entities 1.7 Comments
6
2
WML 2.1 2.2 2.3
3
WML Tasks and Events 3.1 Tasks 3.2 Events
17
4
WML 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10
24
5
WML Timers 5.1 Using Timers with WML 5.2 The Element
36
6
WML 6.1 6.2 6.3 6.4 6.5 6.6
Decks, Templates, and Cards The <wml> Element The Element The Element The <meta> Element The Element The Element
40
7
WML 7.1 7.2 7.3 7.4
Text and Text Formatting The
Element The
Element Character Formatting Tables
45
8
WML Images 8.1 The Element 8.2 The WBMP Image Format
52
9
Introduction to WMLScript 9.1 WMLScript with WML 9.2 What Is WMLScript?
54
Variables and Contexts Variable Substitution Setting Variables Browser Contexts
User Interaction Problems with Web Interaction Interaction in WAP The Element The <select> Element The Element The Element The <do> Element The Element The Element The tabindex Attribute
10 WMLScript Datatypes, Variables, and Conversions 10.1 Datatypes and Literals 10.2 Variables 10.3 Type Conversion
12
57
11 WMLScript Operators and Expressions 11.1 Operand Conversions 11.2 Assignment Operators 11.3 Arithmetic Operators 11.4 Bitwise Operators 11.5 Shift Operators 11.6 Logical Operators 11.7 Increment and Decrement Operators 11.8 Comparison Operators 11.9 Type Operators 11.10 The Conditional Operator 11.11 The Comma Operator 11.12 Precedence and Associativity
63
12 WMLScript Statements 12.1 Expressions as Statements 12.2 Blocks of Statements 12.3 Conditions 12.4 Loops 12.5 Returning from a Function 12.6 Other Statements
74
13 WMLScript Functions 13.1 Function Declarations 13.2 Function Calls 13.3 Calls to Other Script Units 13.4 Calling WMLScript from WML 13.5 Standard Libraries
78
14 WMLScript Pragmas 14.1 The access Pragma 14.2 The meta Pragma
83
15 The Lang Library abort abs characterSet exit float isFloat isInt max maxInt min minInt parseFloat parseInt random seed
85
16 The Float Library ceil floor int maxFloat minFloat pow round sqrt
95
17 The String Library charAt compare elementAt elements find format insertAt isEmpty length removeAt replace replaceAt squeeze subString toString trim
102
18 The URL Library escapeString getBase getFragment getHost getParameters getPath getPort getQuery getReferer getScheme isValid loadString resolve unescapeString
119
19 The WMLBrowser Library getCurrentCard getVar go newContext prev refresh setVar
128
20 The Dialogs Library alert confirm prompt
132
21 Complete Examples 21.1 Calculator 21.2 Battleships
134
A
Absolute and Relative URLs A.1 Parts of a URL A.2 Resolving Relative URLs
142
B
WAP Gateways and WSP B.1 WSP Headers B.2 Browser Support for Caching
145
C
Summary of WMLScript Operators
146
D
Serving WAP Content from a Standard Web Server
148
Colophon
149
Interview with the Author
150
WML and WMLScript Tips & Tricks
154
Learning WML & WMLScript The next generation of mobile communicators is here, and delivering content to them will mean programming in WML (Wireless Markup Language) and WMLScript, the languages of the Wireless Application Environment (WAE). The WAE allows information in almost all applications to be formatted for display on mobile devices, such as cell phones, and enables the user to interact with the information. Why learn yet another technology? According to some estimates, 75 percent of web document viewing by the year 2002 will be through non-desktop devices, many using wireless technologies. Clearly, the future is wireless. For web developers who want to get up to speed quickly in these languages, Learning WML & WMLScript maps out in detail the WAE and its two major components, WML and WMLScript. Fortunately, the WAE provides a World Wide Web-like model for writing applications, incorporating several key features of the Web to ease the transition for developers. Almost all wireless applications can be written with WML, which replaces HTML in the wireless environment, and WMLScript, which replaces JavaScript. With this book, web developers with some knowledge of programming and C, Java, or JavaScript syntax can easily master both languages. Chapter by chapter, Learning WML & WMLScript takes readers through the following WML topics:
•
Decks, templates and cards
•
User Interaction
•
Variables and contexts
•
Tasks, events, and timers
•
Text and text formatting
•
Images
WMLScript topics include:
•
Data types, conversions and variables
•
Operators and expressions
•
Statements
•
Functions
•
Standard libraries
Learning WML & WMLScript is the resource of choice for application developers who want to upgrade their skills and their sites so they won't be left plugged in during the wireless revolution.
Learning WML & WMLScript Preface The Wireless Application Protocol (WAP) is an industry-wide specification for applications that operate over wireless networks, with particular emphasis on applications for mobile devices, especially mobile phones. The standards are published by the WAP Forum, a body formed in June 1997 by Ericsson, Nokia, Motorola, and Unwired Planet, which has since been joined by over a hundred other companies, including IBM, HewlettPackard, Visa, and Microsoft. According to the WAP Forum's official statistics, WAP Forum members represent over 90% of cellular-phone manufacturers worldwide. WAP will be supported by many kinds of devices, from simple cell phones similar to those available today to a new generation of "smart" phones with large touch screens and many applications of their own. That's before we even look at the range of personal digital assistants (PDAs) available, from palmtops to full miniaturized computers complete with keyboards. All will eventually get WAP capabilities, either directly from the manufacturer or as some sort of third-party upgrade. Each device has a different kind of display and different methods for user input. The job of the WAP specification is to sort out this mess and provide a common framework to allow applications to run across all these different platforms. Since WAP works in a mobile environment, it also has to contend with the particular problems of wireless networks: low bandwidth (9600 bps or less is commonplace), high latency (round-trip times of the order of seconds are not uncommon), and unreliability (someone may be using her WAP phone when the train goes into a tunnel or when she walks past a tall building). Everyone with a mobile phone knows about the reliability problems. These problems are why WAP is necessary. Some people may ask why they can't just have normal web pages delivered over normal TCP/IP connections, the only difference from their PCs at home being the wireless link. The trouble with the normal web technologies is that they are aimed at high bandwidth and big screens. WAP keeps the Internet model but optimizes each component for a mobile environment. It keeps track of the state of a session in case the connection is lost, provides compressed formats for the transferred data, and handles displaying of applications regardless of the input and output available.
The WAP Stack The term that refers to all the different parts of the WAP specifications is the WAP stack. This is because the components can conceptually be thought of as layers in a stack. The user interacts with the top of the stack, and the communications hardware sits below the lowest level. This concept is illustrated in Figure P.1, together with the names of the various specifications involved. Going from bottom to top, the lowest layer in the figure contains various protocols (the so-called bearer protocols), which aren't actually part of WAP but which provide the link between WAP and the actual communications hardware:
•
IP (Internet Protocol) and PPP (Point to Point Protocol) are the two lowest-level protocols in normal dialup Internet access. (Many first-generation WAP devices work by making a normal dialup call and sending the WAP data across a modem link. IP and PPP are used in such a case.)
•
SMS (Short Message Service) is a feature provided by most digital mobile phone systems that allows short messages to be sent and received across the wireless link. (Users see this as the ability to send short text messages - a bit like email.) It can also transmit binary data and be used for WAP.
•
GPRS (General Packet Radio System) is a next-generation mobile phone system that will bring higher bandwidth and permanent network connections to cell phones and other wireless devices. Instead of having to dial into the server, a cell phone will effectively have a permanent Internet connection. GPRS is based on IP.
page 1
Learning WML & WMLScript Figure P.1. The WAP stack
The next layer up includes various low-level WAP communications protocols: WTP (Wireless Transaction Protocol), WTLS (Wireless Transaction Layer Security), and WDP (Wireless Datagram Protocol). WTP and WDP provide low-level glue between the upper levels and the really low-level communications. WTLS provides security services (encryption and authentication). These protocols aren't relevant to normal application programmers: unless you're designing a browser, you don't need to know about them. The second highest level in the stack is the high-level communications protocol, called WSP (Wireless Session Protocol). This provides a complete replacement for HTTP (HyperText Transfer Protocol), which is the protocol used between web servers and web browsers. Although you don't need to know how this layer works, there are one or two features that may be directly useful: these are described in Appendix B. The highest stack level is the WAE (Wireless Application Environment), which is the part that the user actually sees and with which she interacts. The WAE aims to provide a World Wide Web-like model for writing applications, allowing existing web developers to ease the transition to producing content and applications for mobile devices. To achieve this, the WAE incorporates several key features of the Web that you'll be familiar with, including URLs (like http://www.wap.net) and MIME content types (such as text/html and image/gif. Additionally, it provides similar replacements for other features: HTML is replaced with WML (Wireless Markup Language), and JavaScript is replaced with WMLScript (Wireless Markup Language Script). Almost all WAP applications can be written without using anything outside of these two languages and WBMP (Wireless Bitmap: the WAP image format), so they form the vast majority of what you as a developer need to know (and the vast majority of this book!).
page 2
Learning WML & WMLScript From Server to Client The complete chain of processing that occurs to WAP content on its journey to the user is illustrated in Figure P.2. (This figure omits the details of the communications, since they're not very important, and they change depending on the precise low-level bearer protocol in use.) Figure P.2. WAP chain of processing
The WAP browser in the figure can run on any supported device, from a cell phone to a PDA. Generally, cell phones need to be designed to support WAP, but most modern PDAs can be upgraded to support WAP simply by purchasing the browser software and installing it. PDAs need to be used with a cell phone to provide the connectivity. The origin server (on the far right of the figure) stores or generates the content itself. In nearly all cases, the protocol used to communicate with the origin server is standard HTTP, so this can be a standard web server. It's usually necessary to make a couple of minor modifications1 to the server's configuration, so it can serve WAP content. All the most popular web-server software can perform this task. An interesting solution is to use a technology such as XSLT (XML Stylesheet Language Transformations), which allows both HTML and WML to be automatically generated from the same raw data. Not included in the picture but quite likely to be present is some sort of backend database server. The origin server uses standard web technologies (such as CGI scripts or Java servlets, for instance) to generate any required dynamic content. These scripts probably need to communicate with a database to get the raw data to output. (This is going beyond the scope of this book, however. All standard techniques for generating web content on a server will also work for WAP, so you should read a book on one of those.)
The WAP Gateway The WAP gateway box in Figure P.2 is the more interesting. The job of the WAP gateway is to convert between the browser's WAP communication protocols (WSP, WTP, and so on) and the standard HTTP and TCP/IP protocols required by the origin server. It's also responsible for converting the content output by the origin server (formatted as text) into the compressed binary formats of WML and WMLScript as required by the browser. The gateway consists of some software to do this conversion, usually running on some sort of standard hardware. (Most proper gateways run on heavy-duty Unix servers, but there is low-end gateway software available that even runs on a Windows-based PC.) The gateway's owner must also handle the connection to the bearer network. For a dialup-based bearer, this process is achieved through a standard access server (the same pieces of hardware people use to dial in to the Internet), but for such bearers as SMS and GPRS, the connection will probably involve a leased line to a carrier. Because of all these infrastructure requirements, most people offering WAP content will not run their own gateways. (Many people will run their own origin servers, since this is not much different from running a normal web server, but far fewer people will run full WAP gateways.) All cell phone carriers that want to support WAP (which is most of them) will probably run their own gateways, and a number of other portal sites already exist, which also run gateways. Since most of these allow users to connect to any content on the Internet, a user just needs an account on one of these to access all the third-party content available.
1
Specifically, modifications include adding support for the WAP content types. The types that need to be added are described in Appendix D. page 3
Learning WML & WMLScript This Book This book doesn't aim to cover the low-level details of either the communication protocols (from your perspective, they behave just like HTTP) or the compressed file formats (it doesn't matter to you how your application gets to the device; all that matters is that it does). I also don't go into the details of how security and encryption are handled (these are just other parts of the communication process). Most web developers don't bother to learn how HTTP or TCP/IP work, as they can get by just fine without, and it only distracts them from their real job of writing web pages. If you want to know these details, you can download the latest versions of the specifications from the WAP Forum's web site (http://www.wapforum.org).
Conventions Used in This Book This book uses the following font conventions: Italic Indicates operating-system pathnames; filenames; program names; Internet addresses, such as domain names and URLs; and new terms where they are defined. Boldface Indicates names of GUI items: window names, buttons, menu choices, etc. Constant width Indicates code, command lines, and options that should be typed verbatim; names and keywords in WML and WMLScript programs, including function names and variable names; and XML element tags.
Italic constant width Indicates items in code where the user or programmer must supply a name or value.
The owl icon designates a note, which is an important aside to the nearby text.
The turkey icon designates a warning relating to the nearby text.
page 4
Learning WML & WMLScript Comments and Questions The information in this book has been tested and verified, but you may find that features have changed (or you may even find mistakes!). You can send any errors you find, as well as suggestions for future editions, to: O'Reilly & Associates, Inc. 101 Morris Street Sebastopol, CA 95472 (800) 998-9938 (in the United States or Canada) (707) 829-0515 (international/local) (707) 829-0104 (fax) To ask technical questions or comment on the book, send email to: [email protected] There is a web site for the book, where examples, errata, and any plans for future editions are listed. The site also includes a link to a forum where you can discuss the book with the author and other readers. You can access this site at: http://www.oreilly.com/catalog/learnwml For more information about our books, conferences, software, Resource Centers, and the O'Reilly Network, see our web site at: http://www.oreilly.com
Acknowledgments As ever, this book involves the work of many people besides myself. I am deeply grateful to my editor, John Posner, for his continual constructive criticism and innumerable helpful comments. Without them, this book would be vastly inferior. I really can't emphasize enough how great a help he was. Thanks to Christien Shangraw and Katie Gardner for finding and supplying me with the StarOffice template and for responding patiently to my queries. Thanks are also due to O'Reilly in general, for allowing me the opportunity to write this book. Thanks and apologies must go to my friends, who put up with me cancelling plans weekend after weekend so that I could get some writing done. Thanks especially to all the people who offered to read through the book before I sent it off: sorry that I never got any of it finished early enough to take you up on your offers! A small and select group of people have been particularly understanding in the face of almost complete abandonment to The Book. You know who you are. Thanks to my employer, for allowing me to write the book in the first place and for allowing me time off at short notice when deadlines were approaching. Finally, a special thanks must go to Leon, because of the quantity of beer he promised me if I'd give him a mention.
page 5
Learning WML & WMLScript Chapter 1. Introduction to WML The heart of WAP from the point of view of you, the content developer, is a new markup language called the Wireless Markup Language ( WML). If you have worked with the HyperText Markup Language (HTML), much of WML will look familiar but be warned that there are several differences that can easily catch you out. Some of these differences come from WML's simplicity compared to HTML: many features that are found in HTML are simply not present in WML. To use a common example, HTML gives you great control over the appearance of text within a document: you can change its size, specify the typeface to be used, add styling such as boldface or underlining, and have a fine degree of control over its color. The only controls WML gives you over the text are a few simple styles (emphasis, strong emphasis, boldface, italics, and underlining) and the ability to specify text that is larger or smaller than normal. A further surprise is that most WAP browsers to date don't even support most of these. Losing this control over appearance that HTML provides forces you to think in a different way about the pages you write, concentrating on content rather than appearance (substance over style, if you like). If you've ever designed a web page to be usable under a really old browser (or a text-only browser) as well as the latest version of a major browser, you'll already have a good idea of the sort of things you need to bear in mind. Not all browsers even know about recent HTML such features as tables, frames, or stylesheets, and if you want to support people with those browsers, you have three choices: avoid the new feature altogether, write your pages to work even if the feature isn't present, or provide multiple versions of your pages and allow the user to select his favorite combination of features. In the same way, not all WAP browsers support images, tables, or text style changes,2 and if you rely on them, you reduce the potential audience for your pages dramatically. It's not all bad, though. While WML does drop many of the features of HTML, it adds some powerful new ones, and because it was designed from the start for interactive applications many of the headaches of the web world simply disappear. It also has the advantage of having been designed in one go, rather than having features haphazardly added by different people without any proper overall coordination, which is the case with many of the new features of HTML.
1.1 A Complete Example Before we discuss WML any further, Example 1.1 displays the time-honored "Hello World." The code for this example, as well as all the other substantial examples, is available on the book's web page (http://www.oreilly.com/catalog/learnwml). Example 1.1. A Simple WML Example <wml>
Hello, World!
Depending on the browser in use, this may look something like Figure 1.1. Several things need to be explained about this example, but for some of them you'll have to wait until later chapters. The first thing to note is the special header (the first four lines). This looks confusing, but you don't actually need to know what it means: just include it at the top of all your WML pages, and all the programs that deal with them will be happy.3
2
3
There are several reasons why these features may not be available. One is that some displays may simply be unable to cope with the features. Another reason, which is common at the moment but which will hopefully go away in the future, is that less widely used features were often lost in the rush to get a WAP device out into the market as early as possible. If you're familiar with the eXtensible Markup Language (XML), you'll recognize these lines as the XML prolog for the document. (WML is an XML application, which means that WML documents follow a set of rules laid down in the XML specifications.) If you're don't know XML, it doesn't matter: just copy those four lines and live in blissful ignorance. A number of other parts of WML syntax are also derived from XML: I will point these out as we encounter them. page 6
Learning WML & WMLScript Figure 1.1. Example 1.1 displayed in a WAP browser
The second thing to note is that all tag names are in lowercase (tags are inside angle brackets). This is important: unlike HTML, where , , , and all refer to the same thing, in WML, tag names are case-sensitive. All current WML tag names are lowercase, so you must enter them that way in your pages. If you've seen some HTML, the rest of the WML syntax should look vaguely familiar, although the first tag is <wml>, not , and there's that mysterious-looking tag. The
tag simply starts a paragraph of text (in this simple case, there is only the one).
1.2 Cards The reason for the tag is that WML structures its content differently from HTML. Instead of a file being a long stream of content, a file of WML represents a deck of cards. Only one card is displayed at a time, but you can link from one card to another and store several in a deck in the same file. Each individual card does in fact behave very much like an HTML page, so you can think of a WML deck as being similar to a number of HTML pages all grouped together. It's good WML style to use decks of cards to group together related information or user interactions. Cards in a deck are all downloaded at the same time, so the user has to wait only once, and the others can be accessed almost instantly. Conversely, it's bad WML style to overuse cards, cramming too many into a single deck (and hence into a single downloaded file). Even if you think 30 cards of information are all relevant at the same time, the user will get bored waiting for all of them to download before she gets to see the first one. It is hard to put a fixed limit on the number of cards you should use, but here's a general rule of thumb: if you find yourself using more than five or six cards in a single deck, you should think hard about how your pages are organized. Although you shouldn't concern yourself too much with the transmission of the content, another thing to bear in mind is that many devices can't cope with large files. (The Nokia 7110 cell phone, the most popular WAP device in Europe, has trouble if the deck is more than about 1400 bytes after being passed through the gateway.)
page 7
Learning WML & WMLScript 1.3 Empty-Element Tags Now, just to worry all the HTML users some more, check out Example 1.2. Example 1.2. An Interesting Tag <wml>
You should recognize most of the structure from Example 1.1, and the tag may be familiar from HTML, but look more closely at the end of the tag: note the extra slash. This is required in WML whenever a tag has no matching end-tag. (An end-tag has a slash after the first angle bracket, like .) These so-called emptyelement tags are quite common in both WML and HTML, but HTML doesn't decorate them in any special way, so they look just like start-tags. This makes some unnecessary work for the browser and any other program that has to read the file, so WML makes the structure more consistent.4
1.4 Elements An alternative way of thinking about these extra slashes is to think in terms of elements.5 An element takes one of two forms: either a start-tag and an end-tag (whose types must match): . . . or a single empty-element tag (complete with extra slash): Note that there is exactly one slash per element. An element can contain other elements (either matched pairs or empty-element tags), possibly mixed up with flow text. Looking at Example 1.2 this way, there is a single <wml> element (as a matched pair <wml> ), containing a single element (as a matched pair ), containing a single
element (also as a matched pair,
), which in turn contains a single element (as the empty-element tag ). It's important to ensure the tags match properly. Mismatching tags such as: <x>......... is an error and will prevent the page from being displayed. This should have been written as: <x>.........
4
5
Again, you may recognize this as another feature WML takes from XML. This feature is critical to XML, and it also makes WML files easier for the browser to read and parse. If you don't know XML, don't worry: just remember to add the extra slash whenever there isn't a matching end-tag. Looking at the document in terms of elements also comes from XML. page 8
Learning WML & WMLScript 1.5 Attributes Start-tags and empty-element tags (but not end-tags) may also have attributes. (In Example 1.2, the title on the tag and the src on the tag are both attributes.) Attributes affect the behavior of the whole element, which is why they can't appear on end-tags (the only purpose of the end-tag is to mark the end of the element). The effects of attributes vary between different elements: the title attribute on the element sets an optional title to be displayed with the card, while the src attribute on the element gives the URL at which the image can be found. You can also add an align="center" attribute to the
element, which centers that paragraph of text (if the browser supports the feature). A further slight difference between WML and HTML is in the quoting of attribute values. In HTML, attribute values may appear in single quotes (attr='value'), in double quotes (attr="value"), and most web browsers also allow them to be unquoted altogether (attr=value), although this isn't strictly valid. WML doesn't allow unquoted attribute values: all values must appear within either single or double quotes.6 1.5.1 Notation for Attributes Within this book, whenever an attribute is described, a brief summary of the type of value it takes is given in parentheses after its name. The following terms are used in these descriptions: string The value can be any string. url The value should be a valid URL. Unless noted otherwise in the description of the attribute, relative URLs (where only part of the URL is given) are OK; these are resolved relative to the current document's URL. Resolving is the process of taking an incomplete (relative) URL and turning it into a complete (absolute) URL. It is described in detail in Appendix A. number The value should be a nonnegative integer. length The value represents a length on the browser's display. It can be specified either as a whole number of pixels or as a percentage (which represents a percentage of the width or height of the screen). In either case, the value must not be negative (but may be zero). boolean The value should be one of the strings true or false. Case is important! name The value should be a string containing only letters, digits, dots, colons, hyphens, and underscores. It is better, however, to avoid the dots, colons, and hyphens, and use only letters, digits, and underscores. variable The value may contain embedded variable references (see Chapter 2, for more information on variables). optional The attribute may be omitted.
6
The rules for quoting attribute values are another thing that will be familiar to XML users, since WML takes them from XML. If you don't know XML, just remember you must use either single or double quotes around all attribute values. page 9
Learning WML & WMLScript required The attribute must be present for the element to be processed correctly. Many browsers will refuse to process a deck if required attributes are missing. default The default value for the attribute. This value is used if the attribute isn't specified on the tag. Only optional attributes can have defaults.
1.6 Entities The final bit of WML syntax you need before starting on the range of different elements is the entity. You may recognize entities if you've ever had to put certain special symbols (quotes, greater than and less than signs, and several others) into an HTML page. Their purpose is to represent symbols that either can't easily be typed in (you may not have a British pound sign on your keyboard) or that have a special meaning in WML. (For example, if you put a < character into your text normally, the browser thinks it's the start of a tag; the browser then complains when it can't find the matching > character to end the tag.) Table 1.1 displays the three forms of entities in WML. Named entities are something you may be familiar with from HTML: they look like & or terminator. If for some reason you want the sequence <do type="accept" label="Submit"> <postfield name="l" value="$(login)"/> <postfield name="p" value="$(password)"/> <setvar name="state" value="0"/> <do type="accept"> <postfield name="s" value="$(state)"/> <postfield name="t" value="$(text)"/> If the task bound to the onenterforward event is a simple task without <setvar> or <postfield> elements, you can use the shorthand form introduced earlier in this chapter: just add an onenterforward attribute to the element. The value of this attribute is the destination URL. For example, the event binding: It's your choice to use the shorthand form, but it means less typing and results in less data being sent to the browser.
page 22
Learning WML & WMLScript Be warned that not all tasks you can bind to the onenterforward event actually make sense. For example, the event binding: <prev/> makes it impossible for the user to enter the card at all: as soon as she went to the card, the browser would immediately return to the previous one! To make matters worse, the event binding: means that as soon as the browser entered the card, it would be immediately redirected to the same card, which would cause an immediate redirect to the same card, and again, and again…. Well-written browsers may notice this and signal an error, but not all browsers are well-written: many simply lock up or even crash.
3.2.2.2 The onenterbackward event The onenterbackward event is the companion of the onenterforward event for the backward direction. This event is triggered when the card is returned to as the result of a <prev> task or some other action that navigates backwards in the history stack. The most common use for the onenterbackward event is to reset state back to some initial value when returning to the beginning. Example 3.3 alters Example 3.1 to illustrate this: instead of an explicit reset button, the login and password are cleared when the user returns to this card via the history stack. Example 3.3. Reset on Reentry <wml>
Login:
Password:
is equivalent to: <do type="accept" label="Order"> If I then decide that I want a pizza with all these toppings except anchovies, the variable toppings is set to p;h;b;c;o;m, or m;o;c;b;h;p, or b;c;h;m;o;p, or any of the 717 other combinations of those six items. (No, I'm not going to list them all.)
page 29
Learning WML & WMLScript If there had been an iname as well as (or perhaps instead of) the name, the variable it referenced is set to 1;2;3;5;6;7 or a permutation of those values. In single-selection lists, however, the character ; is valid in option values. Example 4.3 shows Example 4.2 extended with an earlier card offering set pizzas and the chance to customize them by adding and removing toppings. Note that the option of going back from the second card to the first isn't provided here. This is because the values in the toppings variable may not be in the same order as they were when the first <select> initialized them, because their order is not fixed after a multiple selection. Example 4.3. Mixed Selections <wml>
Choose a Pizza:<select name="toppings"> Pepperoni Supreme Vegetarian
<do type="accept" label="Order"> <do type="accept" label="Customize">
Customize your Toppings <select name="toppings" multiple="true"> Pepperoni Ham Spicy Beef Anchovies Olives Mushrooms Chillies
<do type="accept" label="Order">
4.5 The Element While on the subject of the <select> element, it's time for a closer look at the element that is so vital to it. You've already seen the two most common ways to use this element (with or without a value), but it's also possible to bind a task to an option, so that the task is performed when the user selects the option (or deselects it, for a multiple-selection list). This task is bound to the onpick event. It can be bound either with a conventional binding, or for simple tasks it can be specified with the onpick attribute on the tag itself.
page 30
Learning WML & WMLScript 4.5.1 Attributes of the Element value (optional variable string) Gives a value to this , which is stored in the name variable of the <select>, as detailed earlier. title (optional variable string) Gives a title to this , which some browsers may use to display the option, but some may ignore. onpick (optional variable URL) Provides a shorthand method of binding to the onpick event, for the common case where the task is a simple go. Because this task is reduced to just the URL, it cannot contain any <setvar> or <postfield> elements, and its method is limited to GET. In complicated cases, put an element of type onpick inside the element.
4.6 The Element WAP doesn't define how the <select> element is displayed. It has been implemented in many different ways, including using pulldown menus, scrolling lists, and lines of checkboxes on PDA-type devices and several different types of menus on cell phones. With a small screen, it isn't always possible to display all the available options at the same time. There are several ways to get around this problem: if the options are displayed normally in the text of the page, as with checkboxes for example, then the normal facilities for scrolling the page will do. Many cell phones simply display the currently selected option; activating this for editing changes the screen to a different display with the options. When the editing is complete, the display changes back to the card. The purpose of the element is to divide a long list of options into several sections. Different browsers may use this information in different ways: many simply ignore it (particularly those running on devices with large screens). Others may display the title of the group as part of the option display but not do anything more with it. Some may use the group title as the name of a submenu, with the contents of the group in that submenu. The information is a hint, nothing more. The element takes only one attribute: title (optional variable string) Specifies a title for this group, which may be used by the browser (for example, as the title of a submenu). It may also be completely ignored. As an example, the element can be used in the list of pizza toppings to separate the toppings into different groups: <select name="toppings"> Pepperoni Ham Spicy Beef Anchovies Olives Mushrooms Chillies At publication time, few browsers support the element.
page 31
Learning WML & WMLScript 4.7 The <do> Element The and <select> elements provide high-level user controls, but sometimes all you want is a simple button or menu item. In these cases, the <do> element is exactly what you need. A <do> element is simply a way to specify some arbitrary type of control for the browser to make available to the user. This can be rendered as a graphical button (as many PDA browsers do), as an item in a menu (as most cell phone browsers do), or as just about anything the user can know about and interact with. This can even include things such as voice commands for a hands-off WAP browser (in a car, for example). A <do> element contains nothing but the task to be performed when the element is activated. 4.7.1 Attributes of the <do> Element type ( required string) Specifies the type of this <do> element. This serves as a hint to the browser about the action this element triggers and may influence how the browser chooses to present the element. The following values are defined (undefined or unrecognized types are treated as if they had been specified as unknown): accept Acceptance of something. cell phones often bind this to the "yes" key if there is only one <do> of this type in the card. prev Navigation backwards in the history stack (a <prev> task or something similar). help Request for some sort of help. The help provided can be context-sensitive. reset An operation that clears or resets the state of the interaction; for example, a "clear and start over" operation on a group of text fields or an operation to deselect all options in a <select> element. options A context-sensitive request for additional options; for example, a button to bring up an "advanced options" menu. delete Delete a single item or choice. To delete all items, use the reset type instead. unknown (or empty string) A generic element that doesn't fit any existing category. Any name starting with X- or xExperimental types. The exact behavior of these is undefined. Some browsers may implement some of these for development purposes. These types shouldn't be used in production systems. Any name starting with vnd. (case-insensitive) Vendor-specific types. Some browsers may implement specific <do> types of this form. Using these types allows you to enhance your WML for a specific browser, while remaining portable to others (unrecognized types are treated as if they were specified unknown).
page 32
Learning WML & WMLScript label (optional variable string) Specifies an optional text label for the element. For example, a browser that displays <do> elements as graphical buttons can use this as the button's text. The WAP specifications recommend that to work well on the widest possible variety of browsers, this string should be limited to no more than six characters, but this rule isn't enforced. name (optional name) Specifies the name of this element, for the purposes of shadowing (see Chapter 6, for more on shadowing). This type has no other effect. optional (optional boolean; default false ) If set to true, informs the browser that it can ignore this <do> element.
4.8 The Element While the <do> element is useful, it isn't always what you want. Many cell phone browsers put all the <do> items in a card in a single menu, which means you can't guarantee it will appear where you want it to. Sometimes you want to make some of the text into an HTML-style link, rather than have a separate <do> control next to it. For example, if you have a menu of other pages available, you want the items in the menu to display in the correct order, as in Figure 4.1. Figure 4.1. Menu of available pages
page 33
Learning WML & WMLScript
Almost all web pages use hyperlinks : text or images that can be activated to go to another page. Web browsers usually display these links underlined or in a different color so the user knows it's "clickable." These links are put into a web page with HTML's tag. WML also has hyperlinks. As you might expect from the other user interaction elements you've seen in this chapter, they aren't limited to simply going to another place. WML hyperlinks use tasks to allow them to control just about anything useful. Hyperlinks are put into a page using the element. It takes only one attribute: title (optional variable string) Provides an optional title to the element. As with the label attribute on the <do> element, you should try to keep this to six or fewer characters, and the browser is free to ignore it. This is rarely used in practice, as there is already the linked text inside the to provide a label. The element must contain two things: a task element that is performed when the element is activated and some text or images to which to attach the link. A simple example of the element is: next page This attaches a link to the words next page, so that selecting them sends the browser to the URL page17.wml. The most common tasks to use with elements are tasks. For other kinds of tasks, consider using <do> elements instead. For example, if you want a control to activate a <prev> task, you should strongly consider simply using a <do> with type set to prev. It's best to use only where it's important that the control is kept with the text surrounding it.
4.9 The Element If you've done much work with HTML, the element may seem like a lot of typing. Sure, it's more flexible than HTML's tag, but it seems much nicer to simply type: linked text than it is to type: linked text Fear not: the designers of WML also recognized this fact and provided WML with the element. (The name must be a lowercase a.) It's a useful shorthand for this simple case of the element, which also has the benefit of looking familiar to HTML developers. It takes two attributes: title (optional variable string) This has exactly the same effect as the title attribute on the element. It provides an optional title for the element, which some browsers may use in displaying it. The same caveats apply: it's wise to keep the length to at most six characters, and the browser is free to ignore the attribute (as indeed most do). href (required variable URL) Specifies the URL to go to when the link is activated.
page 34
Learning WML & WMLScript For example, the element: Next Page is exactly equivalent to: Next Page The form using the element is also more efficient than the form using , as there is less to transmit to the browser. Try to use the form wherever possible.
4.10 The tabindex Attribute Some browsers can cycle through and <select> in a card using some sort of TAB key or similar control. Normally, the order in which this happens is chosen by the browser (usually the order in which the elements are specified in the card). The tabindex attribute allows this order to be changed for some or all of the elements in a card. Not all browsers support this feature, as it doesn't fit into all of the user interfaces. If this feature is supported, the browser sorts all the and <select> elements with a tabindex specified in ascending order. Pressing the TAB key (or whatever normally cycles through such elements) then selects these elements in this order. Any elements in the card without a tabindex specified are selected last. Example 4.4 shows how this attribute can be used. The user is asked for a normal postal address. Both the county and nation fields have no tabindex: nation because it has a default, and county because it's usually unnecessary to give a county or state if the postal code is correct. The <do> element at the end calls a WMLScript function to check that the values are acceptable (for example, if no postal code is given, a county is required). Example 4.4. Use of the tabindex Attribute <wml>
Street:
Town/City:
County/State/Province:
Postal/Zip Code:
Nation:
<do type="accept" label="OK">
page 35
Learning WML & WMLScript
Chapter 5. WML Timers The previous chapters described how to interact with users in WML. Sometimes, however, you may want something to happen without the user explicitly having to activate a control. To take a common example, suppose you want to display a company logo when the user connects to your WAP service. On a web page, you'd keep the image for the logo on screen the whole time, but WAP devices have limited screen sizes, and you can't afford to waste the space. You could put the image at the top of the first page and let the user scroll down, but cell phone keypads are fiddly, and you'd prefer that the user didn't have to mess around to see the rest of the service. The same thing rules out a "click to enter" type of control. What you really want is for the logo to be displayed for a second or two so that the user sees it, and for him to then be transported automatically to the main card. This can be done with a WML timer.
5.1 Using Timers with WML A WML card may have a timer. Whenever the card is entered (whether forwards, as the result of a task, or backwards, as the result of a <prev> task), the timer is initialized with a timeout value and started (unless the timeout is zero, in which case the timer never starts). Once the timer has started, it counts down either until the count reaches zero or until a task is executed. If a task is executed, the timer is simply stopped beforehand. (Note, however, that a <noop> task doesn't affect the timer at all.) If the count reaches zero, however, an ontimer event is triggered on the card containing the timer. This event should be bound to a task, either with an element or with the ontimer attribute of the element. 5.1.1 A Simple Example Before looking in depth at the elements that make timers work, Example 5.1 shows the simplest way to display a logo for a short time and then go to the main card. The image is displayed for one second, and then the second card is displayed. There is also a <do> element that allows the user to go directly to the second card without having to wait for the timer. Example 5.1. Displaying a Logo <wml> You can write it more compactly as: <setvar name="display" value="0.0"/>
7 8 9 +
4 5 6 -
1 2 3 *
0 . = /
The basic structure of the page is a result display at the top, followed by four rows of four keys each. These keys are implemented using the element, adding hyperlinks to characters on the page. The keys are laid out in four rows to look like the layout of keys on a simple pocket calculator. Note also the element, which initializes the display variable, so that the display looks right before any keys are pressed. 21.1.1 WMLScript for the Calculator The WMLScript backend for the calculator example needs to provide the three functions referenced by the WML: digit( ) to add a digit to the number, point( ) to add a decimal point, and op( ) to perform an operation. In addition to the display variable already defined, the example needs a few additional variables to emulate the behavior of a pocket calculator. Users enter a sequence of numbers with the digit and decimal point keys, separating the numbers with operators. It's conventional for the operator keys to display a running total as they go along. The following example uses the variable register to store the running total: either the first number entered or the result of the last operation. It also uses both the variable number to store the number currently being entered, so you can keep track of whether the decimal point key has been pressed, and the variable lastop to store the last operator key pressed (because the operation isn't performed until after the second number is read).
page 135
Learning WML & WMLScript Example 21.2 gives the script file for the calculator. Example 21.2. WMLScript for Calculator /* * WMLScript backend for calculator example. */ /* * Add a digit to the number currently being entered, and update display. */ extern function digit (d) { /* Read the current number as a string from the browser context. */ var number = WMLBrowser.getVar ("number"); /* Add digit to number. (Note that the variable 'number' actually * contains a string at this point, so this concatenates strings.) */ number += d; /* Set browser variables and refresh the display. */ WMLBrowser.setVar ("number", number); set_display (Lang.parseFloat ("0" + number)); } /* * Add a decimal point to the number currently being entered. */ extern function point ( ) { /* Read the current number as a string from the browser context. */ var number = WMLBrowser.getVar ("number"); /* Ignore the key if there's already a decimal point. */ if (String.find (number, '.') >= 0) return; /* Add a decimal point to the number. */ number += '.'; /* Set browser variables and refresh the display. */ WMLBrowser.setVar ("number", number); set_display (Lang.parseFloat ("0" + number)); } /* * Handle an operator key: perform the last operation and store this * operator until the next number has been entered. */ extern function op (op) { /* Fetch the register and convert to floating point. */ var register = Lang.parseFloat (WMLBrowser.getVar ("register")); /* Fetch the number and convert to floating point. */ var number = Lang.parseFloat (WMLBrowser.getVar ("display")); /* Fetch the last operator key. */ var lastop = WMLBrowser.getVar ("lastop"); /* Work out what operation needs to be performed and perform it. */ if (lastop == 'add') register += number; else if (lastop == 'sub') register -= number; else if (lastop == 'mul') register *= number; else if (lastop == 'div') register /= number; else register = number; /* Store the new operator for next time. */ WMLBrowser.setVar ("lastop", op); /* Clear the number so we can enter a new one. */ WMLBrowser.setVar ("number", ""); /* Both the display and the register are the result of the operation. */ WMLBrowser.setVar ("register", String.toString (register)); set_display (register); }
page 136
Learning WML & WMLScript /* * Set the display browser variable and refresh the display. */ function set_display (display) { /* Handle an invalid calculation result. */ if (!isvalid display) display = "(error)"; /* Set the browser variable. */ WMLBrowser.setVar ("display", display); /* Refresh the display. */ WMLBrowser.refresh ( ); } There are several things to note about this script file. First, the private function set_display( ) sets the display variable and refreshes the display, but also handles invalid values (in the case of division by zero, for example). Second, note how each of the external functions falls into the same pattern: 1.
Read variables from browser context.
2.
Operate on them.
3.
Write new values back into the browser context.
4.
Perform a task.
In the case of this calculator, the task in Step 4 is always a refresh, and the set_display( ) function handles part of Step 3 and all of Step 4. 21.1.2 Finishing Off Combining the WML of Example 21.1 and the WMLScript of Example 21.2 works, because the newcontext attribute on the element clears the variables. However, it's bad practice and prone to errors to rely on this sort of behavior, so for the sake of neatness and readability, let's add three further <setvar> elements to the task performed when the card is entered. This avoids problems if someone were to remove the newcontext attribute at a later date, without knowing how important it is. Also, there is no way to correct a mistake or clear the calculation. Most pocket calculators have a Clear button, which resets the number currently being entered without affecting the overall calculation, and an All Clear button, which resets the whole calculation. These should be added to the example. The final WML file is given in Example 21.3.
page 137
Learning WML & WMLScript Example 21.3. Final WML for Calculator <wml>
$(display)
<setvar name="display" value="0.0"/> <setvar name="number" value=""/> AC
$d_0_0 $d_0_1 $d_0_2 $d_0_3
$d_1_0 $d_1_1 $d_1_2 $d_1_3
$d_2_0 $d_2_1 $d_2_2 $d_2_3
$d_3_0 $d_3_1 $d_3_2 $d_3_3
page 139
Learning WML & WMLScript Note how the grid of possible guesses looks very much like the keyboard for the calculator. Each square is a hyperlink to a WMLScript function called with two arguments: the row and column of the cell. There are differences from the calculator, however. Note how the text for each of the grid cells comes from a variable whose name contains the row and column of the cell. This regular form for the names makes the WMLScript much simpler, as you will see. Another major difference is that the initialization isn't done with a simple task. Instead, it's done via a WMLScript function called init( ). This function is called from the onenterforward attribute on the element. 21.2.1 WMLScript for Battleships The WMLScript for the battleships example is quite simple. There is one initialization function, one function to handle the user guessing a square, and an additional function to congratulate the user when the game is over. To make Example 21.5 simpler, the initialization doesn't fill the ships in randomly: the same fixed pattern is used each time. Example 21.5. WMLScript for Battleships /* * WMLScript for battleships game. */ /* * Initialize the grid. For simplicity, we don't place the ships randomly. * Instead, there is one fixed grid layout. */ extern function init ( ) { /* Initialize all the display variables to a space. */ for (var i=0; i element in WML (see Chapter 6) - specifically the http-equiv form. The WMLScript meta pragma can also specify headers (see Chapter 14). There are many headers: most are used only for low-level communication and aren't useful for you to set directly. These include headers giving the length of the contents, for example. This information is calculated for you by the WAP gateway, so there's no need to do it yourself. Headers related to caching are useful, however. As you may know, web browsers keep a local cache of responses, to save on repeated network activity fetching the same page or image again and again. WAP browsers also do this, and the caching headers allow you to control how an item is cached, how long it can be kept, and even whether it's cached at all.
B.2 Browser Support for Caching Unfortunately, support for caching headers (or indeed many headers at all) is very poor in WAP browsers at the time of this writing. This means that pages may be cached even when you specifically request them not to be. To get around this, many sites insert a random number into the URL and set up the server to ignore this. Because the number changes from request to request, the browser treats each repeated request as if it were a new request. For example, suppose there's some information that changes regularly at the URL: /news/headlines.wml You can add a header that prevents the page from being cached at all, using the http-equiv form of the <meta> element in WML: <meta http-equiv="Cache-Control" value="no-cache"/> However, the browser may well ignore these header. To get around this, make the browser add a randomly chosen number to the URL requesting the page: /news/headlines.wml?9832077283 Set up your web server to ignore this number and just serve the same page, and your caching problems go away. (The Apache web server does this by default.)
page 145
Learning WML & WMLScript
Appendix C. Summary of WMLScript Operators Operator Operation
Operands
Result
Precedence: 1 (highest) / Associativity: none ++
Increment
Number
Number or invalid
--
Decrement
Number
Number or invalid
+
Unary plus
Number
Number or invalid
-
Unary minus
Number
Number or invalid
~
Bitwise not
Integer
Integer or invalid
!
Logical not
Boolean
Boolean or invalid
typeof
Get datatype
Any
Integer
isvalid
Check if valid/invalid
Any
Boolean
Precedence: 2 / Associativity: lef *
Multiplication
Number,number
Number or invalid
/
Floating-point division
Float,float
Float or invalid
div
Integer division
Integer,integer
Integer or invalid
%
Remainder
Integer,integer
Integer or invalid
Precedence: 3 / Associativity: left +
Addition or string concatenation
Number/string,number/string
Number or string or invalid
-
Subtraction
Number,number
Number or invalid
Precedence: 4 / Associativity: left
Shift right (signed)
Integer,integer
Integer or invalid
>>>
Shift right (unsigned)
Integer,integer
Integer or invalid
Precedence: 5 / Associativity: left
=
Greater than or equal to
Number/string,number/string
Boolean or invalid
Precedence: 6 / Associativity: left ==
Equal to
Number/string,number/string
Boolean or invalid
!=
Not equal to
Number/string,number/string
Boolean or invalid
Integer,integer
Integer or invalid
Integer,integer
Integer or invalid
Integer,integer
Integer or invalid
Boolean, boolean
Boolean or invalid
Precedence: 7 / Associativity: left &
Bitwise and
Precedence: 8 / Associativity: left ^
Bitwise exclusive or
Precedence: 9 / Associativity: left |
Bitwise or
Precedence: 10 / Associativity: left &&
Logical and
page 146
Learning WML & WMLScript Precedence: 11 / Associativity: left ||
Logical or
Boolean, boolean
Boolean or invalid
Boolean,any,any
Any
Precedence: 12 / Associativity: left ?:
Conditional
Precedence: 13 / Associativity: right =
Assignment
Variable,any
Any
*=
Assignment with multiplication
Variable,number
Number or invalid
/=
Assignment with floating-point division
Variable,float
Float or invalid
div=
Assignment with integer division
Variable,integer
Integer or invalid
%=
Assignment with remainder
Variable,integer
Integer or invalid
+=
Assignment with addition or concatenation
Variable,number/string
Number or string or invalid
-=
Assignment with subtraction
Variable,number
Number or invalid
=
Assignment with right shift (signed)
Variable,integer
Integer or invalid
>>>=
Assignment with right shift (unsigned)
Variable,integer
Integer or invalid
&=
Assignment with bitwise and
Variable,integer
Integer or invalid
|=
Assignment with bitwise or
Variable,integer
Integer or invalid
Any,any
Any
Precedence: 14 / Associativity: left ,
Sequential evaluation
page 147
Learning WML & WMLScript
Appendix D. Serving WAP Content from a Standard Web Server All the popular web servers can be configured easily to serve WAP content. In most cases, all that is required is to add a few extra content-type mappings to the server. Most web servers work out the content type of the data in their responses from the extension (suffix) on the filename. For example, a server may have a mapping that all files ending in .jpg or .jpeg have content type image/jpeg, and all files ending with .htm or .html have content type text/html. To serve WML and WMLScript from a standard web server, therefore, it's necessary to teach the server some new filename extensions and content types. The types that need to be added and the common extensions for them appear in Table D.1. Table D.1, WAP Content Types File Type
MIME Type
Extension
WML source
text/vnd.wap.wml
.wml
WMLScript source
text/vnd.wap.wmlscript
.wmls
WBMP image
image/vnd.wap.wbmp
.wbmp
WML binary
application/vnd.wap.wmlc
.wmlc
WMLScript binary
application/vnd.wap.wmlscriptc
.wmlsc
The last two rows in the table, the binary forms of WML and WMLScript, aren't as important as the others. They are useful only if you have access to a WML encoder or WMLScript compiler and want to preconvert your content. (This is a fairly advanced thing to do.) It won't do any harm to have them in the server even if you don't use them, though. The method for actually adding these mappings to the server depends on the server software. Most commercial web servers have some sort of graphical or web-based configuration interface that does this sort of thing. Consult the user's manual or your local expert. If you're using the free web server Apache, simply add the following five lines to the end of the mime.types file in the configuration directory, and then restart the server: text/vnd.wap.wml text/vnd.wap.wmlscript image/vnd.wap.wbmp application/vnd.wap.wmlc application/vnd.wap.wmlscriptc
wml wmls wbmp wmlc wmlsc
page 148
Learning WML & WMLScript
Colophon Our look is the result of reader comments, our own experimentation, and feedback from distribution channels. Distinctive covers complement our distinctive approach to technical topics, breathing personality and life into potentially dry subjects. The insect on the cover of Learning WML and WMLScript is a mosquito (nematocera culicidae). The mosquito is a flying, bloodsucking insect best known, and even feared, for its biting and spreading of disease. There are approximately 2,500 species of mosquitoes in the world, with over 150 species in North America. Mosquitoes usually live close to a water source because the larva must develop in water, which can be anything from a running stream to stagnant water in a birdbath. Depending on the species, a mosquito's life span is between two weeks and a few months. Some can hibernate at temperatures below 50 degrees F, but others can't survive in temperatures that low. Only female mosquitoes bite; males do not. Females must bite because they need blood to develop their eggs. They bite once per batch of eggs, and a female can lay several batches in her lifetime, which multiplies into many generations of mosquitoes per year. Both sexes feed primarily on nectar and other plant and fruit liquids. Mosquitoes are attracted to humans, and other mammals, by the carbon dioxide exhaled when breathing. Other factors also contribute, such as body odor, body heat, and sweat, and sometimes perfumes, deodorants, and detergents. Mosquito bites are more than just itchy and annoying, however. The real potential danger is that mosquitoes can be carriers and transmitters of many serious diseases such as malaria, yellow fever, encephalitis, and the West Nile virus in humans, heartworm in dogs, and Eastern equine encephalitis in horses. As a result, there are many efforts all over the world to control mosquito populations. Mary Anne Weeks Mayo was the production editor and copyeditor for Learning WML and WMLScript. Nicole Arigo proofread the book. Rachel Wheeler, Emily Quill, and Jane Ellin provided quality control. John Bickelhaupt wrote the index. Ellie Volckhausen designed the cover of this book, based on a series design by Edie Freedman. The cover image is an original illustration created by Lorrie LeJeune. Emma Colby produced the cover layout with Quark™XPress 4.1 using Adobe's ITC Garamond font. Alicia Cech and David Futato designed the interior layout based on a series design by Nancy Priest. Mike Sierra implemented the design in FrameMaker 5.5.6. The text and heading fonts are ITC Garamond Light and Garamond Book; the code font is Constant Willison. The illustrations that appear in the book were produced by Robert Romano using Macromedia FreeHand 8 and Adobe Photoshop 5. This colophon was written by Nicole Arigo.
page 149
Learning WML & WMLScript
An Interview with Martin Frost Ever wonder what your Web page looks like on a cell phone? Delivering data applications and Internet content to mobile devices is one of the hot spots on the technological landscape right now. One reason this technology is taking off is because all of the significant industry players joined together to back a common standard for mobile data, the Wireless Application Protocol (WAP). Included in the WAP specification are the Wireless Markup Language (WML), and the WMLScript scripting language, which serve analogous functions to the Web's HTML and JavaScript. As predictions concerning mobile Internet use continue to skyrocket (like a recent Cahners In-Stat study [www.instat.com/pr/2000/md0003md_pr.htm] that promises 1.3 billion wireless data users by 2004), opportunities in developing wireless content will grow rapidly. Now is a great time to become familiar with the tools being used to craft the wireless Web. Martin Frost is the author of Learning WML and WMLScript, a new book that describes the markup and clientside scripting languages used for delivering content to wireless devices. Martin is the head of WAP technology at Digital Mobility Ltd. [www.digimob.com] in London, and has been working with WAP since 1998. Writer Bruce Stewart talked to Martin about the book, WML and WMLScript, and the future of the WAP model. Stewart: Why don't we start with an explanation of what the Wireless Application Protocol (WAP) is and why it was created. Frost: WAP is a standard for creating applications to run on wireless devices, such as cell phones and PDAs. It was created to work around the limitations of these devices, especially the very small screens and the limited bandwidth available for downloading content. Stewart: How do WML and WMLScript fit in to the WAP model? Frost: To make it easier for developers to learn the WAP standards, they are based on a model very similar to the Web, which uses HTML to create pages of formatted text, and JavaScript to add dynamic features. WML is WAP's equivalent of HTML. It allows text to be marked up with paragraphs, hyperlinks, text input boxes, and so on, but in a way that optimizes the content for small screen sizes. Similarly, WMLScript replaces JavaScript in the WAP world. It allows simple client-side checking of input, but is much simpler than JavaScript and is considerably less demanding on the device. Stewart: WML appears to be pretty closely related to HTML, so experienced Web developers should be able to make the jump to WML without a steep learning curve. What are the biggest differences between the two markup languages, and are there any WML concepts that experienced HTML coders should pay particular attention to when learning WML? Frost: One important difference is that WML is based on XML, which means that much of the syntax is a lot stricter than HTML. For example, all tag names in WML are case-sensitive, whereas HTML allows any case. Another effect of XML is that empty-element tags, which are tags that don't have an end tag, must be written with an extra slash like:
whereas in HTML this would look the same as a start tag
A lot of HTML contains syntax errors that are ignored by Web browsers, but will cause problems for WAP browsers. Many people forget the quotes around attribute values and miss the semicolons off the ends of entities, and both of these mistakes will cause the file to be rejected by most WAP browsers, even though Web browsers will attempt to ignore the error.
page 150
Learning WML & WMLScript WML also includes several new features that aren't found in HTML, most notably in its support for interaction. HTML evolved over some time to include new features: interaction was initially limited to just hyperlinks, then Netscape added forms with checkboxes, text input and so on, and JavaScript was added later still. WML has a different way of approaching these things, which is more elegant and consistent but may take some getting used to. This new approach is discussed in detail in my book, Learning WML and WMLScript. Stewart: Could you elaborate a little on WML's support for interaction, and how it's different from the Web model? Frost: On a Web page, you've got hyperlinks and form-submit buttons, but these each have different limitations and look different onscreen. In WML, the control is separated from its action, so there is a thing called a "task". This is simply an action to be performed by the browser, such as going to a new place, running some WMLScript, and so on. This task is then linked to the actual control--the task is just another tag, so it's placed inside the control. This means that you can have a hyperlink which does a POST, a button which runs some WMLScript, and you can also link these tasks to other things like a timer that goes off after a certain amount of inactivity, a particular option being selected from a list, and so on. It all just helps to make these things more consistent. You learn how to write tasks once and then it works in all these places. Stewart: Please explain the "deck of cards" metaphor that WML uses? Frost: A Web page is basically a continuous stream of content. You can put labels into it and jump to particular places, but all you are doing is scrolling to fixed places in the stream. WML treats its files as analogous to a stack of cards, each of which has separate content. Instead of a label merely referring to an offset in a continuous stream, the label names a card. There is no way to get from one card to another simply by scrolling--there must be an explicit link to a card. The idea was to minimize the need for scrolling by keeping the amount of information on a card small and presenting information on a sequence of separate cards. In practice, most programmers don't use this feature as much as they maybe should. Stewart: Your forthcoming book, Learning WML and WMLScript, points out that many of the current WAP browser implementations are incomplete. What WML or WMLScript features should be specifically avoided by developers who want their WAP applications to work on as many devices as possible? Frost: It depends on what you mean by work. Some features, such as tables and image alignments, are supported only by a select few WAP browsers, but usually won't actually break anything seriously if they are used. The display may look wrong, but it may still be usable. A few months ago I would have recommended not using WMLScript at all, but the situation has improved enormously. A number of browsers have trouble with some standard library functions, but it seems that the test suite is gradually doing its job and weeding out the bad implementations. The main thing to bear in mind is that you should avoid relying on the letter of the specification for things like boundary cases in libraries until the browsers get more mature. Stewart: What is the test suite, and how does that process work? Frost: The test suite is used for two things. While a WAP browser is being developed, it can be tested regularly against parts of the test suite to find any bugs in it. Once it's ready for release, the whole test suite is run, and this is used by the certification process to ensure that the browser really is compatible with the standards. The latest WAP test suite can be found at www.opengroup.org/vswap1.1.4/
page 151
Learning WML & WMLScript Stewart: A lot of attention has been given in the technical press to an insecurity in current WAP gateways that requires encrypted data to be briefly decrypted at the gateway as it gets translated from TLS to WTLS, or vice versa. Is this really an important concern, and why or why not? Frost: It really depends on who you are. If you trust whoever's running the gateway, it's not a problem. Most security experts are very paranoid--it comes with the territory. They are also invariably perfectionists, and the idea of having this extra point of weakness is not something they are happy with. They are interested in designing systems where you don't have to trust anyone, because even a respectable company can be forced in court or by a government to reveal private information, and the gateway may be vulnerable to a cracker. The other main area of concern is from banks and other financial institutions, since the main real reason for WTLS is to allow mobile financial transactions. Most banks don't really understand computer security-if they did, they wouldn't pay so much to all the self-proclaimed experts. They do, however, have very strict procedures about what risks are and aren't acceptable. Their rules say that the private data must not be accessed by any outside party, so they don't like the gateway operator having this information in the clear, even if it's only buried deep in the guts of the gateway software. Stewart: Are you comfortable transferring personal data over WTLS? Frost: I wouldn't use WTLS to send anything actually incriminating, anything that could cause me real trouble if it was decrypted, just because I wouldn't want to trust anyone for things like that. I'd be as happy to use it for sending my credit card number as I would be to send that number to a Web site using HTTPS. The situation is actually very similar: If I buy something from a Web site, my credit card number is transmitted to that site, where it is decrypted and stored. It must then be reencrypted to send to the credit card clearing company, so there is still a third party involved. Stewart: The most recent release of WAP supposedly resolves this security issue (the June 2000 Conformance Release [www.wapforum.org/what/technical.htm]), but realistically how long will it take for us to see widespread implementation of this new version? Frost: It will depend on how much pressure there is to adopt it fast. All the companies involved with WAP are trying to get exciting content out there as fast as possible. That has to take priority over a negligible increase in security which no one will ever notice. If there is serious pressure from banks or someone, the companies will have to prioritize things differently. Stewart: I noticed in your biographical information that you have written a WAP gateway. Was this difficult? And why write your own instead of using one of the existing gateway products? Frost: Writing a WAP gateway isn't too hard. There are some problems with the specifications containing errors, and there are some parts where implementing the specification literally can cause problems, but it's more an engineering exercise than anything else. Most of the techniques are fairly standard for using in any high-performance networking system. Studying the design of a well-written TCP stack or something similar will give you most of the clues you need. As to why we wrote our own, we needed the gateway to integrate tightly with the company's proprietary application server architecture because we wanted to provide a seamless user experience, with the ability to reconnect later and pick up where you left off, and so on. Another consideration was that we wanted access to the source so that we could fix problems quickly, rather than having to put customers off with, "Sorry, but our gateway supplier hasn't sent us the patch yet." At the time we started on the project, the open source gateway wasn't really in a usable state. We considered it, but decided that we could do a better job ourselves. Stewart: What percentage of portable net-enabled devices do you think currently use WAP (vs. other protocols), and how do you expect that number will change over the next two years?
page 152
Learning WML & WMLScript Frost: Most high-end PDAs already support normal Web browsing, and that will always stay. Most current PDAs either have WAP as an option or the supplier is working on it. So this fraction will increase. The situation is different with cell phones. In Europe, there is at least one phone from every major manufacturer with WAP, and many manufacturers are working on retrofitting WAP into the older models that they plan to continue. In the U.S., there are still cell phones available using Phone.com's proprietary HDML system, and this has held back the adoption of WAP. The fragmented nature of the U.S. telecom market doesn't help much, either. There are many different systems, and still even some analog networks! All of Europe uses GSM, which means that there is only one standard for phone manufacturers to contend with, and only one version of the phone software that has to have WAP integrated into it. These problems mean that WAP will take longer to take off in the U.S. As to actual percentages, I really can't comment. Various people have quoted widely varying statistics on adoption, and I prefer to leave making quantitative judgments to the statisticians! Stewart: Fair enough. Do you think NTT DoCoMo's i-Mode, probably the most popular alternative to WAP, will ever be successful outside of Japan? Frost: In its current form, no. i-Mode is quite closely tied into DoCoMo's network. It uses data capabilities only found on that network. I also think that other operators would be unwilling to embrace i-Mode wholeheartedly and thereby give a large amount of power and influence to a single company. The advantage of WAP is that the specifications [www.wapforum.org/what/technical.htm] are published by the WAP Forum [www.wapforum.org], a body which anyone can join - although there is quite a steep joining fee. A number of companies have made loud public statements that WAP is dead and i-Mode is the future, but I think most of them are just desperately flailing around, trying to regain the initiative. The amount of investment that has been put into WAP gives it a huge head start on any other system for now. Finally, i-Mode really isn't all that special. It uses normal HTML and sound and image files. Apart from the details of the actual over-the-air communication, the only new part is the compressed form of HTML that they use. WAP has an equivalent to this that works for other XML documents, as well. There are some useful lessons to be learned from i-Mode about the sorts of applications that are useful and successful in a wireless environment, but most of these lessons are applicable to pretty much any system, including WAP. Stewart: What do you think the future holds for WAP and WML? As bandwidths increase, do you think WAP will continue to evolve or eventually be superceded by another wireless technology? Frost: Higher bandwidth will not kill WAP, it will simply enable richer content and a better user experience. It may well be the case that some parts of WAP, like the special communications protocols optimized for low bandwidth, will become redundant and can be replaced by regular HTTP. The future for WML is more interesting. The WAP Forum has announced that the next-generation of WAP will be based around XHTML, which is the W3C's appointed successor to HTML, and based on XML in the same way that WML is. However, this is still a long way off. In addition, WML will continue to have a place in cell phones for some time, even once XHTML starts being used. The fact that WML is optimized for small screens means that it will continue to perform better than alternatives, even with lots of bandwidth. Even if it's possible to get a phone with a multimegabit link, many people will still want small phones, because of their convenience. Just think of the people you know with cell phones now. Even though there are phones available with big screens, how many people use them compared to the smaller, more convenient ones? XHTML content designed for big color screens will come out poorly on these devices, but WML works just fine!
page 153
Learning WML & WMLScript WML and WMLScript Tips & Tricks WAP (Wireless Application Protocol) is the de facto standard for creating applications that run on cell phones and other wireless devices. WML and WMLScript are the two languages used to write these applications. Here are some tips to help you write WAP content. Some of these are quite general, and some are quite detailed and technical, but I hope you'll find all of them useful. 1.
Check your content on different browsers. Most of the current WAP browsers suffer from bugs and incompatibilities with the published specifications. This problem is particularly severe when things should work according to the specifications but fail mysteriously on a particular browser. (This situation will get better with time; there is now an official test suite available and a certification program. But until both are widely adopted, incompatibility remains a serious problem.) This WAP browser incompatibility means that, for the time being, you should test your WAP applications on as many different devices as possible. Don't assume that some technique you've used will work everywhere just because it works on one browser. Try it out on different devices, preferably on one from a different manufacturer.
2.
Check it on different screens. Don't write your applications for one device and assume that everyone else has the same screen size. There are few things more irritating than having a nice new PDA with a big screen and having four words of text on each page. On the other hand, be aware that putting long essays onto WAP sites will cut out the huge portion of your audience accessing your site via a cell phone. If you have content that will benefit from a big screen, consider making two versions of your site: one with lots of small files for cell-phone users and one with a few big files for PDA users. Things like news stories and sports reports really benefit from this sort of treatment. Also, don't rely on a screen's width to be a particular dimension. Some sites lay out tabulated information by relying on a particular cell phone to put line breaks in the right places. This type of layout is completely unreadable on most other cell phones, let alone PDA browsers.
3.
Provide alternatives to timers. Many WAP sites use WML's timer facilities to display logos and splash screens before the main content loads. Very few sites provide any alternate means of entering the main page if the timer does not work as expected. If no alternative is provided, the user will be stranded on a page with no way to go forward or back. (Unsurprisingly, users find this a frustrating experience.) The most common reason for a timer to fail is a name attribute on the timer referencing a variable that isn't initialized properly somewhere else. This works fine the first time, since the default value is used, but later visits to the same page will use the value "0" for the timer, which disables it. To be on the safe side, always provide a <do> or element to perform the same action as the timer. This also improves the user's experience, since he or she can skip past the timed page, if the time-out is long.
4.
Remember to use entities. A surprisingly common mistake that even experienced WAP developers make from time to time is to forget to use character entities when writing characters like "&" and "