Visit Mozilla.org

XUL Tutorial:Creating a Window

Материал из MDC.



На страницах этого руководства мы постепенно соберем диалоговое окошко поиска файлов.

Сперва познакомимся с базовым синтаксисом XUL файла.

Содержание

[править] Создаем XUL файл

Файлу можно дать любое имя, однако, оно долно иметь расширение «.xul». Структура простейшего XUL файла может быть такой:

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window
    id="findfile-window"
    title="Find Files"
    orient="horizontal"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<!-- Тут будут другие элементы --> 
</window>

Это окно не выполняет никаких действий, так как в нем нет ни одного элемента (их мы добавим в следующем разделе руководства). Рассмотрим код строчка за строчкой:

  1. <?xml version="1.0"?>
    Это строка просто показывает, что файл целиком состоит из XML-данных. Такая прагма должна быть первым элементом в каждом XUL-файле, так же как и в каждом XHTML файле.
  2. <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
    Здесь задается стиль, который будет применен к элементам текущего документа (в этом примере — CSS-файл). Это стандартный способ задать стилевой файл для XML-документа. В этом случае мы импортируем стили из глобальной части пакета офорления (скина). Здесь не указан конкретный файл, поэтому Mozilla сама решит, какие файлы в директории использовать. А именно будет выбран и подгружен основополагающий файл «global.css». Этот файл содержит описание внешнего вида по умолчанию всех элементов XUL. Так сделано потому, что XML никак не определяет внешний вид своих элементов. Чаще всего системный стиль подключают первым в больштнстве XUL-документов. Используя прагму <?xml-stylesheet ... ?>, вы можете подключать собственные стилевые файлы, другие системные стили, а так же стили любых расширений Мозилы. Подключить CSS-файл можно так же внутри вашего файла с помощью директивы @import. Это позволит уменьшить количество директив в заголовке XUL-документа.
  3. <window
    This line declares that you are describing a window. Each user interface window is described in a separate file. This tag is much like the BODY tag in HTML which surrounds the entire content. Several attributes can be placed in the window tag -- in this case there are four. In the example, each attribute is placed on a separate line but they do not have to be.
  4. id="findfile-window"
    The id attribute is used as an identifier so that the window can be referred to by scripts. You will usually put an id attribute on all elements. The name can be anything you want although it should be something relevant.
  5. title="Find Files"
    The title attribute describes the text that would appear on the title bar of the window when it is displayed. In this case the text 'Find Files' will appear.
  6. orient="horizontal"
    The orient attribute specifies the arrangement of the items in the window. The value horizontal indicates that items should be placed horizontally across the window. You may also use the value vertical, which means that the items are placed in a column. This is the default value, so you may leave the attribute off entirely if you wish to have vertical orientation.
  7. xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
    This line declares the namespace for XUL, which you should put on the window element to indicate that all of its children are XUL. Note that this URL is never actually downloaded. Mozilla will recognize this URL internally.
  8. <!-- Other elements go here -->
    Replace this comment block with other elements (the buttons, menus and other user interface components) to appear in the window. We'll add some of these in the next set of sections.
  9. </window>
    And finally, we need to close the window tag at the end of the file.

[править] Opening a Window

In order to open a XUL window, there are several methods that can be used. If you are only in the development stage, you can just type the URL (whether a chrome:, file: or other URL type) into the location bar in a Mozilla browser window. You should also be able to double-click the file in your file manager, assuming that XUL files are associated with Mozilla. The XUL window will appear in the browser window as opposed to a new window, but this is often sufficient during the early stages of development.

The correct way, of course, is to open the window using JavaScript. No new syntax is necessary as you can use the window.open() function as one can do for HTML documents. However, one additional flag, called 'chrome' is necessary to indicate to the browser that this is a chrome document to open. This will open the window without the toolbars and menus and so forth that a normal browser window has. The syntax is described below:

window.open(url,windowname,flags);

where the flags contains the flag "chrome" as in this example

window.open("chrome://navigator/content/navigator.xul", "bmarks", "chrome,width=600,height=300");

[править] The findfile.xul example

Let's begin by creating the basic file for the find file dialog. Create a file called findfile.xul and put it in the content directory specified in the findfile.manifest file (we've created in the previous section). Add the XUL template shown at the top of this page to the file and save it.

You can use the command-line parameter '-chrome' to specify the XUL file to open when Mozilla starts. If this is not specified, the default window open will open. (Usually the browser window.) For example, we could open the find files dialog with either of the following:

mozilla -chrome chrome://findfile/content/findfile.xul 
 
mozilla -chrome resource:/chrome/findfile/content/findfile.xul

If you run this command from a command-line (assuming you have one on your platform), the find files dialog will open by default instead of the Mozilla browser window. Of course, because we haven't put any UI elements in the window, you won't see a window appear. We'll add some elements in the next section.

To see the effect though, the following will open the bookmarks window:

mozilla -chrome chrome://communicator/content/bookmarks/bookmarksManager.xul

If you are using Firefox, try below.
firefox -chrome chrome://browser/content/bookmarks/bookmarksManager.xul

The '-chrome' argument doesn't give the file any additional privileges. Instead, it causes the specified file to open as a top-level window without any browser chrome, such as the address field or menu. Only chrome URLs have additional privileges.

The Extension Developer's Extension contains an XUL editor that allows you to type in XUL code and see the results in real-time from within Mozilla!

[править] Troubleshooting

  • If the XUL window fails to show up on the desktop but has an icon on the desktop tool bar, check the xml-stylesheet declaration. Make sure that you have included the stylesheet correctly:
 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

In the next section, we will add some buttons to the window.