Learn about XUL, a subset of XML used to describe user interfaces, that helps you to make rich user interfaces with nothing more complicated than a text editor. In the fifth part of this series you will receive an introduction to XPCOM, the object model used by XUL, and take a close look at a basic example of the combination of Mozilla components and interfaces that make up the abstraction layer.
The code needed to open the dialog box that you use to select which file to open is implemented using the nsIFilePicker interface. The file open dialog will be opened when the Open button on the menu is selected, so it will need to go into a function, which will be called when the Open button is selected. Add anoncommand="openDialog();"call to the open menu element. JavaScript would normally go into a file of its own, but for this example it can sit in the XUL file. Add the opening script tag and begin the function:
<script> function openDialog() {
The first line of the code inside the function sets a variable to hold the filePicker interface:
var nsIFilePicker = Components.interfaces.nsIFilePicker;
You then set a second variable to hold the component and request an instance of the interface:
Next you set a variable that initializes the open file dialog, and pass it parameters that specify its type, its title and its mode:
fileChooser.init(window, "Select a File to open", nsIFilePicker.modeOpen);
Finally, you create a variable that calls the show() method of the open file dialog, which is what displays the box on screen:
var fileBox = fileChooser.show();
Don’t forget to add the closing curly brace to signify the end of the function. The code required to create the Save As dialog box is extremely similar. Create the following function and note that the only differences are the title and mode of the initialization variable:
function saveDialog() { var nsIFilePicker = Components.interfaces.nsIFilePicker; var fileChooser = Components.classes["@mozilla.org/ filepicker;1"].createInstance(nsIFilePicker); fileChooser.init(window, "Select a Location to save", nsIFilePicker.modeSave); var fileBox = fileChooser.show(); }
Close off the script tag and save the file as opensave.xul in the same location as the rdf file describing it. Open the file from inside Mozilla using its chrome url and you should get your simple menu bar and simple menu. Selecting the Open will open the Select a File to open dialog box, and selecting Save will open the Select a Location to save dialog box. The functionality to actually open or save files requires far more code and won’t be discussed here. Once you’re done, choose close on your menu and Mozilla should exit.