Create your own awesome maps

Even on the go

with our free apps for iPhone, iPad and Android

Get Started

Already have an account?
Log In

XUL by Mind Map: XUL
0.0 stars - 0 reviews range from 0 to 5

XUL

1. Simple Elements

1.1 Creating a Window

1.2 Adding Buttons

1.3 Adding Labels and Images

1.4 Input Controls

1.5 Numeric Controls

1.6 List Controls

1.7 Progress Meters

1.8 Adding HTML Elements

1.9 Using Spacers

1.10 More Button Features

2. The Box Model

2.1 The Box Model

2.2 Element Positioning

2.3 Box Model Details

2.4 Groupboxes

2.5 Adding More Elements

3. More Layout Elements

3.1 Stacks and Decks

3.2 Stack Positioning

3.3 Tabboxes

3.4 Grids

3.5 Content Panels

3.6 Splitters

4. Toolbars and Menus

4.1 Toolbars

4.2 Simple Menu Bars

4.3 More Menu Features

4.4 Popup Menus

4.5 Scrolling Menus

5. Events and Scripts

5.1 Adding Event Handlers

5.2 More Event Handlers

5.3 Keyboard Shortcuts

5.4 Focus and Selection

5.5 Commands

5.6 Updating Commands

5.7 Broadcasters and Observers

6. Document Object Model

6.1 Document Object Model

6.2 Modifying a XUL Interface

6.3 Manipulating Lists

6.4 Box Objects

6.5 XPCOM Interfaces

6.6 XPCOM Examples

7. Trees

7.1 Trees

7.2 More Tree Features

7.3 Custom Tree Views

7.4 Tree View Details

7.5 Tree Box Objects

8. RDF and Templates

8.1 Introduction to RDF

Resource Description Framework, get data from outside datasources, store resources such as, bookmarks, the history, mail messages, Mozilla provideds datasource for the above common data, Use, populate trees, use any of the provided RDF datasources, point to an RDF file stored in XML, Makes it very convenient to display tress with lots of rows in them, populate other XUL elements, listboxes, menus, RDF specification

RDF/XML, consist of a model, graph representation of data, XML Language, used to represent RDF data., some similarities to the XUL header, Instead of the 'window' element, RDF element is used, The namespace for RDF was declared so that the RDF elements are recognized properly, Place the data indise.

RDF database, Mozilla bookmarks example, list may be hierarchical, can have folders or categories of bookmarks, Each of the fields in an RDF database is a resource, with a name associated with it., described by URI, Example, Name, http://home.netscape.com/NC-rdf#Name, Bookmark Name, URL, http://home.netscape.com/NC-rdf#URL, URL to link to, Description, http://home.netscape.com/NC-rdf#Description, Bookmark description, Last Visited, http://home.netscape.com/WEB-rdf#LastVisitDate, Date of last visit

RDF/XML file example, three records described, one for each animal, Each RDF:Description tag, Describe a single record, three fields are described within each record, name, species, class, Given a namespace of ANIMALS, The URL declared on the RDF tag, The name was selected because it has meaning in this case., The namespace feature is useful because the class field might conflict with that used for styles, Not necessary for all records to have the same fields, But makes sense to have them all the same, The 'Seq' and 'li' elements, specify that the records are in a list., Much like how HTML lists are declared., The 'Seq' element, Indicate that the elements are ordered, or in sequence, Can use 'Bag', Indicate unordered data, 'Alt', Indicate data where each record specifies alternative values (such as mirror URLs), URI generated from the example, Name, http://www.some-fictitious-zoo.com/rdf#name, Species, http://www.some-fictitious-zoo.com/rdf#species, Class, http://www.some-fictitious-zoo.com/rdf#class

8.2 Templates

Populating elements, Create Elements, From data supplied by RDF, 1. RDF file, 2. Internal datasource, Mozilla provided datasources, bookmarks, history, mail messages, Treeitems and Menuitems, Usually populated with data., Obviously can use other elements, Allow creation of elements based on RDF data, Need to provide a simple template, Which will be duplicated for each element that is created., Essentially, you provide only the first element and the remaining elements are constructed based on teh first one., template is created using the 'template' element., Inside 'template', Place the elements want to use, For each constructed element., Placed inside the container, container that will contain the constructed element., Example, If use a 'tree', place 'template' element inside a 'tree' element., Simple Template Example, Create a button for each top-level bookmark., Use Mozilla bookmarks datasource, Visual, A vertical box has been created, Contain a column of buttons, One for each top-level bookmark., Can see in the image that the set of buttons has been created, one for each bookmark., 'template' contains a single 'button', This single button is used as a basis for all the buttons that need to be created., Container and Datasources, Vertical Box, Special attributes, 1. 'datasources' attribute, Declare what RDF datasource will be providing the data to create the elements., e.g. datasources="rdf:bookmarks", bookmarks datasource, provided by Mozilla, My own datasource, specify the URL of an RDF file, e.g. <box datasources="chrome://zoo/content/animals.rdf" ref="http://www.some-fictitious-zoo.com/all-animals">, Can specify multiple datasources at a time, by separating them with a space in the attribute value, Used to display data from multiple sources, 2. 'ref' attribute, Indicates where in the datasource I would like to retrieve data from., bookmarks case, value NC:BookmarksRoot, indicate the root of the bookmarks hierarchy, Depend on the datasource I am using, If using my own RDF file, value is usually correspond to the value of an 'about' attribute on an RDF Bag, Seq or Alt element, Inside the Template, The elements inside the template, Need to be declared differently., 'uri' attribute, above example, 'button' element has an unusual value for the 'label' attribute, attribute, begins with 'rdf', indicates that the value should be taken from the datasource, 'label' attribute of example earlier., The remainder of the value refers to the name property in the datasource, Constructed by, taking the namespace URL used by the datasource and appending the property name., example code, I can dynamically generate lists of elements with the attributes provided by a separate datasource, The uri attribute is used to specify the element where content generation will begin. Content earlier will only be generated once whereas content inside will be generated for each resource., More Examples, This creates a vertical box with a button and a label for each bookmark., The button will have the name of the bookmark and the label will have the URL., The new elements that are created are functionally no different from ones that you put directly in the XUL file. The 'id' attribute is added to every element created through a 'template' which is set to a value which identifies the resource. You can use this to identify the resource., Code, Example 3, You can also specify mutiple resource values in the same attribute by separating them with a space.

How Templates are Built, element that has a 'datasource' attribute, Indicates the element is expected to be built from a template., Object 'Builder', Added to the element, Responsible for building the content from the template, In Javascript, 'builder' property, used to access builder object., I will only need to do this to have the builder regenerate the content in situation where it is not done automatically., Two different types of builders, 1. Content Builder, Used in most situation, starts, uri="rdf:*" specified, example, Takes the content inside the 'template' element and duplicates it for each row., 2. Tree Builder, Used only for trees

Rules, 'rule' element, Define a rule for each variation of elements, e.g. a rule for bookmarks and a rule for separators., Attributes placed on the 'rule' element determine which rules apply to which RDF resource., When scanning for which rule applies to the data, each 'rule' element is checked in sequence for a match., The order in which I define rules is important., Earlier rules will override later rules., Example, By using two rules, we have allowed the contents of the template to be selectively generated., first 'rule', bookmark separators are selected, by the 'rdf:type', second 'rule', Does not have any attributes, So all data matches it, To get an attribute from the RDF namespace (rdf:type), We needed to add the namespace declaration to the 'window' tag, Summary text

8.3 Trees and Templates

Adding Datasources to Trees, 'datasources' and 'ref' attribute to the 'tree' element., specify the datasource and root node to display, Multiple rules can be used to indicate different content for different types of data., e.g. <tree datasource="rdf:history" ref="NC:HistoryByDate" flags="dont-build-content">, 'flags' attribute to the value dont-build-contend, Indicates that the tree builder should be used., In the template, will be one 'treecell', for each column in the tree, The cells should have a 'label' attribute, Set the label for the cell, This would normally be set to an RDF property, so that the label is pulled from the datasource, Template-built Tree Example, The following example demonstrates a template-built tree, in this case for the file system., Detail Explanation Of Logic, Image Explanation

Sorting Columns, Tree which generate their data from a datasource have the optional ability to sort their data, Sort, Ascending, Descending, Any Column, By clicking the column headers, This sorting feature is not available for trees with static content, Although you can write a script to sort that data, Set 'sortDirection' attribute value, ascending, descending, natural, The order the data is stored in the RDF datasource, 'sortActive' attribute, Should be set to 'true' for one column, The one that I would like to be sorted by default, style class 'sortDirectionIndicator', May use this on a column that can besorted., Cause a small triangle to appear on the column header that inidicates the direction of the sort., First attribute, 'sort', Set to an RDF property that is used as the sort key., Example

Persisting Column State, persist which column is currently sorted, Remembered between sessions, Use attributes, 'persist', on each 'treecol' element, Five attributes of Columns, 1. 'width', 2. 'order', 3. 'visible', 4. which column is currently sorted, 5. sort direction, e.g. <treecol id="Date" label="Date" flex="1" class="sortDirectionIndicator" persist="width ordinal hidden sortAvtive sortDirection" sort="rdf:http://home.netscape.com/WEB-rdf#LastModifiedDate

Additional Rule Attributes, Two additional attributes, 1 iscontainer, 2. isempty, If this attribute is set to true, then the rule will match all resources that have no children.

8.4 RDF Datasources

Other Mozilla Datasources, Mozilla provides a number of other built-in datasources, They work very similarly to the bookmarks, although the fields will be different in each case.

The History List, rdf:history, Date, http://home.netscape.com/NC-rdf#Date, Date of last visit, Name, http://home.netscape.com/NC-rdf#Name, Title of the page, Page, http://home.netscape.com/NC-rdf#Page, Page name, Referrer, http://home.netscape.com/NC-rdf#Referrer, Referrer of the page, URL, http://home.netscape.com/NC-rdf#URL, URL of the page, Visit Count, http://home.netscape.com/NC-rdf#VisitCount, Number of page visits, Using the History List Example

Other Datasources, Bookmarks(rdf:bookmarks), Files(rdf:files), The files datasource is an example of a datasource that determines its resources only when necessary. We don't want every file in the filesystem to be determined before the data is displayed. Instead, only the files and directories that the tree element (or other elements) will need to display at a given time will be determined.

Composite Datasources, I can specified multiple datasources, <tree datasources="rdf:bookmarks rdf:history animal.rdf" ref=NC:BookmarksRoot">, This example reads the resources from the bookmarks, history and the animals.rdf file. They are combined into a single composite datasource and can be used as if they were one., rdf:null

Custom RDF Datasources, Use my own RDF datasource storedin an RDF file, local file, remote file, Just put the URL of the RDF file in the datasources attribute., Using RDF file Example, Source, RDF

8.5 Advanced Rules

The Full Rule Syntax, 'rule' tag, child tags, 'condition', specify the criteria for matching a given resource, Can specify a number of conditions, All must match, In the simple rule syntax, The conditions are placed directly on the ' rule' element itself., 'action', If the conditions match for a resource, the content placed within the actions tag is generated., In the simple syntax, the content is placed directly inside the rule., 'bindings'

Rule Conditions, 'content' element, It serves as a placeholder as the template builder iterates through the resources., It specifies the name of a variable in which is placed a reference to the root resource while the conditions are analyzed for a match., The root resource is the one specified by the ref attribute on the element containing the template., syntax, <content uri="?var"/>, The question mark indicates that the text following it is a variable. You can then use the variable 'var' within the remainder of the conditions. Of course, you can name the variable whatever you want., 'member' element, iterate through a set of child resources., means a container such a Seq, Bag or Alt, RDF/XML fragment, want to display a row in a tree for each city. To do this, use the member element, 'triple' element, heck for the existence of a given triple (or assertion) in the RDF datasource, like a property of a resource, a trip exists between a bookmar and its URL, <triple subject="A Bookmark to mozilla.org" predicate="URL" object="www.mozilla.org">, Add a weather prediction to the city datasource, code, template builder iterate over each city as before, When gets to triple, Look for an assertion in the RDF datasource for a city's weather prediction, The variable 'pred' will be assigned the prediction., The builder will repeat this for each of the four cities, A match occurs and the builder will generate content for each city that has a prediction, If the city has no prediction resource, the condition does not match and no content will be generated for that city., No need to put 'rdf:' at the beginning of the predicate., 'condition' tag, replace the 'object' with an in-line value, specify want to match on 'Cloudy', Code to match if city has both name and prediction

Generating Content, Complete Tree Example

Adding Additional Bindings, 'bindings' element, Final element you can add inside a 'rule', Example, This binding will grab the temperature resource of each city and assign it to the 'temp' variable., This is similar to what a triple does, The difference is that a binding is not examined when attempting to check the conditions, This means that the city must have a name and prediction to be displayed, yet it does not matter if it has a temperature., However, if it does, it will be placed in the 'temp' variable

8.6 Persistent Data

Remembering State, save state of a window across session, E.g. The window should remember which toolbars are collapsed even after the user exits., localstore.rdf, in the same directory as other user preferences., New nodeHolds state information about each window, New nodeIt works with Mozilla user profiles, so that each user can have different settings., 'persistent' attribute, add a 'persist' attribute, to the element which holds a value you want to save., Set to a space-separated list of attributes of the element that you want to save., The element must also have an 'id' attribute, sample code

Our Find Files Example, This will cause the x and y position of the window and the width and height of the window to be saved.

Save the state of a XUL window

9. Skins and Locales

9.1 Adding Style Sheets

Style Sheets, <?xml-stylesheet href="chrome://global/skin/" type="text/css">

Changing the Styles, For installed files, you'll have to create or modify a manifest file and install the skin., Our find Files Dialog Example, The new xml-stylesheet line is used to import the style sheet, findfile.css

Importing Style Sheets, Style import from XUL, <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>, Style import from CSS, @import url(chrome://global/skin);, The second syntax is preferred because it reduces the number of dependencies within the XUL file itself., All elements can be styled using CSS, Selector, Select the element that I wish to have styled., The selector is the part before the curly brace in a style rule, Summary of selectors, You can combine these rules in any way that you wish. It is always a good idea to be as precise as possible when specifying what gets styled. It is more efficient and it also reduces the likelihood that you'll style the wrong thing.

9.2 Styling a Tree

Styling the Tree, Style added to the 'tree' element will apply to the entire tree, Adding a style to the 'treecol' element does not cause the style to be applied to the column but only to the header, body of the tree, outer 'treechildren', only real element in the tree body, The inner elements are just placeholders

Setting Properties, use the 'properties' attribute, on the rows or cells to set one or more named properties, Can be used with static content, RDF built content, Those with a 'custom view', e.g. <treerow properties="makeItBlue">

CSS Selectors for the Tree, syntax, <treechildren::-moz-tree-row(makeItBlue) { background-color: blue; }, values, ::-moz-tree-cell, a cell. Use this to set borders and background colors., ::-moz-tree-cell-text, he text in a cell. Use this to set the font and text color., ::-moz-tree-twisty, the appearance of the twisty used to expand and collapse child rows., ::-moz-tree-image, the image for a cell. You can set the image with the list-style-image property., ::-moz-tree-indentation, the indentation to the left of rows that are children of other rows., ::-moz-tree-column, a column., ::-moz-tree-line, the lines that are drawn to connect child rows to parent rows., ::-moz-tree-separator, a separator in a tree., ::-moz-tree-progressmeter, content for progressmeter cells. You can create a progressmeter column by setting the type attribute on the column to progressmeter., ::-moz-tree-drop-feedback, the drag and drop feedback., ::-moz-tree-checkbox, the image to use for checkbox columns., ::-moz-tree-row, a row. Use this to set the background color of a row., I can check for multiple properties, separating them with commas

Default Properties, checked, this property is set cells whose column is type="checkbox", focus, this property is set if the tree currently has the focus., selected, this property is set for rows or cells that are currently selected., current, this property is set if the keyboard cursor is at the row. Only one row will have this property set at a time., hover, this property is set if the mouse cursor is on the row. Only one row will have this property set at a time., container, this property is set for rows or cells that have child rows., leaf, this property is set for rows or cells that do not have child rows., open, this property is set for rows or cells which are expanded., closed, this property is set for rows or cells which are collapsed., primary, this property is set for cells in the primary column., sorted, this property is set for cells in the current sorted column., even, this property is set for even numbered rows., odd, this property is set for odd numbered rows. This property, along with the even property allow you to set, for example, alternating colors for each row., dragSession, this property is set if something is currently being dragged., dropOn, if a drag is occuring over the tree, this property is set for the row currently being dragged over, as long as the mouse pointer is hovering over the row., dropBefore, this property is set if the mouse pointer is hovering before the row currently being dragged over., dropAfter, this property is set if the mouse pointer is hovering after the row currently being dragged over., progressNormal, this property is set for progress meter cells., progressUndetermined, this property is set for undeterminate progress meter cells., progressNon, this property is set for non-progress meter cells., The properties are set for rows or cells in rows with the necessary state. For columns and cells, one additional property, the id of the column or column the cell is in will be set.

Setting Properties for the RDF-built Trees, For RDF-built trees, you can use the same syntax. However, you will often set the properties based on values in the datasource.

Setting Properties for the Custom View, set properties, By supplying the functions, getRowProperties(), e.g. getRowProperties:function(row,prop), getColumnProperties(), etColumnProperties : function(column,columnElement,prop){}, getCellProperties(), getCellProperties : function(row,column,prop){}, These return information about an individual row, column and cell, Example, Make every fourth row have blue text, code, var aserv=Components.classes["@mozilla.org/atom-service;1"].getService(Components.interfaces.nsIAtomService);, props.AppendElement(aserv.getAtom("makeItBlue"));, This function would be defined as part of a view object

Example style sheet

9.3 Modifying the Default Skin

Skin Basics, skin, set of style sheets, images, behaviors that are applied to a XUL file, I can change the look of a window without changing its functionality, Firefox provides a skin by default, I may download others, The XUL for any skins is the same, The style sheets and images used are different, Described in CSS, define, colors, borders, images, The file classic.jar, contains the skin definitions., The global direcotyr within this archive contains the main style definitions for how to display the various XUL elements., By changing these files, you can change the look of the XUL applications

Customize with userChrome.css, If I place 'userChrome.css' in a directory called 'chrome' inside my user profile directory, I can override setting without changing the archives themselves., The file 'userContent.css", customizes Web pages, customizes chrome files, E.g., menubar {background-color:red;}

Skin Packages, Effect only one window, Example, Add a red border around the meuu commands in the bookmarks manager window, change bookmarksManager.css in classic.jar, menuitem {border: 1px solid red;}, 'list-style-image' property, Can assign images to a button, checkbox and other elements, checkbox {list-style-image: url("chrome://findfile/skin/images/check-off.jpg");, checkbox[checked = "true"] {list-style-image: url("chrome://findfile/skin/images/check-on.jpg);

9.4 Creating a Skin

A Simple Skin, Creating a Custom Skin Package, Adding Style Rules, Example Code, first rule (for 'window > box'), specifies that the chid box of the window has a different color, CSS: .findfilesbox {background-color:#0088CC;}, XUL: <vbox class="findfilesbox" orient="vertical" flex="100%"> <toolbox>, Rounding on the Tabs, special Mozilla style rule, -moz-border-radius, creates rounded border corners, The last rule only applies to tabs that have their 'selected' attribute set to true, It makes the text in the selected tab appear bold, underlined and dark blue, Adding Toolbar Icons, It is somewhat difficult to distinguish the buttons on the toolbar from the commands on the menu., Mozilla Composer provides some icons for open and save buttons, which we'll just use here to save time., We can set the image for a button using the 'list-style-image' CSS property, Other Changes, code, We add some images to the buttons and make the Find button have bold text, indicate it is the default button, The last rule applies to buttons when the mouse is hovering over them., Set text color to dark blue in this case., minor changes to the spacing around the items, by setting margins.

Creating a Global Skin

9.5 Localization

Entities, Table of strings is created for each language, Instead of hard-coding text directly into an application, each piece of text is only a reference into the string table, SML provides entities which can be used for a similar purpose, codes, &lt, entity used to place less than sign, &gt, entity used to place greater than sign, XML has a syntax which allow you to declare custom entities., I can use these so that the entity is replaced with its value, which can be a string of text, Entities may be used whenever text occurs, including the values of attributes., Example, <button label="&findLabel;", demonstrates the use of an entity in a button, The text that will appear on the label will be the value that the entity &findLabel; has., A file is created which contains the entity declarations for each supported language., In English, the &findLabel; entity will probably be declared to have the text "Find".

DTD Files, Entities are declared in Document Type Definition (DTD) files, Declare the syntax and semantics of a particular XML file, but they also let you declare entities, In the Mozilla chrome system, find DTD files located in the 'locale' subdirectory, non-installed chrome files, just put the DTD file in the same directory as the XUL file., Note, Normally one DTD file per XUL file, use in XUL, add line, <!DOCTYPE window SYSTEM "chrome://findfile/locale/findfile.dtd">, add the locale to the chrome.manifest file,, locale findfile en-US locale/

Declaring Entities, syntax, <!ENTITY findLabel "Find">, for Japanese, <!ENTITY findLabel "検索">, Use entities for values, that could be different in a different language, E.g.Access keys and keyboard shortcuts

Changing the Find Files example, xul code, Each text string has been replaced by and entity reference., A DTD file has been included near the beginning of the XUL file, Each entity that was added should be declared in the DTD file, more note, findfile.dtd

9.6 Property Files

Properties, Like DTD, For message to be displayed from script

Stringbundles, <stringbundleset id ="strbundles">, <stringbundle id="strings" src="strings.properties"/>, </stringbundleset>, Getting a String from the Bundle, 'getString' properties, var strbundle = document.getElementById("strings");, var nofilesfound=strbundle.getString("notFoundAlert");, alser(nofilesfound);, Text Formatting, 'getFormattedString()' method, Example, result

Escape non-ASCII Charaters

10. Bindings

10.1 Introduction to XBL

XUL's sister language

eXtensible Bindings Language

Bindings, Describes the behavior of a XUL widget, e.g. a binding might be attached to a scroll bar, The behavior describes the properties and methods of the scroll bar in addition to describing, XBL is an XML language, The 'binding's element is the root element of an XBL, contain one or more 'binding' elements, Declares a single binding, 'id' attribute can be used to identify the binding, I assign a binding to an element by setting the CSS property -moz-binding to the URL of the binding file, scrollbar { -moz-binding: url('chrome://findfile/content/findfile.xml#binding1'); }, Five types of things that it declares, 1. Content, child elements that are added to the element that the binding is bound to., 2. Properties, properties added to the element. They can be accessed through a script., 3. Methods, methods added to the element. They can be called from a script., 4. Events, events, such as mouse clicks and keypresses that the element will respond to. The binding can add scripts to provide default handling. In addition new events can be defined., 5. Style, custom style properties that the XBL defined element has

Binding Example, This example creates a window with a single box., The box has been declared to have a class of okcancelbuttons., The box has been declared to have a class of okcancelbuttons.

10.2 Anonymous Content

XBL Content, Declaring Scrollbar Example, Contains a single binding, 'content' tag, declare anonymous content, will be added to the scroll bar, Filename Input Field Example

Override the Bound Element, e.g. <scrollbar/> <scrollbar><button label="Overridden"/></scrollbar>

Using the Children Element, When I want both the XBL content and the content provided by the XUL file to be displayed.', Added in place of the 'children' element., Handy when creating custom menu widgets., Example, Creats an input field with a button beside it., The 'menupop' will be added to the content in the location specified by the 'children' element, To DOM functions, the content will appear as it was in the XUL file., 'menupopup' will be a child of the 'menu', XBUL content is hidden away so the XUL developer doesn't need to even know it is there., result content, 'include' Attribute, I wish to only include specific types of content, Allow only certain elements to appear in the content., Its value should be set to a single tag name, or to a list of tags separated by vertical bars, <children includes="button"/>, This line will add all buttons that are children of the bound element in place of the 'children' tag., I can place multiple 'children' element in a binding to place different ypes of content in different placfes., Other elements will not match this tag., Example, The explicit children in the XUL file will be placed at the location of the 'children' tag., There are two images, so both will be added next to each other., Resulting code, From the DOM's perspective, The 'child' elements are still in their original location., The outer XUL box has two children, which are the two images, The inner box with the border has one child, the 'children' tag., This also applies to CSS selector rules., Multiple Children Elements, I can use multiple 'children' elements and have certain elements be placed in one location and other elements placed in another., By adding a 'include' attribute and setting it to a vertical bar-separted list of tags., I can make only elements in that list be placed at that location., Example, The first 'children' element only grabs the label and button elements, as indicated by its 'include' attribute., The second 'children' element, because it has no 'include' attribute, grabs all of the remaining elements.

10.3 XBL Attribute Inheritance

Attributes can be inherited

Inherited Attributes, XBL allow us to build composite widgets while hiding their actual implementation., Add attributes to the bound elements that modify the inner elements., Example, The 'label' attribute has been placed directly on the 'button' element., The problem with this is that the label would be the same every time the binding was used., 'inherits' attribute, To be placed on the element that should inherit an attribute from the outer element., In this case the button. Its value should be set to a comma-separated list of attribute names that are to be inherited., <xul:textbox xbl:inherits="flex"/><xul:button xbl:inherits="label"/>, When the content is generated, the 'textbox' grabs the 'flex' attribute from the searchbox and the 'button' grabs the 'label' attriburte from teh searchbox., This allows both the flexibility of the textbox and the label of the button to be different for each use of the binding., Changing the value of the attributes on the searchbox with a script will update the textbox and button also., I can add the 'inherits' attribute to as many elements as I wish, to inherit any number of attributes., When the inherits attribute has been placed in the XBL namespace, by prefixing it with 'xbl:'. The namespace should be declared somewhere earlier, usually on the 'bindings' element., example, The button inherits the 'label' attribute., Note this attribute is also given a value directly in the XBL. This technique is used to set teh default value if the attribute is not present., This button will inherit its 'label' attribute from the outer element., If no 'label' is present, it will be given a default value of OK, Two generated elements inherit from an attribute that has the same name., e.g. create a labeled textbox out of a 'label' and a 'textbox' element., The label will need to inherit its text from the 'value' attribute and the textbox will also need to inherit its default value from the 'value' attribute as well., We need to use a different attribute and map it to the same one., The 'textbox' inherits the 'value' attribute directly., The 'inherits' attribute on the label grabs the 'title' attribute from the labeledtextbox and maps it to the 'value' attribute of the 'label' element., Another example, The value of the oktitle attribute is mapped to the 'label' attribute of the first button., The canceltitle attribute is mapped to the 'label' attribute of the second button., The first button also inherits the 'image' attribute., Result code, The attributes are duplicated on the inner content. Changing the attributees on the box with the okcancel class will automatically change the values on the buttons., Noticed that we just made up our own attribute names. This is valid in XUL.

10.4 Adding Properties

The XBL Interface, I can define my own properties for the elements I created., I can also add methods that can be called., Three types of items I can add, Field are used to hold a simple value, Properties can also be used to hold a value but may have code execute when an attempt is made to retrieve or modify the value., Methods are functions which may be executed., All three are defined within an 'implementation' element, which should be a child of the 'binding' element. Within the implementation, I define individual field, property, and method elements, one for each one that I want., General syntax

Fields, code, A 'number' field has been defined in the binding, which stores the random number., The two extra buttons set and get the value of this field., The syntax is very similar to getting and setting the properties of HTML elemetns., In this example, no content has been placed inside either the XUL box or its definition in XBL, which is perfectly valid., Should assigned a default value, <field name="number"> 25</field>, <field name="currentTime"> new Date().getTime();</field>

Properties, Onget Attribute and Onset Attribute, I can use the 'onget' and 'onset' attributes to have code execute when teh property is retrieved or modified., Each to the 'property' element and set its value to a script which either gets or sets the value of the property., example

Getter Element and Setter Element, code, The property in this example will only be able to hold integer values.

Readonly Attribute, adding a 'readonly' attribute, To the 'field' tag or 'property' tag and setting it to true, Attmpting to set the value of a read-only property will fail

10.5 Adding Methods

Methods, example code, A method declaration goes inside the implementation element, like the fields and properties do., Two type of child elements, parameters, describe the parameter to the method and 'body' which contains the script for the method., 'body' element, It contains the script that is executed when the method is called., The names of the parameters are defined as variables in the script as if they ahd been passed as parameters., Example JavaScript function written as XBL method

Accessing the Anonymous Content, 'getAnonymousNodes' method, var value=document.getAnonymousNodes(element);, Example code

Accessing from Inside the Anonymous Content, 'getBindingParent' method, 'parentNote' property, go up by a single node., The children of an element placed in the XUL file can be retrieved in the normal way and don't move even if you use the 'children' tag., Code

Constructors and Destructors, Example Code

10.6 Adding Event Handlers

Event Handlers, I can trap the events and handle them in a special way, I can add event handlers to the elements inside the content if needed., e.g. 'oncommand' handlers added to some button, Handler Element, Can add event handler to the entire contents, all elements defined in the 'content' tag., e.g userful when trapping the focus and blur events., Describe the action taken for a single event handler., I can use more than one handler if necessary., If an event does not match any of the 'handler' events, it is simply passed to the inner contnet as usual, General handler syntax, Use the event name withou the 'on' in front of it., A common reason to set handlers is to modify the custom properties when an event occurs., For example, a custom checkbox might have a checked property which needs to be changed when the user clicks the checkbox, <handlers><handler event="mouseup" action="this.checked=!this.checked"/></handlers>, Handling Mouse Events, Example, Handling Key Events, Example, I can also use the 'keycode' attribute to check for non-printable keys. The section on keyboard shortcuts provide more inforamtion., The modifier keys can be checked by adding a 'modifiers' attribute., Valid Values, alt, control, meta, shift, accel, If set, the handler is only called when the modifier is pressed. You can require multiple modifier keys by separating them with spaces., syntax when the code in a handler is more complex

Handlers Example, The content is a single textbox, A field 'clipboard' has been added to it to store the clipboard contents., This does mean that the clipboard operations are limited to this single textbox. However, each one will have its own buffer., Three handlers added, 1. Cut, this.clipboard=document.getAnonymousNodes(this)[0].vaule;, document.getAnonymousNodes(this)[0].value;, 2. Copy, 3. Paste

10.7 XBL Inheritance

Inheritance, add 'extends' attribute to the 'binding' tag., Example Source, The XBL here extends from the XUL 'textbox' element., The URL given in the extends attribute is the URL of the binding of the textbox binding., This means that we inherit all of the content and behavior provided by the textbox binding., In addition, we add a handler which responds to the keypress events.

Autocompleting TextBoxes, Adds extra event handling so that when a URL is typed, a menu pop up with possible completions., I can use it in my own application too., Just create a textbox with two extra attribute, <textbox type="autocomplete" searchSessions="history">, Set the 'type' to 'autocomplete' to add teh autocomplete feature to an existing textbox., Set the 'searchSessions' to indicate what type of data to look up., In this case, the value history is used, which looks up URLs in the history., I can also use the value addrbook to look up addresses in the address book., Firefox uses a different autocomplete mechanism than the Mozilla suite, see XUL:textbox (Firefox autocomplete)

10.8 XBL Example

A Slideshow Element, Content of the Slideshow, Example Source, This binding creates the slideshow structure that we want., The 'flex' attribute has been added to a number of elements so that it stretches in the right way., The 'label' attributes on the two buttons inherit their values from the bound element. Here, they inherit from two custom attributes, 'previoustext' and 'nexttext'., This makes it easy to change the labels on the buttons., The children of the element that the XBL is bound to will be placed inside the 'deck'., The 'selectedIndex is inherited by the dec, so we may set the initial page in the XUL., XUL file, The first button, 'Button 1" has been used as the first page of the deck. The 'label' widget has not appeared as no 'value' has been specified for it., Style Sheet used here, .slideshow { -moz-binding: url("slideshow.xml#slideshow"); }, page Property, code, The 'page' property gets its value by looking at the first element of the anonymous array. This returns the vertical box, so to get the deck, we need to get the first child node of the box., The anonymous array isn't used as the deck is not anonymous from the box., Finally, the value of the 'selectedIndex' attribute is retrieved., To set the page, a method 'setPage' is called which will be define later., An 'oncommand' handler will need to be added to the Previous and Next buttons so that the page is changed when the buttons are pressed., Conveniently, we can change the page using the custom 'page' property that was just added:, Because the 'page' property is only on the outer XUL element, we need to use the parentNode property to get to it., The first parentNode returns the parent of the buttonwhich is the horizontal box, the second its parent, the vertical box, and finally, its parent which is the outer box., The 'page' property is incremented or decremented. This will call the 'onget' script to get the value, increment or decrement the value by one, and then call the 'onset' handler to set the value., setPage method, This function is called 'setPage' and takes one parameter 'newidx'., The body of the method has been enclosed inside '<![CDATA['and']]>'., This is the general mechanism in all XML files that can be used to escape all of the text inside it., That way, you don't have to escape every less-than and greater-than sign inside it., var thedeck=document.getAnonymousNodes(this)[0].childNodes[0];, Get the first element of the anonymous content array, which will be the vertical box, then get its first child, which will be the deck element., var totalpages=this.childNodes.length;, Get the number of children that the bound box has. This will give the total number of pages that there are., if (newidx<0) return 0;, If the new index is before the first page, don't change the page and return 0. The page should not change to a value earlier than the first page., if (newidx>=totalpages) return totalpages;, If the new index is after the last page, don't change the page and return the last page's index. The page should not change to one after the last page., thedeck.setAttribute("selectedIndex",newidx);, Change the selectedIndex attribute on the deck. This causes the requested page to be displayed., document.getAnonymousNodes(this)[0].childNodes[1].childNodes[1].setAttribute("value",(newidx+1)+" of "+totalpages);, This line modifies the label element so that it displays the current page index. The label element can be retrieved by getting the first element of anonymous content (the vertical box), the second child of that label element (the horizontal box), and then the second element of that box. The value attribute is changed to read '1 of 3' or something similar. Note that one is added to the index because indicies start at 0., Constructor, Code, Additional Features, Some keyboard shortcuts could be used for teh Previous and Next buttons (say backspace and the Enter key)., First and Last buttons could be added to go to the first and last pages., The label element could be changed to a field where the user could enter the page to go to, or a popup could be added to allow selection of the page from a menu., We could also add a border aroudn teh deck with CSS to make it look a bit nicer., The Final Code

11. Specialized Window Types

11.1 Features of a Window

Creating Another Window, As in HTML, window.open() function, Open second window, return a reference to the newly opened window, Can use this reference to call functions of the other window, Take three arguments, Arg. 1: URL of the file you wish to open, Arg. 2 :Internal name of the window, Arg .3: List of display flags, Flat 'chrome' is important to open the window as a chrome file, If you do not add the 'chorme' flag, the file will open up as the content in a browser window., Example, var myWin = window.open("chrome://findfile/content/findfile.xul", "findfile", "chrome");

Specifying the Width and Height, Example specified width and height, <window width='400' height ='450' xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">, width=400 pixel, height=450 pixel, must specified both width and height, if only specify one, other will be set to zero

Other Window Features, Can use any of the pre-existing flags, find in a Javascript reference, May disable a feature by setting it to 'no', e.g. 'dialog=no', alwaysLowered, The window will always appear behind other windows, alwaysRaised, The window will always appear above other windows, centerscreen, The window will be centered on the screen when opened., dependent, The window will always appear relative to the window that opened it. If the window that opened the new window is moved, the new window is moved relative to it., dialog, The window is a dialog box, which may appear differently., modal, The dialog is modal. The window that opened the modal window can't be interacted with until the modal window is closed., resizable, The user can resize the window

See also DOM window.open() reference

11.2 Creating Dialogs

Creating a Dialog, openDialog() function is used to open a dialog, related to open(), displays a dialog instead of a window, take additional arguments beyond the first three, These arguments are passed to the new dialog and placed in an array stored in the new window's 'arguments' property., You can pass as many arguments as you wish, Example, var somefile=document.getElementById('enterfile').value;, window.openDialog("chrome://findfile/content/showdetails.xul", "showmore", "chrome", somefile);, In this example the dialog showdetails.xul is displayed. It's passed one argument, somefile, which was taken from the value of an element with the ID enterfile. In a script used by the dialog, we can then refer to the argument using the window''s arguments property., var fl = window.arguments[0];, document.getElementById('thefile').value = fl;, Pass Values back, 'window.opener' property, holds the window that opened the dialog.

The Dialog Element, Example, <dialog id="example" title="Dialog example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" buttons ="accept, cancel" ondialogaccept="doOK()" ondialogcancel="return do Cancel();">, <script> function doOK() {alert("You pressed OK!"); return true; }, return true, indicates that the dialog should be closed., if dialog shouldn't be closed, false should be returned, function doCancel() { alert("You pressed Cancel!"); return true;} </script>, <description value="Select a button"/>, </dialog>, The button attributes, accept - an OK button, cancel - a Cancel button, help - a Help button, disclosure - a disclosure button, which is used for showing more information, values separated by commas, Can set code to execute when the buttons are pressed, 'ondialogaccept', 'ondialogcancel', 'ondialoghelp', 'ondialogdisclosure', Other useful attributes, buttonlabelaccept, label to appear on the accept button e.g. Save, buttonaccesskeyaccept, access key to use for the accept button eg S, defaultButton, Button is activated when teh Enter key is pressed, The buttons elements, can be accessed with the following javascript, var acceptButt = document.documentElement.getButton("accept")

11.3 Open and Save Dialogs

File pickers, Is a dialog that allows the user to select a file, Most commonly used for the Open and Save menu commands, XPCOM interface 'nsIFilePicker', used to implement a file picker, Note: file picker only works from chrome URLs, THREE Modes, 1. Open, the user is asked to select a file for opening, 2. Get Folder, the user is asked to select a folder (directory), 3. Save, the user is asked to select the name to save a file to, Creating a file picker, Need to create a file picker component and initialize it, var nsIFilePicker =Components.interfaces.nsIFilePicker;, var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);, A new file picker object is created and stored in teh variable 'fp'., fp.init(window, "Select a File", nsIFilePicker.modeOpen);, This function takes three arguments, The window that is opening the dialog, The title of the dialog, The mode, Default directory and filters, Two features you can set before displayed, 1. Default directory that is displayed when the dialog is opened, Set the default directory by setting the 'displayDirectory' property of the file picker object, The directory should be an nsILocalFile object, 2. A filter that indicates the list of file types that are displayed in the dialog., e.g. to hide all but html files, To add filters, call the appendFilters() function to set the file types that you wish to have displayed, fp.appendFilters(nsIFilePicker.filterHTML | nsIFilePicker.filterImages);, add filters for HTML and for image files, the manner in which this is done is plateform specific., fp.appendFilters(nsIFilePicker.filterText | nsIFilePicker.filterAll);, Add filters for text files and for all files. The user therefore has the option to display text files only or all files., XML, filterXML, XUL, filterXUL, To Filter Custom Files, appendFilter(), e.g. fp.appendFilter("Audio Files", "*.wav; *.mp3");, Getting the selected file, show the dialog, show() function, It takes no arguments but returns a status code that indicates what the user selected., The function does not return until the user has selected a file.', Returns one of the Three Constants, (1) returnOK, the user selected a file and pressed OK. The file the user selected will be stored in the file picker's file property., (2) returnCancel, the user pressed Cancel., (3) return Replace, In the save mode, this return value identifies that the user selected a file to be replafced. (returnOK will be returned when the user entered the name of a new file.), Should check the return value and then get the file object from the file picker using the file property, var res=fp.show();, if (res == nsIFilePicker.returnOK) { var thefile = fp.file; // -- do something with the file here --- }

11.4 Creating a Wizard

The Wizard, A wizard is a special type of dialog that contains a number of pages, Buttons appear at bottom, Each page contains a single question or a set of related questions, After the last page, the operation is carried out., Often used to help the user perform a complex task, 'wizard' element, The pages of the wizard are created using the 'wizardpage' element., wizardpage, You can place whatever content you want, Note: wizards currently only work properly from chrome URLs., The 'description' attribute, May optionally be placed on a wizardpage element, To provide a sub-caption for that page., Attribute 'onwizardfinish'

Handling Page Changes, wizard.onwizardfinish attribute, Set it to a script, This script might be used to save the information that the user entered during the wizard, E.g., <wizard id="example-window" title="Select a Dog Wizard" onwizardfinish="return saveDogInfo();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">, When the user clicks the Finish button, the function saveDogInfo() will be called., return true, wizard close, return false, wizard does not close, e.g. saveDogInfo() encountered invalid input, related attributes, onwizardback, Back button, onwizardnext, Next button, onwizardcancel, Cancel button, Above attributes are called when the Back, Next and cancel buttons are pressed respectively., wizardpage Attributes, onpagerewound, onpageadvanced, You can use different code for each page., Validate input before continue, onpagehide, method called when the page is hidden, onpageshow, method called when the page is shown, pageadvanced, <wizardpage pageadvanced='return funcName()'></wizardpage></code>

11.5 More Wizards

More Complex Wizard Navigation, 'next' attribute, wizard's goto() method, arg, page ID, Might call this method in the onpageadvanced, Or onwizardnext handlers, return false, New nodeBecause already changed the page

Wizard Functions, wizard works like, tabbed panel, except that the tabs are not displayed and the user navigates between pages by using the buttons along the bottom., Property, canAdvance, set to true, indicate that the Next button should be enabled., if set to false, the Next button is disabled., You can change the property when invalid or valid data has been entered., Example, <?xml version="1.0"?>, <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>, <wizard id="theWizard" title="Secret Code Wizard" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">, <script> function checkCode() { document.getElementById('theWizard").canAdvance = document.getElementById('secretCode').value == "cabbage"); } </script>, <wizardpage onpageshow="checkCode()"; return true;"> <label value="Enter the secret code:"/> <textbox id=secretCode" onkeyup="checkCode();"/> </wizardpage>, <wizardpage> <label value="That is the correct secret code."/> </wizardpage>, </wizard>, canRewind, Can use to enable or disable the Back button, the Back button will be disabled on teh first page, you don't have to set it yourself, currentPage, holds a reference to the currently displayed wizardpage, You can also modify the current page by changing the property, When Change it, The various page change events will be fired.

11.6 Overlays

Using Overlays, In simple application, With only one window, One XUL file, A script file, A style sheet, A DTD file, perhaps some images, More sophisticated applicatons, Contain many, windows, dialogs, Common between each window, Numerous elements or parts of the UI, Eg., Each of Mozilla's components share some common elements, Some of the menus are similar, Tools menu, Help menu, sidebar is similar, each window shares some common global keyboard shortcuts., One could re-implementing, the similar elements and functions in each file that are needed., difficult to maintain, Use a mechanism, Allows you to separate the comon elements and have them shared between windows., Do this with Overlays, Example, Create help menu that is shared between several windows., help menu placed in an overlay, given 'id' attribute to identify it., Each window will import the overlay, using a directive, Only need to add a single menu element, same vale for its id attribute as used in the overlay, This menu does not need to contain any children, When a window with an overlay is opened, the elements in both the window and the overlay with the same ids are combined together., The children of matching elements are added to the end of the set of children in the window's element., Attribute that are present on the overlay's elements will be applied to the window's elements., find files example, import overlay syntax, <?xul-overlay href="chrome://findfile/content/helpoverlay.xul"?>, Added somewhere near the top of the file, Usually just before any DTDs are declared, Simple help menu stored in an overlay, Source, need to include the DTD file, Code use the overlay, Help 'menu' element contains no content, items from the menu are taken from the overlay, becaue ids match, DTD file, putting the attributes on the help menu in the overlay, label, accesskey

Duplicate content, window's content used, overlay's content appended, Example

Placing Overlaid Elements, Allows you to overlay menus, toolbars and other widgets at the exact location wished., attribute, 'insertbefore', value = id of an element want to insert before, 'insertafter', position, specify a specific index position, first position is 1

Removing elements, Example

Can be used to separate common content

11.7 Cross Package Overlays

Applying Overlays to other Packages, Note: This section talks about contents.rdf which ahs been replaced in Gecko 1.8 by Manifest Files, Have the oerlays specify which windows that they apply to, Example, Add 'menu items' or 'toolbars' to Mozilla brower window., The Mozilla Mail application, find files example, special here, id used on the 'toolbox', value(browser-toolbox), same as the identifier of the toolbox in the browser window, navigator.xul, To add this overlay to the manifest file, 1, Add one for each window that we are applying an overlay to., Add code into contents.rdf just before the closing RDF tag., Declares that we are adding a overlay window, A child of the root overlay node (urn:mozilla:overlays, You can add additional nodes for any other windows that you want to apply overlays to by adding additional 'li' nodes., 2. Add a node for each overlay to apply to the window, dd these lines just after the previous lines., Mozilla Example Detailed

Apply overlays to files that don't import them.

12. Installation

12.1 Creating an Installer

XPInstall Packages, XPInstall, (a). XUL Windows, (b). Scripts, (c). Other Files, Packaged into JAR files, All files want to be installed, install.js, extension, typically .api, pronounced zippy, distinguish from other archives, Single File Installer, Simple Install Script, (a) Download Package, (b) Install, (c) Mechanism, XPInstall

Install Triggers, Global Object InstallTrigger, function InstallTrigger.install(), args, (a) Package name, (b) Callback function, Called when Installation complete

XPI Archives, must contain install.js, xpi, install.js, JARS, special zip file, can use zip utility to view and add file

12.2 Install Scripts

Creating an install script, note: for FireFox Extension, install.js is replaced by install.rdf, 1. specified what package and version is been installed, 2. Use the install function to install the files and directories. Or remove files or directory e.g. uninstall portion of the program, Indicated Only, Allow process to be aborted if encounter error, System stay unmodified, 3. Start the process of installing the necessary

The Component Registry, Store Infomration about application, File List, Versions, Other relevant info, Hierarchy of keys and values, Key, Directory like path, e.g. Author/Package Name, e.g. Netscape/Personal Security Manager

Install Initialization, Install Object has a function, initInstall(), initialize for installation, Should be called at beginning of installation script, e.g. initInstall("packageName", "regPackage", "version");, e.g. initInstall("Find Files", "/Xuplanet/Find Files", "0.5.0.0");, Set the directory files are installed, (a) Simple, Assigned a directory and install all files there, setPackageFolder();, from know directory, for portability reason, e.g specify identifier of known directory, e.g. Chrome, One arg., The directory, e.g. findDir = getFolder("Chrome", "find file");, setPackageFolder(findDir);, (b) Advance, Assign per file basis, New node

Setting Install Files, addDirectory();, All content under the directory installed, addFile();, File specified installed, registerChrome();, registerChrome(Install.CONTENT | Install.DELAY_CHROME, getFolder(findDir, "content");, registerChrome(Install.SKIN | Install.DELAY_CHROME, getFolder(findDir, "skin");, registerChrome(Install.LOCALE | Install.DELAY_CHROME, getFolder(findDir, "locale");, DELAY_CHROME, indicates chrome to be installed next time Mozilla is run

Install Completion, performInstall();, take no arg.

12.3 Additional INstall Features

Mozilla XUL Tutorial