Buy this Book
Print Book $59.99 PDF $41.99 Read it Now!
Print Book £42.50
Add to UK Cart
Reprint Licensing

Programming Firefox
Programming Firefox Building Rich Internet Applications with XUL

By Kenneth C. Feldt
Book Price: $59.99 USD
£42.50 GBP
PDF Price: $41.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Firefox and Friends
The Firefox browser is a collection of C++ libraries designed to be assembled into any number of applications that you can run on machines with any of the major desktop operating systems (Windows, OS X, Linux, etc.).
A browser's functionality combines what the user sees—through web content—and underlying technologies used to access information and to decode, render, and stylize content. Although much of this book focuses on the XUL interface language to build application interfaces, it also touches on the evolving Internet standards that extend the breadth and depth of information available through the Web.
Most people say the World Wide Web was "born" in the spring of 1993, when Jon Mittelhauser and Marc Andreesen, working out of the University of Illinois, developed what would become the first widely acceptable graphical interface to the Internet.
The software was known as Mosaic, and its widespread acceptance provided the first indication that the Internet was something that could interest (and provide value to) business users and the public.
Marc Andreesen went on to start Netscape Communications Corporation, a company that focused on the commercialization of the Netscape Navigator browser. In 1998, Netscape turned development of the browser over to the open source community in the form of the Mozilla Organization. The Mozilla community rewrote the Netscape code base and released the first commercial product in the form of Netscape 6.
The browser was, unfortunately for Netscape, technically and commercially disappointing. Netscape continued to support Mozilla-based browsers through 2003, when America Online (which owned Netscape) shut down operations, leaving the Mozilla organization on its own to continue development and commercialization of the browser code.
The Mozilla browser was actually a suite of applications that incorporated both a browser and an email and newsreader client. To reduce the perceived "bloat" of the suite, Mozilla decided to break the browser portion out of the suite.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Mozilla to Firefox and Thunderbird
Most people say the World Wide Web was "born" in the spring of 1993, when Jon Mittelhauser and Marc Andreesen, working out of the University of Illinois, developed what would become the first widely acceptable graphical interface to the Internet.
The software was known as Mosaic, and its widespread acceptance provided the first indication that the Internet was something that could interest (and provide value to) business users and the public.
Marc Andreesen went on to start Netscape Communications Corporation, a company that focused on the commercialization of the Netscape Navigator browser. In 1998, Netscape turned development of the browser over to the open source community in the form of the Mozilla Organization. The Mozilla community rewrote the Netscape code base and released the first commercial product in the form of Netscape 6.
The browser was, unfortunately for Netscape, technically and commercially disappointing. Netscape continued to support Mozilla-based browsers through 2003, when America Online (which owned Netscape) shut down operations, leaving the Mozilla organization on its own to continue development and commercialization of the browser code.
The Mozilla browser was actually a suite of applications that incorporated both a browser and an email and newsreader client. To reduce the perceived "bloat" of the suite, Mozilla decided to break the browser portion out of the suite.
The initial browser was referred to as Phoenix, was renamed Firebird, and finally was released as Firefox version 1.0 in November 2004.
Today the Mozilla Foundation operates as a nonprofit organization to manage the open source development aspects of the program. The foundation owns the for-profit Mozilla Corporation, which focuses on browser support for end users and commercialization programs.
The Mozilla code base now supports the Firefox browser, the Thunderbird email client (), and the Camino browser for OS X. The complete application suite (formerly the Mozilla suite) is now branded as the SeaMonkey Internet application suite. All the browser engines implement the same rendering logic (the code that paints the screen web content), known as the Gecko rendering engine. The Mozilla suite offers tools to allow developers to embed the Gecko engine alone in customized applications.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
XML Technologies
As I just mentioned, XUL stands for XML User Interface Language. In fact, many of the key technologies discussed here are based on XML, or the Extensible Markup Language. As the XML form so dominates both the interface design and the structure of displayed documents, it makes sense to consider what XML is, why it is so important, and what impact it has on electronic document structure.
XML has its roots in the Standard Generalized Markup Language (SGML). SGML was developed out of a 1960s IBM project to develop documents whose content could be machine-readable. SGML was a metalanguage, a self-describing form that allowed document contents to describe how it was encoded, facilitating machine-driven typographic processes and, eventually, decoding and cataloging.
But SGML was very complex, and with the advent of the "GUI-friendly" Web, work was initiated to carry over some of SGML's advantages of portability to Internet-rendered documents.
In 1995, work began under the auspices of the World Wide Web Consortium (W3C), and XML version 1.0 became a consortium recommendation in February 1998.
XML's power lies in a simple tree structure of text fields, and the capability to define document types that enable decoders to interpret text fields in different ways. The tree structure means that any software accessing a well-formed XML file "knows" how to traverse the contents, which themselves are a feature of some utility.
But more exciting is the capability of an XML document to include a document type reference that adds a context to the tree elements, giving meaning to the document's content. For example, an XML document type can define a row as a horizontal alignment of text, but a different document type can define a row as a portion of a mathematical formula. That context can be used to direct the document renderer to display graphics tables or math formulas.
XUL ("zool") files are themselves XML documents. A document namespace field instructs the browser logic that the XUL content is to be interpreted and painted according to a XUL document type. The Firefox framework is "smart" enough so that if other portions of the document need to be drawn as HTML elements, a namespace prefix can be attached to those elements to "switch" the rendering into HTML mode. Designers no longer need to build one monolithic GUI file structure—different display types can now be constructed and mixed together to extend the widget vocabulary.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
At the Top of It All: The DOM
The Document Object Model (DOM) represents a programmatic interface to web page content. The DOM model is used to define how any XML document may be accessed and manipulated by software.
Early HTML allowed scripting languages limited access to page elements. Scripts could access HTML elements by name or by an element's position within an HTML form. Programmers used this access to manipulate the interface on the basis of the correctness of an entry or to otherwise manipulate the interface based on the input values.
In 1998, the development community recast the HTML 4.0 specification into an XML syntax. This combination of HTML and XML, in the form of XHTML, meant that web documents could now be accessed through the DOM interface. This XHTML document model goes far beyond simple access to basic forms or HTML elements by name. The XHTML DOM makes public a document interface to allow scripts to access the entire document content as a tree of nodes, each node representing a part of the document. Developers use the DOM specification to traverse the document tree, to access and modify element attributes, and to dynamically modify element styles.
Scripts can also dissect the entire document structure, adding event listeners to all elements of a given class, inserting interface widgets as a specific position in the interface tree, moving elements around the tree, accessing document content, and even removing page elements under program control.
DOM access is the lynchpin to most modern web applications that employ JavaScript to manipulate the user interface. Many of the functions behind Firefox's more complicated XUL widgets use JavaScript that accesses elements through DOM methods.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Mixing Document Types
One of the most underutilized features of the Firefox framework is the ability to render XML documents of different types—that is, XML documents that may represent HTML along with content representing mathematics (MathML) and Scalable Vector Graphics (SVG).
The preceding section described how you can define different document types. The Firefox framework can render most of those types without the need for an external plug-in. shows an example of MathML (the XML rendering of mathematics).
Figure 1-2: Firefox and W3C MathML test page
The capability of Firefox to render such content without the need for plug-ins should not be understated. Once a plug-in is used to render specialized content, additional scripting complexity is added if the designer wishes to "connect" the logic of a web page with the specialized content (e.g., a page that includes an XHTML table full of data and an SVG graphic controlled by the same code). The capability to manage such content makes the Firefox engine a good candidate for simpler, cleaner code to extend interface interactivity.
A number of XML document types exist that promise to bring additional innovation to the Web. Time will tell whether the content development community can take advantage of the delivery platform that Firefox offers:
  • XHTML
  • SVG
  • Geography Markup Language (GML)
  • MusicXML
  • RSS
  • Chemical Markup Language (CML)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Started
The development tools required for XUL development (and to experiment with the examples in this book) are relatively modest.
A good text editor is essential—the editor included with most development systems is more than adequate. If you don't want to shell out the cash for a full-fledged development system, you still have inexpensive options.
OS X platforms use the XCode developer tools that come with the Mac OS X distributions; users can also subscribe to the Apple Developer Connection to get a copy of the tools.
For the Windows platform, plenty of options are available. One of the most serviceable of such tools is the Notepad++ application from the SourceForge project. Regardless of your preferences, all you really need is an editor with syntax highlighting and syntax folding, the features that allow highlighting of keywords and of code segments bracketed by braces and parentheses, as shown in .
On Unix platforms, you have a wide range of usable editors from which to choose—from vim and emacs to more user-friendly tools such as Anjuta and KDevelop. It is also possible to use the Eclipse cross-platform development environment for the exercises in this book.
Figure 1-3: Notepad++
A number of chapters demonstrate how to integrate XUL applications with server code. Developers may want to implement similar functionality on their machines by installing their own servers.

Section 1.5.1.1: Apache web server

The web server of choice is the Apache web server (). This book uses Apache 2.0 for the PC and Apache 1.3 as bundled with OS X distributions. You should not encounter any compatibility issues with later versions of Apache, the only requirement being its integration with PHP.

Section 1.5.1.2: PHP

The scripting language used in this book is Personal Hypertext Processor (PHP). Although PHP is most often used to mix HTML with programmatic logic on the server, we will use it more often to serve as frontend logic that bridges requests from the XUL-based client and the database engine. PHP 4 or PHP 5 are more than adequate for the examples in this book. The executables are available from .
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: XUL Basics
The XML User Interface language, XUL, is a document format and vocabulary used to describe cross-platform user interfaces that the Firefox engine renders.
HTML and XHTML (HTML's XML-compliant kin) are used to build web pages—combinations of text, images, and multimedia, with interactivity built in by adding JavaScript event handlers to interface elements or server scripts acting on client-provided forms. XUL interface elements, or widgets, are designed to wrap interactivity around web pages. The Firefox browser itself is a collection of XUL buttons, frames, and menus defined by XUL source. The Gecko rendering engine is the drawing logic that displays all XUL interfaces.
This chapter provides an introduction and basic overview of XUL interfaces (most of these elements will be discussed in greater detail later in this book), including:
  • The structure of a XUL file
  • Introduction to the box model
  • Setting dimensions and positioning
  • Simple interface elements (buttons, labels, text)
  • Menus and toolbar buttons
  • Containers (group boxes, tab boxes)
  • Content display
  • Utility widgets
XML files may include the XML preamble that identifies the file type:
<?xml version="1.0"?>
As XML files, XUL interfaces must be well formed—that is, the elements must have opening and closing tags.
In the case of XUL windows, the root element must be a window:
<window>
    ... some children
</window>
The term element refers to the basic unit of a XUL document. Elements are represented via their tags, or terms surrounded by angle brackets (<>). Each opening tag (<tag>) must include a closing or terminating tag (</tag>). Elements enclosed by an opening and closing tag are said to be children of the tag.
XML elements often have attributes that are of the form attributeName=attributeValue and are declared within the element's opening tag. In the case of a XUL window, attributes must be defined to set the window's height and width:
height="heightInPixels"
width="widthInPixels"
Other common attributes for the window include an id
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
File Structure
XML files may include the XML preamble that identifies the file type:
<?xml version="1.0"?>
As XML files, XUL interfaces must be well formed—that is, the elements must have opening and closing tags.
In the case of XUL windows, the root element must be a window:
<window>
    ... some children
</window>
The term element refers to the basic unit of a XUL document. Elements are represented via their tags, or terms surrounded by angle brackets (<>). Each opening tag (<tag>) must include a closing or terminating tag (</tag>). Elements enclosed by an opening and closing tag are said to be children of the tag.
XML elements often have attributes that are of the form attributeName=attributeValue and are declared within the element's opening tag. In the case of a XUL window, attributes must be defined to set the window's height and width:
height="heightInPixels"
width="widthInPixels"
Other common attributes for the window include an id (used when JavaScript scripts need to get a reference to the window), title (for interface display), and orient (to set the initial layout direction of children).
The final critical attribute for the topmost node is the xmlns attribute, which defines the namespace to be used within the document.
XML documents are meant to be extensible, or able to incorporate different types of elements depending on what information is to be encoded in the document. XHTML documents have elements that represent HTML document elements such as body, head, div, and others.
But as mentioned in , you can use different types of documents to represent mathematical relationships, graphics, or chemical structures. It is quite possible that these different document types may use an element tag that another document type uses as well. The xmlns namespace declaration is a mechanism for defining what namespace a specific element belongs to, providing the browser engine with a pointer or reference to a dictionary that describes the required structure of a tag.
As an example, the following code sets the default namespace for all tags that are not prefixed:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
XUL Widgets
XUL widgets are at the heart of building Firefox applications.
The XUL layout hierarchy is based on a primitive <box> container—all XUL interfaces are a collection of nested boxes that contain any number of other boxes. Most developers will use two box subclasses: a <vbox> that lays out child elements in a vertical alignment, and an <hbox> that presents children in a horizontal alignment.
A designer can control how a box positions child content by using the orient attribute: a value of horizontal will result in a box's children being placed along a horizontal axis and a value of vertical will result in content being placed along the vertical axis. The Firefox framework supports <vbox> and <hbox> elements as a shortcut alternative to using the orient attribute.
For our first test, we will combine our boxes with the simple XUL label element. Adding child elements to the different forms of boxes illustrates the difference in how vboxes and hboxes work:
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window
    id="theWindow"
    title="The Window"
    orient="horizontal"
    width = "400"
    height = "300"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
    xmlns:html="http://www.w3.org/1999/xhtml"
    >

  <hbox>
   <label value="label 1"/>
    <label value="label 2"/>
     <label value="label 3"/>
  </hbox>
   <vbox>
   <label value="label 4"/>
    <label value="label 5"/>
     <label value="label 6"/>
  </vbox>
</window>
The resulting window now illustrates the difference, as shown in .
Figure 2-2: hbox and vbox layouts
One technique to use when learning (and when debugging advanced designs) is to create a specialized appearance, or style, that is associated with a class of elements being tested. By setting distinctive colors and borders, it is sometimes easier to spot problems with a design.
The style assignment follows the CSS style:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introducing Input Controls
Controls represent the user interface widgets responsible for fielding interaction with the user. Buttons, text fields, text areas, and various forms of menus provide the lion's share of control logic.
Labels provide the designer with the simplest of all interface elements—a string of displayed text:
<label value="My Label"/>
Buttons represent the basic interaction tool. Buttons are painted using the native operating system's GUI, resulting in an interface that looks much more like a desktop application than a browser.
Buttons allow you to add an image icon, using attributes that enable you to control the button's appearance:
label
The text appearing on the button.
image
The URI of an image to appear as an icon on the button.
dir
Sets the position of the icon relative to the label:
normal (default)
The icon appears to the left of or above the button label.
reverse
The icon appears to the right of or below the button label.
orient
Determines the layout of the label and the icon:
horizontal (default)
The icon and label are oriented horizontally.
vertical
The icon and label are oriented vertically.
illustrates the effects of altering the attributes for a button.
Figure 2-9: Buttons with an icon
All text entry is conducted through the textbox element. The default nature of a textbox is to support a one-line entry, but several attributes affect the nature of the entry area:
maxlength
The maximum number of characters allowed in the text box for single-line text entry.
multiline
If true, pressing Enter during text entry forces a new line entry; otherwise, all text is combined in a single text line.
rows
The number of rows displayed for a multiline text entry area.
size
The total number of characters displayed within a single-line text entry box.
wrap
Turns word wrapping on or off; a value of off disables word wrapping.
Developers use a single-line text area when the size of text will be limited for data fields, and they use a multiline text area for a general-purpose "narrative" entry. The actual number of vertical and horizontal rows visible in the text box may also depend on the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
More Complex Containers
Vertical presentations of selection options are made possible by lists (for simple collections) and trees (for hierarchical relationships).
In its simplest form, a list is merely a listbox container with listitem children. Listitems display the contents of the label attribute, but they also support a value attribute that scripts use to obtain some data that the designer chooses not to be rendered in the interface.
You also can divide listboxes into multiple columns in a fashion very similar to that of the HTML table element. For multiple-column lists, the first child of a listbox is a <listhead> element that contains one <listheader> child for each column to be displayed with a header. Following the <listheader> child is the <listcols> entry with one child for each column to be displayed.
Finally come the <listitem> children, but unlike the simplest single-column implementation (and similar to the table layout), multicolumn list items contain <listcell> children that are rendered in the columns. An example of multicolumn lists is shown in the following code fragment and in :
<hbox flex="1"  class="test_b">
<listbox>
  <listhead>
    <listheader label="Column 1"/>
    <listheader label="Column 2"/>
    <listheader label="Column 3"/>

  </listhead>

  <listcols>
    <listcol/>
    <listcol/>
    <listcol flex="1"/>
  </listcols>
  <listitem>
    <listcell label="R1C1"/>
    <listcell label="R1C2"/>
     <listcell label="R1C3"/>
  </listitem>
  <listitem>
    <listcell label="R2C1"/>
    <listcell label="R2C2"/>
      <listcell label="R2C3"/>

  </listitem>
  <listitem>
    <listcell label="R3C1"/>
    <listcell label="R3C2"/>
    <listcell label="R2C3"/>

  </listitem>
   <listitem>
    <listcell label="R4C1"/>
    <listcell label="R4C2"/>
    <listcell label="R4C3"/>

  </listitem>
</listbox>
</hbox>
Figure 2-12: Multicolumn list
A more complicated interface that makes possible a hierarchical representation is the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Managing the Display Space
Firefox includes a number of widgets that help organize controls and labels as they appear in a window.
Most applications require some interface element to set a context for a collection of commands. The XUL <tabbox> element provides a family of containers that represent the tabbed-index collection of panels.
Each <tabbox> element starts with a <tabs> element, whose <tab> children represent the buttons attached to their respective content panels.
The main content of a tab box is wrapped by the <tabpanels> element, which contains <tabpanel> children. The tab panels are the topmost container for the interface widgets bound to the tab. The following code and illustrate the use of a tab box:
<tabbox flex="1">
  <tabs>
    <tab label="Sports"/>
    <tab label="News"/>
     <tab label="Weather"/>
      <tab label="Entertainment"/>
  </tabs>

  <tabpanels flex="1">
    <tabpanel id="sports">
     <vbox flex="1">
      <label value="Sports"/>
     </vbox>
    </tabpanel>
     <tabpanel id="news">
     <vbox flex="1">
      <label value="News"/>
     </vbox>
    </tabpanel>
     <tabpanel id="Weather">
     <vbox flex="1">
      <label value="Weather"/>
     </vbox>
    </tabpanel>
     <tabpanel id="Entertainment">
     <vbox flex="1">
      <label value="Entertainment"/>
     </vbox>
    </tabpanel>
  </tabpanels>

</tabbox>
Figure 2-17: Tab box
The use of the flex attribute can significantly affect the appearance of tab boxes.
Adjusting the flex attribute on the <tabbox> affects the amount of horizontal space the tab box occupies; setting the flex attribute on the <tabpanels> element changes the amount of vertical space the entire box occupies.
Now that we've discussed flexing, it's time to discuss the widget used to reallocate space, or split the content area into different sections. Splitters placed in <hbox> elements divide the area into vertical segments. Splitters in
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Content Display Panels
You use content panels to display web pages. The src of a content panel points to a web page through a URL. The three basic types of content panels are iframes (generally used when the interface is managing user navigation through heavy use of scripting), browser (used to provide additional navigational features), and tabbrowser (a browser embedded within a tabbox). The following code shows how to add an iframe element within a tabpanel, and shows the result:
<tabpanel class="test_a" id="news">
 <vbox  >
   <label value="News"/>
  </vbox>
 </tabpanel>
 <tabpanel id="Weather">
  <iframe flex="1" src="http://www.weather.com/"/>
 </tabpanel>
 <tabpanel id="Entertainment">
  <vbox flex="1">
   <label value="Entertainment"/>
  </vbox>
 </tabpanel>
Figure 2-19: Addition of an iframe
Remember to set the flex attribute on the iframe element. Omitting this step can result in very tiny slices of a web page being displayed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Miscellaneous Widgets
In addition to simple container boxes and controls, most XUL programmers enhance their applications by using a number of widgets that provide both layout services and useful programming interfaces. Here are some examples:
<spacer>
Sometimes it's not enough to use the flex and pack attributes to organize widgets in the manner desired. Spacer widgets act as invisible "springs." Setting the flex attribute of a spacer allows the designer to push elements to one side of a parent container.
<statusbar>
A status bar is placed along the bottom of a window. A <statusbar> contains a <statuspanel> child, which includes label attributes. Developers can access the label property of a statuspanel to provide feedback to the user:
<statusbar pack="end">
  <statusbarpanel label="Still waiting...."/>
</statusbar>
<progressmeter>
This widget displays an operating-system-specific progress meter. A value attribute represents an integer percentage of completion. When the mode attribute is set to determined, the meter changes to show the percentage of completion. When the mode attribute is set to undetermined, the meter displays a graphic to indicate ongoing activity. Developers use the determined mode when an activity consists of known steps of completion and they want to indicate task progression. They use the undetermined mode to indicate an ongoing task.
<description>
Whereas you can use label fields to display short lines of text, you can use a <description> element to display longer segments of text. The contents will wrap as the enclosing box changes size.
Here is an example of code that displays information and the status of an activity at the bottom of our window:
<description style="color:gray;">
We are currently processing your order. Please do not press
  any buttons unless you are really tired of waiting.
</description>

<statusbar >
  <progressmeter mode="undetermined" />
  <spacer flex="1"/>
  <statusbarpanel label="Still waiting...."/>
</statusbar>
...
shows the results.
Figure 2-20:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Helper Features
A number of additional features help designers deliver flexible interfaces that are more intuitive and user-friendly.
XUL labels provide a control attribute that supports a binding to GUI controls to specify which control receives focus when the label is clicked. Setting the value of the control attribute of a label will result in shifting input focus to the control with the matching id attribute.
The tabindex provides the same functionality available in most interface models that allow the user to quickly traverse through a series of text entry and control fields:
tabindex="someIndex"
Higher indices define the order of the next focused text entry area when the Tab key is pressed. Radio box elements should have a tabindex set to the first element of the box.
Implementation of tabindex is operating-system-specific. Windows platforms traverse focus to include buttons and checkboxes; OS X implementations may send focus only to text entry fields depending on a control panel setting.
The following source file illustrates the addition of the control attribute and tabindex to several fields. and illustrate the differences between Windows and OS X implementations.
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<?xml-stylesheet href="data:text/css,
      .test_a {
        background-color: #808080;
        border-color:black;
        border-style:dashed;
        border-width: thin;
        }

     .test_b {
        background-color: #c0c0c0;
        border-color:black;
        border-style:solid;
        border-width: thin;
        }

 type="text/css"?>

<window
    id="theWindow"
    title="The Window"
    orient="horizontal"
    width = "400"
    height = "300"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
    xmlns:html="http://www.w3.org/1999/xhtml"
    >

 <vbox flex="1">

<vbox>
<hbox>
<groupbox  flex="1">
  <caption>
   <label value="Please send me info:"/>
  </caption>
 <hbox>
    <label control="cmt" value="Comments:"/>
    <textbox tabindex="1" id="cmt" flex="1"/>
 </hbox>
  <checkbox   tabindex="2" label="Touring in the British Isles"/>
   <checkbox   tabindex="3"  label="Cycling in France"/>
    <checkbox   tabindex="4" label="Skiing in Switzerland"/>
 </groupbox>

<radiogroup pack="center" >
 <radio  tabindex="5"  label="Option 1"/>
 <radio  label="Option 2"/>
 <radio  label="Option 3"/>
</radiogroup>
</hbox>

<grid class="test_b" flex="1">
<columns>
 <column/>
 <column flex="1"/>
</columns>

  <rows>
    <row>
     <label control="Nm" value="Name:"/>
     <textbox tabindex="6" id="Nm"/>
    </row>

     <row>
     <label control="Addr" value="Address:"/>
     <textbox tabindex="7" id="Addr" />
    </row>

     <row>
     <label control="Ph" value="Phone:"/>
     <textbox tabindex="8"  id="Ph" />
    </row>

     <hbox pack="center">
     <button  tabindex="9" label="Send" />
    </hbox>
  </rows>
</grid>
 </vbox>
</vbox>

</window>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Mozilla Style Declarations
The Firefox framework extends the CSS specification to support the enhanced styling of elements. (We will provide a more thorough discussion of CSS pseudoclasses and properties in and .)
Familiar CSS notation to style a class of HTML elements looks like this:
tagName : {
 someStyleAttribute: someValue;
someOtherStyleAttribute: someOtherValue;
....
}
This statement directs the rendering engine to assign styling characteristics to document elements that match the tagName (e.g., div elements).
Developers can design an interface that is much richer than those available only through HTML's styling specifications. Not only is there now a richer portfolio of style properties, but the variety of GUI widgets added by the XUL framework also calls for adding functionality to the CSS specification.
The Firefox framework supports Mozilla-enhanced CSS pseudoproperties that allow creation of new styling directives, and pseudoelements that enable the application of "standard" style declarations to customized element declarations.
The use of an extended pseudoproperty looks like this:
hbox.myClass {
 -moz-box-pack:center;
}
In this case, any document hbox elements that have the class attribute set to myClass will have the pack property set to end.
Here we see the value behind such an extension; no existing CSS style for pack works the way XUL designers expect. Use of the pseudoproperties allows the broad assignment of Firefox- (and XUL-) specific styling to interface elements.
In a fashion consistent with conventional stylesheet declarations, should any element be subject to a pseudoproperty declaration and have attribute assignments referencing attributes of the same name, the inline assignment takes precedence.
Pseudoclasses are a way in which the CSS specification supports binding appearances to elements based on their relationship to other document elements. The Firefox framework includes a number of such classes, most of which involve customizing tree appearances.
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
The XUL framework provides a family of interface widgets that look similar to other GUI toolkits.
XUL interfaces are distinct in their use of the XML structure to represent the interface. Using XML to describe interfaces in turn allows the use of industry-standard stylesheets to add a distinctive look and to extend the interface appearance.
The box model used by Firefox generally discourages the use of absolute numbers for positioning or sizing, relying instead on attributes that describe how a box fills its available space and how child elements are to be positioned.
Now that we've covered the basics of how interface files are structured and you've been introduced to the core widget set, we have the tools we need to build XUL applications.
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: Coding and Testing for the Real World
I'll start this chapter with an overview of using JavaScript with a specific XUL application—in particular, I'll discuss how JavaScript objects and the XUL document structure interact to put some machinery behind the interface widgets. I will follow up the development topics with an overview of debugging techniques and services offered by Mozilla.
One effective technique for exploring different elements of an interface is to define a target application that exercises topics of interest. With that in mind, in the next few chapters we'll design an Internet application that allows the user to select portions of a web page and create a text note that cites the page (and selected text).
The application will allow users to do the following:
  • Manually enter a web page for viewing
  • Save the viewed web page into a category of bookmarks
  • Create a note that captures their comments about a topic
  • Cite in a note the text they've selected in the viewed web page
  • Change the font style and size attributes of the note text
  • Export the note text as an HTML document
We will also use custom code to "bookmark" viewed pages, and we will build the application to run as a standalone application. shows a rough sketch of what we will be designing.
Figure 3-1: NewsSearch interface sketch
With this sketch, we can start by building a simple source file that contains our boxes for content.
A first cut at the source file newssearch.xul follows:
<?xml version="1.0"?>
<?xml-stylesheet href="testStyles.css" type="text/css"?>

<window
  id="theMainWindow"
  title="Test Window"
  orient="horizontal"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">


 <!-- main top level container -->
 <hbox flex="1" >

 <!-- a container for some kind of list -->
 <vbox style="background-color:yellow;" flex="2" >
  <description id="tocDescription">
   Table of contents
  </description>
 </vbox>

 <!-- container for content and tool areas -->
 <vbox flex="2" >

 <!-- used to display content -->
 <hbox  style="background-color:green;" flex="3" >
  <description id="msgDescription">
   Content to be displayed
  </description>
 </hbox>

  <!-- used to display typing area  -->
 <hbox style="background-color:blue;" flex="3" >
 <description id="noteDescription">
   Note area
  </description>
 </hbox>

  <!-- used to display tool area-->
 <hbox flex="1" >

  <spacer flex="1"/>

    <vbox>
     <spacer flex="1"/>
      <hbox>
       <button id="B1" label="B1" />
       <button id="B2" label="B2"/>
       <button id="B3" label="B3"/>
       <button label="B4"/>
      </hbox>
      <spacer flex="1"/>
    </vbox>

  <spacer flex="1"/>

 </hbox>

 </vbox>
 <!-- container for messages and tool areas -->

 </hbox>
 <!-- main container -->

</window>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Defining a Target Application
One effective technique for exploring different elements of an interface is to define a target application that exercises topics of interest. With that in mind, in the next few chapters we'll design an Internet application that allows the user to select portions of a web page and create a text note that cites the page (and selected text).
The application will allow users to do the following:
  • Manually enter a web page for viewing
  • Save the viewed web page into a category of bookmarks
  • Create a note that captures their comments about a topic
  • Cite in a note the text they've selected in the viewed web page
  • Change the font style and size attributes of the note text
  • Export the note text as an HTML document
We will also use custom code to "bookmark" viewed pages, and we will build the application to run as a standalone application. shows a rough sketch of what we will be designing.
Figure 3-1: NewsSearch interface sketch
With this sketch, we can start by building a simple source file that contains our boxes for content.
A first cut at the source file newssearch.xul follows:
<?xml version="1.0"?>
<?xml-stylesheet href="testStyles.css" type="text/css"?>

<window
  id="theMainWindow"
  title="Test Window"
  orient="horizontal"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">


 <!-- main top level container -->
 <hbox flex="1" >

 <!-- a container for some kind of list -->
 <vbox style="background-color:yellow;" flex="2" >
  <description id="tocDescription">
   Table of contents
  </description>
 </vbox>

 <!-- container for content and tool areas -->
 <vbox flex="2" >

 <!-- used to display content -->
 <hbox  style="background-color:green;" flex="3" >
  <description id="msgDescription">
   Content to be displayed
  </description>
 </hbox>

  <!-- used to display typing area  -->
 <hbox style="background-color:blue;" flex="3" >
 <description id="noteDescription">
   Note area
  </description>
 </hbox>

  <!-- used to display tool area-->
 <hbox flex="1" >

  <spacer flex="1"/>

    <vbox>
     <spacer flex="1"/>
      <hbox>
       <button id="B1" label="B1" />
       <button id="B2" label="B2"/>
       <button id="B3" label="B3"/>
       <button label="B4"/>
      </hbox>
      <spacer flex="1"/>
    </vbox>

  <spacer flex="1"/>

 </hbox>

 </vbox>
 <!-- container for messages and tool areas -->

 </hbox>
 <!-- main container -->

</window>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adding Logic
So far, we have a main window with a few boxes and buttons. The next step is to attach some type of trigger to an interface widget, and then some software to execute the logic the user expects. To start off, let's assume that our NewsSearch application will require a button to launch a server-based login process. To do that, we will attach a login script to one of our buttons. That script will conduct an initial connection with a server (which we will only simulate in this chapter) to verify a user account. The completion of the process will allow us to display a list of news items that are available for viewing. These requirements lead us to explore the following topics:
  • Attaching logic to widgets that execute some function as a result of user input
  • Developing a script to authenticate a user and modify the interface by changing the contents and appearance of document elements
  • Using the debugger when things don't work
All of these stages in one way or another require an understanding of how XUL, JavaScript, and the Document Object Model (DOM) interact. Although I will provide detailed information about JavaScript, DOM, and XUL in , we need to at least lay the foundation for some basic concepts before we continue.
JavaScript is a language that a browser engine interprets at runtime. There are two broad areas you must understand to use the language effectively: the syntax of the language itself (not a subject of this book), and the interaction of the language with the DOM to which XUL documents adhere.
Any manipulation of an XML structured document relies on the DOM as defined by the World Wide Web Consortium (W3C). The W3C defines several layers of DOM specifications that build upon one another:
DOM Level 1
Level 1 defines the structure of XML documents, including XML-formatted HTML documents (technically referred to as XHTML documents). The core DOM 1 specification provides the initial description of document nodes, how to access them, and how to change the structure of a document by adding and removing nodes from the DOM document tree. Also part of DOM Level 1 is the description of
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Simple Authentication Script
Because we will probably want to provide our NewsSearch service to a limited clientele, we will have to log in and authenticate users.
Our "real" application will involve a server authentication process that passes data from XUL text widgets and is triggered by XUL buttons, but for now, let's just hardcode some fictitious names into the application. We'll focus on the use of some XUL input widgets, and then modify our application to display a nice startup screen welcoming the user. To accomplish those tasks, we will break our work into two phases:
  • Read a username and password from a XUL input field
  • Change one of our display areas to remove the login buttons and generate a new welcome message
We accomplish single-line input through the XUL <textbox> element. Textboxes also have attributes to define password entries and a maximum length attribute.
Now we'll add a couple of text entry areas to the center area of our interface and a few spacers to line things up. The resulting changes in our source file follow:
<!-- used to display message -->
 <hbox   flex="3" >

  <spacer flex="1"/>
  <vbox>  <!-- stack message and login controls vertically -->

    <spacer flex="1"/>
      <description id="msgDescription">
       Waiting for login.
      </description>
      <label value="User Name:" control="userName"/>
      <textbox id="userName"/>
      <label value="Password:" control="userName"/>
      <textbox id="password"  type="password" maxlength="8"/>
      <button id="loginButton " label="Logon"/>
     <spacer flex="1"/>
  </vbox>
  <spacer flex="1"/>

 </hbox>
 <!-- used to display message -->
We will also remove the "debug" style settings that have been in place to help us with our box positions and settings. And we will temporarily comment out the groove and background color of our styles specified in testStyles.css to make the interface look a little more realistic:
vbox {
/*
  border-style:groove;
  background-color:#888888;
  */
  }

 hbox {
 /*
  border-style:groove;
  background-color:#cccccc;
  */
  }
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
When Things Don't Work
Mistakes happen—there always exists the possibility that this program, as simple as it is, may not work. We will take a brief side trip to look at the simplest (though often most common) errors, and how to quickly find them.
Developers often find themselves confronting problems that fall into three categories:
  • Typographical errors that prevent a script from being parsed and interpreted
  • Programming errors in which the mistake consists of an improper implementation of logic that is otherwise sound
  • Logic errors that represent a flawed design
In terms of XUL development, the designer can rely on the JavaScript console to help report coding and logic errors, the DOM inspector to view a XUL interface tree, the JavaScript debugger to help trace programming and logic errors, and the operating system console to report the output of TRACE statements during program execution.
To show how you can use these tools, we'll look at the basic types of errors and how to identify them.
Because this is a simple application, let's purposely break the file and see what happens.
In the case of typographical errors that result in a corrupted XUL file, most mistakes are caught rather quickly. For example, removing one of the double quotes for an attribute assignment:
<!-- a container for some kind of list -->
 <vbox flex="1 > <!-- quote intentionally left out -->
 </vbox>
yields an immediate response when we try to open the source XUL file, as shown in .
Figure 3-10: XUL file parsing error
Less obvious is how to detect a problem with a source JavaScript file.
For example, if we intentionally leave out one of the closing parentheses in our initialize function:
function initialize(  ) {
try {
 document.getElementById("B1").addEventListener("command",
  genericBtnHandler,true;
 // Oops no closing paren
when we open the corrupt source file with Firefox, the interface looks fine, but pressing button 1 does nothing. How do we find out what is wrong?
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
This chapter introduced the basics of using JavaScript to interact with a XUL interface through the DOM. The basics of accessing the DOM tree, looking up element nodes, and modifying their style and content provide developers with the fundamental skills to build a XUL application.
We also covered the main debugging techniques and tools that we will use for the rest of this project, including the JavaScript console for reporting execution errors and viewing diagnostic information, the Venkman debugger for interactive debugging, and the DOM Inspector for viewing the DOM tree as the user and our code interact with the interface.
Next, we move our application that runs as a XUL file in a local directory to one that more closely resembles a commercial implementation.
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: Configuring for Chrome and a Server
In this chapter, we will move our application from its home in a test directory to a setting that is more consistent with commercial implementations.
We will create two key pieces for implementing our application:
  • A local XUL application communicating with a Personal Hypertext Processor (PHP) server
  • A remote XUL application being served by PHP scripts
Both implementations will use an SQL database to hold user and password information to conduct the authentication process. shows a block diagram illustrating the relationship of the main elements of our design.
Figure 4-1: NewsSearch information flow
This book uses the term XUL application to describe our NewsSearch project. This differs from conventional web applications that are designed to be served web pages that are rendered by web browsers. A XUL application, however, can be implemented as a page served to a XUL-capable browser, or it can be configured to run as an application local to the user's machine. In the case of the latter, the files that comprise the application (Jav