Documentation/DevGuide/LibreOffice Basic


 * First Steps with LibreOffice Basic guides you through the necessary steps to write LibreOffice Basic UNO Programs.
 * LibreOffice Basic IDE provides a reference to the functionality of the LibreOffice Integrated Development Environment (IDE). It describes:
 * The dialogs to manage Basic and dialog libraries.
 * The functionality of the Basic IDE window: the Basic macro editor and debugger, and the Dialog editor.
 * The assignment of macros to events
 * Features of LibreOffice Basic describes the Basic programming language integrated in LibreOffice, including
 * Provides an overview about the general language features built into LibreOffice Basic.
 * Extends the UNO language binding chapter LibreOffice Basic by information on how to access the application specific UNO API.
 * Points out threading and rescheduling characteristics of LibreOffice Basic that differ from other languages, such as, from Java, which can be important under certain circumstances.
 * Advanced Library Organization describes how the Basic library system stores and manages Basic macros and dialogs in LibreOffice, and how the user can access libraries and library elements using the appropriate interfaces.
 * Programming Dialogs and Dialog Controls describes the toolkit controls used to create dialogs in the dialog editor. In this section the different types of controls and their specific properties are explained in detail.
 * Creating Dialogs at Runtime describes how UNO dialogs can be created at runtime without using the dialog editor. This is useful to show dialogs from UNO components. As this is an advanced way to create dialogs, this section goes deeply into the Toolkit interfaces and extends the section Programming Dialogs and Dialog Controls.
 * Library File Structure discusses the various files used by the Basic IDE.
 * Library Deployment discusses the automatic deployment of Basic libraries into a local or a shared LibreOffice installation.

Step By Step Tutorial
This section provides a tutorial to enable developers to use the Basic IDE. It describes the necessary steps to write and debug a program in the Basic IDE, and to design a Basic dialog. A comprehensive reference of all tools and options can be found at LibreOffice Basic IDE.

Creating a Module in a Standard Library

 * 1) Create a new Writer document and save the document, for example, FirstStepsBasic.odt.
 * 2) Click.

The LibreOffice Basic Macros dialog appears. The Macro from list shows macro containers where Basic source code (macros) can come from. There is always a My Macros and a OpenOffice Macros container for Basic libraries. Additionally, each loaded document can contain Basic libraries.



The illustration above shows that the document FirstStepsBasic.odt is the only document loaded. Therefore, the My Macros, OpenOffice Macros and FirstStepsBasic.odt containers are displayed in the illustration above. Both containers, My Macros and FirstStepsBasic.odt, contain a library named Standard. The OpenOffice Macros container contains the libraries that come with a default LibreOffice installation – most of them are AutoPilots. The Standard libraries of the application and for all open documents are always loaded. They appear enabled in the dialog. Other libraries have to be loaded before they can be used.

The libraries contain modules with the actual Basic source code. Our next step will create a new module for source code in the Standard library of our FirstStepsBasic.odt document.


 * 1) Scroll to the document node FirstStepsBasic.odt in the Macro from list.
 * 2) Select the Standard entry below the document node and click New.

LibreOffice shows a small dialog that suggests to create a new module named Module1.


 * 1) Click  to confirm.

The Basic source editor window appears containing a Sub (subroutine) Main.



The status bar of the Basic editor window shows that the Sub Main is part of FirstStepsBasic.Standard.Module1. If you click in the Basic editor, you will see that LibreOffice created a module Module1 below the Standard library in FirstStepsBasic.odt.



When a module is selected, the Macro name list box on the left shows the Subs and Functions in that module. In this case, Sub Main. If you click while a Sub or Function is selected, the Basic editor opens and scrolls to the selected Sub or Function.

Writing and Debugging a Basic UNO program
Enter the following source code in the Basic editor window. The example asks the user for the location of a graphics file and inserts it at the current cursor position of our document. Later, the example will be extended by a small insert graphics autopilot.

If help is required on Basic keywords, press F1 while the text cursor is on a keyword. The LibreOffice online help contains descriptions of the Basic language as supported by LibreOffice.

Starting with the line oDoc = ThisComponent, where the document model is accessed, we use the UNO integration of LibreOffice Basic. ThisComponent is a shortcut to access a document model from the Basic code contained in it. Earlier, you created Module1 in FirstStepsBasic.odt, that is, your Basic code is embedded in the document FirstStepsBasic.odt, not in a global library below the My Macros container. The property ThisComponent therefore contains the document model of FirstStepsBasic.odt.

To observe the values of Basic variables during debugging, enter a variable name in the Watch field of the Basic editor and press the key to add the watch, or point at a variable name with the mouse cursor without clicking it. In the example below, we can observe the variables sGraphicUrl and oGraphicObject :



Since OpenOffice.org 2.0.0 it is also possible to inspect the values of UNO objects in the Basic debugger during runtime.

Calling a Sub from the User Interface
A Sub can be called from customized icons, menu entries, upon keyboard shortcuts and on certain application or document events. The entry point for all these settings is the Customize dialog accessible through the button in the Macro dialog or the  command.

To assign the Sub Main to a toolbar icon, select and click the Toolbars tab. The Toolbars tab looks like this:



Click the button in the Toolbars tab. In the Add Commands dialog that pops up, scroll down the Category list until you see the Application Macros node. Expand it and the FirstStepsBasic.odt node. Navigate to the Module FirstStepsBasic.Standard.Module1 and select it. When Module1 is selected, the Commands list shows an entry "Main" for the Sub Main in Module1. Clicking will add it to a toolbar.

You can now click the new toolbar item to launch the example macros.

The section Assigning Macros to GUI Events describes other options to make your Sub accessible from the user interface.

Creating Dialogs
To create a dialog in the Basic IDE, right-click the Module1 tab at the bottom of the Basic source editor and select. The IDE creates a new page named Dialog1:



Our dialog shall offer a more convenient way to select a file than the simple input box of our first example. Furthermore, the user shall be able to control how the picture is anchored in the text after inserting it. For this, we will create a wizard dialog with two steps.

Now the dialog looks similar to the illustration below:



To edit the dialog, such as setting the title and changing the size, select it by clicking the outer border of the dialog. Green handles appear around the dialog. The green handles can be used to alter the dialog size. The Properties Dialog is used to define a dialog title and other dialog properties.

Adding Event Handlers
Now we will write code to open the dialog and add functionality to the buttons. To show a dialog, create a dialog object using createUnoDialog and call its execute method. A dialog can be closed while it is shown by calling endExecute.

To add functionality to GUI elements, develop Subs to handle GUI events, then hook them to the GUI elements. To add functionality to the buttons of our dialog, click the Module1 tab in the lower part of the Basic IDE and enter the following Subs above the previous Sub Main to open, close and process the dialog. Note that a Private variable oDialog is defined outside the Subs. After loading the dialog, this variable is visible from all Subs and Functions of Module1.

Select the Cancel button in our dialog in the dialog editor, and click the Events tab of the Properties Dialog, then click the ellipsis button on the right-hand side of the Event Execute action. As shown in the next illustration the Assign Action dialog appears.



In the Assign Action dialog press the button to open the Macro Selector dialog shown in the illustration below. Navigate to FirstStepsBasic.Standard.Module1, select the Sub CancelGraphicsDialog and press the button to link this sub to the wizard dialog's Cancel button.



The next illustration shows how the new assignment is shown in the Assign Action dialog.



Pressing the OK button in the Assign Action dialog finishes the assignment process.

Using the same method, hook the Finish button to FinishGraphicsDialog.

AutoPilot Dialogs
The final step is to create a small AutoPilot with two pages. The LibreOffice Dialogs have a simple concept for AutoPilot pages. Each dialog and each control in a dialog has a property Page (Step) to control the pages of a dialog. Normally, dialogs are on page 0, but they can be set to a different page, for example, to page 1. All controls having 1 in their Page property are visible as long as the dialog is on page 1. All controls having 2 in their page property are only displayed on page 2 and so forth. If the dialog is on Page 0, all controls are visible at once. If a control has its Page property set to 0, it is visible on all dialog pages.

This feature is used to create a second page in our dialog. Hold down the key, and click the label and file control in the dialog to select them. In the Properties Dialog, fill in 1 for the Page property and press Enter to apply the change. Next, select the dialog by clicking the outer rim of the dialog in the dialog editor, enter 2 for the Page property and press the key. The label and file control disappear, because we are on page 2 now. Only the buttons are visible since they are on page 0.

On page 2, add a label "Anchor" and two option buttons "at Paragraph" and "as Character". Name the option buttons  and , and toggle the State property of the   button, so that it is selected by default. The new controls automatically receive 2 in their Page property. When page 2 is finished, set the dialog to page 1 again, because we want it to be on page 1 on startup.



The Subs below handle the and  buttons, and the Sub   has been extended to anchor the new graphics selected by the user. Note that the property that is called Page (Step) in the GUI, is called Step in the API.

LibreOffice Basic IDE
This section discusses all features of the Integrated Development Environment (IDE) for LibreOffice Basic. It shows how to manage Basic and dialog libraries, discusses the tools of the Basic IDE used to create Basic macros and dialogs, and it treats the various possibilities to assign Basic macros to events.

Managing Basic and Dialog Libraries
The main entry point to the library management UI is the menu item. This item activates the LibreOffice Basic Macros dialog where the user can manage all operations related to Basic and dialog libraries.

LibreOffice Basic Macros Dialog
The following picture shows an example macro dialog. From here you can run, create, edit and delete macros, assign macros to UI events, and administer Basic libraries and modules.



Displayed Information
The tree titled with Macro from shows the complete library hierarchy that is available the moment the dialog is opened. See Advanced Library Organization for details about the library organization in LibreOffice.

Unlike the library organization API, this dialog does not distinguish between Basic and dialog libraries. Usually the libraries displayed in the tree are both Basic and dialog libraries.

The tree titled Macro from represents a structure consisting of three levels:

Library container -> library -> library element


 * The top-level nodes represent the application Basic and dialog library container (nodes  and  ). For each opened document, the document's Basic and dialog library container (see Advanced Library Organization). In the example two documents are open, a text document called Description.odt and a spreadsheet document named Calculation.ods.
 * In the second level, each node represents a library. Initially all libraries, except the default libraries named, are not loaded and grayed out. To load a library, the user double-clicks the library. In the example above, the   root element contains the   library, already loaded by default.
 * The third level in the tree is visible in loaded libraries. Each node represents a library element that can be modules or dialogs. In the LibreOffice Basic Macros dialog, only Basic modules are displayed as library elements, whereas dialogs are not shown. By double-clicking a library the user can expand and condense a library to show or hide its modules. In the example, the  library is displayed expanded. It contains two modules,   and  . The document Description.odt contains a   library with one Basic module  . Calculation.ods contains a   library without Basic modules. All libraries, respectively their dialog library part, may also contain dialogs that cannot be seen in this view.

If a library is password-protected and a user double-clicks it to load it, a dialog is displayed requesting a password. The library is only loaded and expanded if the user enters the correct password. If a password-protected library is loaded using the API, for example, through a call to, it is displayed as loaded, not grayed out, but it remains condensed until the correct password is entered (see Advanced Library Organization).

The middle column contains information about the macros, that is, the Subs and Functions, in the libraries. In the list box at the bottom, all Subs and Functions belonging to the module selected in the tree are listed. In the edit field titled Macro name, the Sub or Function currently selected in the list box is displayed. If there is no module selected in the tree, the edit field and list are empty. You can type in a desired name in the edit field.

Buttons
On the right-hand side of the LibreOffice Basic Macros dialog, there are several buttons. The following list describes the buttons:


 * Run
 * Executes the Sub or Function currently displayed in the Macro name edit field. The LibreOffice Basic Macros dialog is closed, before the macro is executed.


 * Close
 * Closes the LibreOffice Basic Macros dialog without any further action.


 * Assign
 * Opens the Customize dialog that can also be opened using Tools - Customize. This dialog can be used to assign Basic macros to events. For details see Assigning Macros to GUI Events below.


 * Edit
 * Loads the module selected in the tree into the Basic macro editor. The cursor is placed on the first line of the Sub or Function displayed in the Macro name edit field. See chapter Basic IDE Window below for details about the Basic macro editor. This button is disabled if there is no module selected in the tree or no existing Sub or Function displayed in the Macro name edit field.


 * Delete
 * This button is only available if an existing Sub or Function is displayed in the Macro name edit field. The Delete button removes the Sub or Function displayed in the Macro name edit field from the module selected in the module selected in the tree.


 * New
 * This button is only available if no existing Sub or Function is displayed in the Macro name edit field. The New button inserts a new Sub into the module selected in the tree. The new Sub is named according to the text in the Macro name edit field. If Macro name is empty, the Sub is automatically named Macro1, Macro2, and so forth.


 * Organizer
 * This button opens the LibreOffice Basic Macro Organizer dialog box that is explained in the next section.


 * Help
 * Starts the LibreOffice help system with the Macros topic.

LibreOffice Basic Macro Organizer Dialog
This dialog is opened by clicking the Button Organizer in the LibreOffice Basic Macros dialog. The dialog contains the tab pages Modules, Dialogs and Libraries. While the LibreOffice Basic Macros dialog refers to Subs and Functions inside Basic modules, such as run Subs, delete Subs, and insert new Subs, this dialog accesses the library system on module (tab page Modules), dialog (tab page Dialogs) and library (tab page Libraries) level.

Modules
Illustration 12.13 shows the LibreOffice Basic Macro Organizer dialog with the Modules tab page activated. The list titled Module is similar to the Macro from list in the Macro dialog, but it contains the complete library hierarchy for the LibreOffice application libraries and the document libraries. The libraries are loaded, and condensed or expanded by double-clicking the library. The illustration shows the application library Standard containing two modules, Module1 and Module2.



The illustration above shows that two documents are loaded. The illustration shows a library  in document Description.odt containing a module named , and another library   in document Calculation.ods containing no Basic module.

The following list describes the buttons on the right side of the dialog:


 * Edit
 * Loads the module selected in the tree into the Basic macro editor. If a module is not selected, this button is disabled.


 * Close
 * Closes the LibreOffice Basic Macro organizer dialog without any further action.


 * New Module
 * Opens a dialog that allows the user to type in the desired name for a new module. The name edit field initially contains a name like Module, such as Module1 and Module2, depending on the modules already existing. Clicking the OK button adds the new module as a new item in the Module list. The New Module button is disabled if the selected library has read-only status.


 * Delete
 * Deletes the selected module. This button is disabled if no module is selected, or if the selected module belongs to a library with read-only status.

Dialogs
The illustration below shows the LibreOffice Basic Macro Organizer dialog with the Dialogs tab page activated. The illustration shows the application library  containing two dialogs, Dialog1 and Dialog2.



The illustration shows a library  in document Calculation.ods containing a dialog named , and another library   in document Description.odt containing no dialog.

The following list describes the buttons on the right side of the dialog:


 * Edit
 * Loads the dialog selected in the tree into the Dialog editor. The section Dialog Editor below describes the Dialog Editor in more detail. If a dialog is not selected, this button is disabled.


 * Close
 * Closes the LibreOffice Basic Macro organizer dialog without any further action.


 * New Dialog
 * Opens a dialog that allows the user to enter the desired name for a new dialog. The name edit field initially contains the name Dialog, such as Dialog1 and Dialog2, depending on the dialogs already existing. Clicking the OK button creates the dialog in the Dialog list. This button is disabled if the selection contains a library with read-only status.


 * Delete
 * Deletes the selected dialog. This button is disabled if no dialog is selected, or if the selected dialog belongs to a library with read-only status.

Libraries
The following illustrations show the LibreOffice Basic Macro Organizer dialog with the Libraries tab page activated. In this dialog, the application and document libraries are listed separately. The Library list only contains the libraries of the library container currently selected in the Location list box. The second illustration is dropped down showing the My Macros & Dialogs and OpenOffice Macros & Dialogs entries and the two open documents.





The libraries are displayed in the following manner:


 * Regular libraries are displayed in black.
 * Libraries with read-only status are grayed out.
 * Library links are followed by an URL indicating the location where the library is stored. In the example above, all libraries except for Standard and Library1 are library links and all library links have read-only status.
 * Password protected libraries are indicated with a key symbol before the name. In the example, only Library1 is password protected.

Clicking a library twice (not double-click) allows the user to rename it.

The following list describes the buttons on the right side of the dialog:


 * Edit
 * Loads the first module of the library selected in the Library list box into the Basic macro editor (see Basic Source Editor and Debugger below). If the library only contains dialogs, the first dialog of the corresponding dialog library is displayed in the Dialog editor (see Dialog Editor below). If the Basic/Dialog editor window does not exist, it is opened.


 * Close
 * Closes the LibreOffice Basic Macro Organizer dialog without any further action.


 * Password
 * Opens the Change Password dialog displayed in the next illustration for the library currently selected in the Library list box.


 * This dialog is used to change the password if the library is already password protected. Enter the old password first, then the new password twice.


 * If the library is not password protected, the Old password edit field is disabled. The new password is entered twice in the New password section. Clicking OK activates the password protection if both passwords match.


 * [[Image:PasswordDialog.png|none|thumb|410px|The Change Password dialog]]


 * New
 * Opens a dialog allowing the user to enter the name for a new library. The name edit field initially contains the name Library, such as Library1 and Library2, depending on the libraries already existing. Clicking the OK button creates the library and adds it to the Library list. A new library is always created as a Basic and dialog library.


 * Import
 * This button is used to import additional libraries into the library container that is selected in the Location list box. The button opens a file dialog where the user selects the location where the library is imported from. The following types of files can be selected:
 * Library container index files (script.xlc or dialog.xlc)
 * Library index files (script.xlb or dialog.xlb)
 * LibreOffice documents (e.g. *.odt, *.ods, *.sxw, *.sxc, *.sdw, *.sdc)
 * Star Office 5.x and previous Basic library files (*.sbl)


 * After selecting a file, an Import library dialog is displayed. The next illustration shows the dialog after selecting a library index file script.xlb. The dialog displays all libraries that are found in the chosen file. In this example, only the library Euro appears, because the file script.xlb only represented this library.


 * [[Image:AppendLibraries_Library.png|none|thumb|334px|The Import Libraries dialog]]


 * The checkboxes in the Options section, when selected, indicates if a library is inserted as a read-only link and if existing libraries with the same name are replaced by the new library.


 * The next illustration shows the dialog after selecting the writer document LibraryImportExample. This document contains the four libraries Standard, Library1, Library2 and Library3. The illustration shows that the libraries Library1 and Library2 are selected for import. The Insert as reference (read-only) option is disabled, because the libraries inside documents cannot be referenced as a link. As well, StarOffice 5.x Basic library files can not be linked.


 * [[Image:AppendLibraries_Document.png|none|thumb|334px|The Import Libraries dialog with selected libraries]]


 * Clicking the OK button imports the selected libraries into the library container that was previously selected in the Location list box, including the Basic and dialog libraries.


 * Export
 * This button is used to export a library. The Standard library cannot be exported. Clicking the button displays the Export Basic library dialog.


 * [[Image:ExportLibrary.png|none|thumb|230px|The Export Basic Library dialog]]


 * This dialog allows to chose between two export formats. Choosing Export as package and clicking OK opens the Export library as package file dialog allowing to save the library in the UNO package bundle format that can be easily imported from other LibreOffice installations using the Package Manager available in the Tools menu. So this format should be used for deploying Basic libraries.


 * [[Image:ExportLibrary_Package.png|none|thumb|400px|The Export library as package dialog]]


 * Choosing Export as BASIC library in the Export Basic library dialog opens the Export as BASIC library dialog allowing to choose a location where the library will be stored as folder named like the library. This format can be accessed with the Import functionality described above.


 * [[Image:ExportLibrary_Basic.png|none|thumb|400px|The Export as BASIC library dialog]]


 * The exported libraries always contain both Basic Modules and Dialogs.


 * Delete
 * Deletes the item selected in the Library list box. If the item represents a library link, only the link is removed, not the library itself. The Delete button appears disabled whenever a Standard library is selected, because Standard libraries cannot be deleted.

Basic IDE Window
The LibreOffice IDE is mainly represented by the Basic IDE window. The IDE window has two different modes:


 * The Basic editor mode displays and modifies Basic source code modules to control the debugging process and display the debugger output
 * The dialog editor mode displays and modifies dialogs.

Basic source code and dialogs are never displayed at the same time. The IDE window is in Basic editor or debugger, or in dialog editor mode. The following illustration shows the Basic IDE window in the Basic editor mode displaying Module2 of the application Standard library.



The IDE window control elements common to the Basic editor and dialog editor mode are described below. The mode specific control elements are described in the corresponding subchapters Basic Source Editor and Debugger and Dialog Editor:


 * Clicking the Printer button in the main toolbar prints the displayed Basic module or dialog directly without displaying a printer dialog.
 * The Save button in the main toolbar behaves in two different ways depending on the library currently displayed in the IDE window.
 * If the library belongs to the application library container, the Save button saves all modified application libraries.
 * If the library belongs to a document, the Save button saves the document.
 * On the left-hand side of the toolbar, a Library list box shows the currently displayed library. The user can also modify the displayed library. In the example above, the Standard library of the application Basic ([My Macros & Dialogs].Standard) is displayed. The list box contains all the application and document libraries that are currently accessible. The user can select one to display it in the IDE window.
 * The tabs at the bottom of the IDE window indicate all the modules and dialogs of the active library. Clicking one of these tabs activates the corresponding module or dialog. If necessary, the IDE window switches from Basic editor to dialog editor mode or conversely. Right-clicking a tab opens a context menu:
 * Insert opens a sub menu to insert a new module or dialog.
 * Delete deletes the active module or dialog after confirmation by the user.
 * Rename changes the name of the active module or dialog.
 * Hide makes the active module or dialog invisible. It no longer appears as a tab flag, thus it cannot be activated. To activate, access it directly using the LibreOffice Basic Macros or LibreOffice Basic Macro Organizer dialog and clicking the Edit button.
 * Modules opens the LibreOffice Basic Macro Organizer dialog.
 * The status bar displays the following information:
 * The first cell on the left displays the fully qualified name of the active module or dialog in the notation.
 * The second cell displays an asterisk " " indicating that at least one of the libraries of the active library container has been modified and requires saving.
 * The third cell displays the current position of the cursor in the Basic editor window.
 * The fourth cell displays "INSRT" if the Basic editor is in insertion mode and "OVER" if the Basic editor is in overwrite mode. The modes are toggled with the Insert key.

Basic Source Editor and Debugger
The Basic editor and debugger of the IDE window is shown when the user edits a Sub or Function from the Tools - Macros - Organize Macros - LibreOffice Basic dialog. In this mode, the window contains the actual editor main window, debugger Watch window to display variable values and the debugger Calls window to display the Basic call stack. The Watch and Calls windows are only used when a Basic program is running and halted by the debugger.

The editor supports common editor features. Since the editor is only used for the LibreOffice Basic programming language, it supports a Basic syntax specific highlighting and help for Basic keywords.



The following list explains the functionality of the macro toolbar buttons.

Illustration 12.24: Basic Editor and Debugger shows how the IDE window looks while a Basic program is executed in debugging mode.


 * The Stop button is enabled.
 * A breakpoint is set in line 11.
 * The execution is halted in line 12. The current position is marked by a yellow arrow.
 * The Watch window contains the entries Value and Hello, and displays the current values of these variables. Values of variables can also be evaluated by touching a corresponding identifier in the source code with the cursor.
 * The Calls window shows the stack. The currently executed Sub doIt is displayed at the top and the Sub Main at the second position.

Dialog Editor
This section provides an overview of the Dialog editor functionality. The controls that are used to design a dialog are not explained. See Programming Dialogs and Dialog Controls for details on programming these controls. The dialog editor is activated by creating a new dialog, clicking a dialog tab at the bottom of the IDE window, or selecting a dialog in the LibreOffice Basic Macro Organizer dialog and clicking the Edit button.

Initially, a new dialog consists of an empty dialog frame. The next illustration shows Dialog2 of the application Standard library in this state.



In the dialog editor mode, the Controls button is enabled and the illustration shows the result by clicking this button. A small toolbar with dialog specific tools is displayed. The buttons in this toolbar represent the types of controls that can be inserted into the dialog. The user clicks the desired button, then draws a frame with the mouse at the position to insert the corresponding control type.

The following three buttons in the dialog tools window do not represent controls:



The illustration above shows that the dialog tool window can be pulled from the main toolbar by dragging the window at its caption bar after opening it.

The Properties dialog has two tabs. The General tab, visible in Illustration 12.26, contains a list of properties. Their values are represented by a control. For most properties this is a list box, such as color and enum types, or an edit field, such as numeric or text properties. For more complex properties, such as fonts or colors, an additional ellipsis button opens another type of dialog, for example, to select a font. When the user changes a property value in an edit field this value is not applied to the control until the edit field has lost the focus. This is forced with the tab key. Alternatively, the user can commit a change by pressing the Enter key.

The Events tab page displays the macros assigned to the events supported by the selected control:



In the example above, a macro is assigned to the Key pressed event: When this event occurs, the displayed Sub  in Module2 of the application Basic library   is called. The events that are available depend on the type of control selected.

To change the event assignment the user has to click one of the ellipsis buttons to open the Assign Action dialog displayed in the illustration below.



The list box titled Event displays the same information as the Events tab of the Properties dialog. The Assign Action dialog is always the same, that is only the selected event in its Event list changes according to the ellipsis button the user selected on the Events tab of the Properties dialog.

To assign a macro to an event, the user needs to click on the Macro ... button. This opens the Macro Selector dialog which allows the user to select a macro from the library hierarchy. Clicking OK in the Macro Selector assigns the selected macro to the event. If another macro is already assigned to an event, this macro is replaced. If no Sub is selected, the OK button is disabled.

If the dialog is stored in a document, the library hierarchy displayed in the Macro Selector dialog contains the application library containers and the library container of the document. If the dialog belongs to an application dialog library, document macros are not displayed since they cannot be assigned to the controls of application dialogs. This is because it cannot be guaranteed that the document will be loaded when the application dialog event is fired.

The Remove button is enabled if an event with an assigned macro is selected. Clicking this button removes the macro from the event, therefore the event will have no macro binding.

The list box below the Remove button is used to select different macro languages. Currently, only LibreOffice Basic is available.

The OK button closes the Assign Action dialog, and applies all event assignments and removals to the control. The changes are reflected on the Events tab of the Properties dialog.

The Cancel button also closes the Assign Action dialog, but all assignment and removal operations are discarded.

As previously explained, it is also possible to select several controls simultaneously. The next picture shows the situation if the user selects both CommandButton1 and CheckBox1. For the Properties dialog such a multi selection has some important effects.



Here the caption of the Properties contains the string  to point out the special situation. The two important differences compared to the single selection situation are:


 * The displayed properties are an intersection of the properties of all the selected controls, that is, the property is only displayed if all the selected controls support that property. A property value is only displayed if the value is the same for all selected controls. All selected controls are effected when a value is changed by the user. Values that are not the same for all controls can be set with the effect that the specified value applies to all controls in the selection.
 * A multi-selection Properties dialog does not have an Events tab. Events can only be specified for single controls.

Assigning Macros to GUI Events
The functionality to assign macros to control events in the dialog editor was discussed earlier. There is also a general functionality to assign macros or other actions to events. This functionality can be accessed through the Customize dialog that is opened using Tools – Customize or by clicking the Assign button in the Macro dialog. In this section, only the assignment of macros is discussed. For more information about this dialog, refer to the LibreOffice documentation.

The next illustration shows the Menu tab of the Customize dialog



The illustration above shows how a macro is assigned to a new menu item. The Menu and Menu Content list boxes can be used to navigate the LibreOffice menu hierarchy. Clicking the Add... button opens the Add Commands dialog. The Category list box in the Add Commands dialog contains entries for built-in LibreOffice functions, and a OpenOffice Macros entry that represents the hierarchy of LibreOffice macros. When an entry is selected in the Category list box, any commands or macros it contains are displayed in the Commands list box on the right.

Clicking the Add button in the Add Commands dialog adds the selected command or macro to a menu.

The other buttons in the Menus tab of the Customize dialog are as follows:


 * The New button creates a new top level menu
 * The Menu button has commands for moving, renaming and deleting top level menus
 * The Modify button has commands for adding submenus and separators, and renaming and deleting menu items.
 * The arrow buttons change the position of a menu item.
 * The Reset button restores the default menu configuration.

The next illustration shows the Events tab of the Customize dialog:



On this tab, macros can be assigned to general events in LibreOffice. The events are listed in the list box titled Event. The Assign button opens the Macro Selector from which the user can select macros to assign to events. The Remove button removes the assigned macro from the selected event.

In the Keyboard tab macros are accessed in Category and Function list boxes, then assigned to a shortcut key that can be specified in the Shortcut keys list box. There are also Load, Save, and Reset buttons for loading, storing and resetting keyboard configurations.

The Keyboard tab contains OpenOffice and Document radio buttons which control the scope for which keyboard assignments are made.

Dialog Localization
Beginning with OpenOffice.org 2.2.0 it is possible to localize dialogs created in the Dialog Editor. The localization always refers to complete Dialog Libraries, not to single dialogs. A Dialog Library's default state is “Not localized”. In this state dialogs behave and are stored in the same way as before the localization feature was available.

The entry point for localizing a Dialog Library is the Manage User Interface Languages dialog that can be opened by clicking the Manage Language button in the dialog tool window. The following illustration shows the dialog editor with an opened Manage User Interface Languages dialog.



Initially no language is defined, so the Present Languages list has no entry. The dialog captions shows that the localization refers to the complete library Standard. To enable localization for this library the Add... button has to be used. It opens another dialog allowing to choose the first language to be supported (see the next illustration). The currently active UI language is preselected.



After choosing a language and clicking the OK button this language becomes the only entry in the Present Languages list of the Manage User Interface Languages dialog:



The first language also becomes the first default language. As stated in the comment on the dialog itself the Default language is relevant in two situations.


 * If a dialog does not support the language that is required the strings for the default language will be displayed. Example: A dialog supports English and French with English being the Default Language. If this dialog is used with German being the Office's user interface language, English strings will be displayed.
 * When a new language is added, all strings are taken from the default language. Example: A button label is “Thanks” for English and “Merci” for French with English being the default language. When adding German as another language the label initially will also be “Thanks”. The idea behind this behavior is that a user creating a localized dialog will usually like to take his own mother language or a common language like English as reference for translating to any other language.

Now - or any time later - other languages can be added by again clicking the Add... button. This time a slightly different dialog is used:



It allows to choose more than one language. As also described in the comment on the dialog the strings for the new languages will be copied from the current default language. After checking one or more languages and clicking the OK button these languages also become entries in the Present Languages list of the Manage User Interface Languages dialog:



The default language can be changed by selecting another language and clicking the Default button. One or more languages can be deleted by selecting them and clicking the Delete button. As deleting a language also deletes all strings associated with this language this action will only be completed after a corresponding warning message has been acknowledged by the user. If the Default Language is deleted the first of the remaining languages will become Default Language.

If all languages are deleted the Library will return to the “not localized” state. The Resource IDs (see Technical Background) stored in the localizable dialog/control properties will be replaced by the corresponding strings assigned to the last Default Language.

If a Dialog Library is localized an additional Language toolbar is visible. It allows to select the current language as shown in the next illustration. Besides the List Box containing the Languages another Manage Language button is placed allowing to open the Manage User Interface Languages dialog also from the Language toolbar.



All localizable dialog/control strings are displayed for this current language. So the button label in the illustration is “English” if English is selected as current language, but it can be different for the other languages. If a localized property is changed using the Properties Dialog this change also is only related to the current language. The next illustration shows how the dialog could look after switching the current language to French.



The following list shows which dialog/control properties are localizable at all:


 * (Button, Check Box, Option Button)
 * (Text Box, Combo Box)
 * (List Box, Combo Box)
 * (Dialog)
 * (Currency Field)
 * (all controls)

Currently, the localization is limited to strings that are visible in the dialog or that could become visible in another context like the help text.

Technical Background
This section provides an overview of how the Dialog Localization feature works internally and how the resources are stored. In case of a localized Dialog Library the localized properties do not contain strings but Resource IDs referring to a String Resource table. Example:

Dialog XML snippet, not localized:

Dialog XML snippet, localized:

"&amp;" is the XML encoding for the & character. This character is used as escape character marking the string as localized. The pure Resource ID is  respectively.

The strings referenced by the Resource IDs are stored in files meeting the format of Java properties files, e.g. described in https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html. In the Library's folder one of these files is stored for each language following a special naming scheme. For the languages used in the example above the following files are stored in the Dialog Library's folder (both for Application based libraries stored in the file system and for Document based libraries stored in a document's package file):

Dialog1.xdl                    // Dialog XML description DialogStrings_en_US.properties // English (USA) properties file DialogStrings_et_EE.properties // Estonian properties file DialogStrings_fr_FR.properties // French properties file DialogStrings_en_US.default    // Empty file marking English (USA) as default language

Each of these files contain all strings for the corresponding language using the Resource IDs as keys. The French properties file for the dialog shown in the last illustration looks like this:

# Strings for Dialog Library Standard 0.Dialog1.HelpText=1.Dialog 1.Title=French Dialog 2.Dialog1.CommandButton1.HelpText= 3.Dialog1.CommandButton1.Label=French 4.Dialog1.CheckBox1.HelpText= 5.Dialog1.CheckBox1.Label=French Box1 6.Dialog1.CheckBox2.HelpText= 7.Dialog1.CheckBox2.Label=French Box2 8.Dialog1.ListBox1.HelpText= 9.ListBox1.StringItemList=French List Entry1 10.ListBox1.StringItemList=French List Entry2 11.ListBox1.StringItemList=French List Entry3

The IDs start with a numeric part that is unique for the complete library. The textual part following then contains the Dialog, Control and Property name the Resource ID refers to. The numeric ID alone would be unique but the textual part makes it easier to associate Resource IDs and controls when resource properties files should be edited manually. When the dialog or controls are renamed the Resource IDs are renamed accordingly.

The UNO API used for managing the String Resource is placed in com.sun.star.resource. Each Dialog Library supports com.sun.star.resource.XStringResourceSupplier, giving access to a com.sun.star.resource.StringResource component. This component supports com.sun.star.resource.XStringResourceResolver, allowing to resolve strings using Resource IDs as keys and com.sun.star.resource.XStringResourceManager , allowing to add and remove strings and languages.

In case of an Application Dialog Library the StringResource supports com.sun.star.resource.StringResourceWithLocation allowing to read/write the properties files from/to the file system. In case of a Document Dialog Library the StringResource supports com.sun.star.resource.StringResourceWithStorage allowing to read/write the properties files from/to the document's package file.

Further details are described in the IDL documentation.

Features of LibreOffice Basic
This section provides a general description of the Basic programming language integrated in LibreOffice.

Functional Range Overview
This section outlines the functionality provided by LibreOffice Basic. The available runtime library functions are also described. The functionality is based upon the Basic online help integrated in LibreOffice, but limited to particular functions. Use the Basic online help to obtain further information about the complete Basic functionality.

Apart from the LibreOffice API, LibreOffice Basic is compatible to Visual Basic.

Screen I/O Functions
Basic provides statements and functions to display information on the screen or to get information from the user:


 * The  statement displays strings or numeric expressions in a dialog. Multiple expressions are separated by commas that result in a tab distance between the expressions, or semicolons that result in a space between the expressions. For example:


 * The MsgBox function displays a dialog box containing a message. Additionally, the caption of the dialog, buttons, such as OK, Cancel, Yes and No, and icons, such as question mark and exclamation mark, that are to be displayed are specified. The result then can be evaluated. For example:


 * The  function displays a prompt in a dialog where the user can input text. The input is assigned to a variable. For example:

File I/O
LibreOffice Basic has a complete set of statements and runtime functions to access the operating system's file system that are compatible to Visual Basic. For platform independence, the ability to handle file names in  URL notation has been added.

It is not recommended to use this classic Basic file interface in the UNO context, because many interfaces in the LibreOffice API expect file I/O specific parameters whose types, for example, com.sun.star.io.XInputStream are not compatible with the classic Basic file API.

For programming, the file I/O in LibreOffice API context with the service com.sun.star.ucb.SimpleFileAccess should be used. This service supports the interface com.sun.star.ucb.XSimpleFileAccess2, including the main interface com.sun.star.ucb.XSimpleFileAccess that provides fundamental methods to access the file system. The methods are explained in detail in the corresponding interface documentation. The following list provides an overview about the operations supported by this service:


 * copy, move and remove files and folders (methods,  ,  )
 * prompt for information about files and folders (methods,  ,  ,  ,  ,  )
 * open or create files . These functions return objects that support the corresponding stream interfaces com.sun.star.io.XInputStream, com.sun.star.io.XOutputStream and com.sun.star.io.XStream . These interfaces are used to read and write files. The  does not have methods of its own for these operations. Additionally, these interfaces are often necessary as parameters to access methods of several other interfaces. The opened files have to be closed by calling the appropriate methods com.sun.star.io.XInputStream:closeInput  or com.sun.star.io.XOutputStream:closeOutput.
 * The  also does not have methods to ask for or set the position within a file stream. This is done by calling methods of the com.sun.star.io.XSeekable interface that is supported by the objects returned by the   methods.

Two more services are instantiated at the global service manager that extends the service com.sun.star.ucb.SimpleFileAccess by functionality specific to text files:


 * The service com.sun.star.io.TextInputStream supporting com.sun.star.io.XTextInputStream and com.sun.star.io.XActiveDataSink
 * The service is initialized by passing an object supporting  to the com.sun.star.io.XActiveDataSink:setInputStream  method, for example, an object returned by com.sun.star.ucb.XSimpleFileAccess:openFileRead.


 * Then the method com.sun.star.io.XTextInputStream:readLine and com.sun.star.io.XTextInputStream:readString  are used to read text from the input stream/file. The method com.sun.star.io.XTextInputStream:isEOF  is used to check for if the end of the file is reached. The com.sun.star.io.XTextInputStream:setEncoding  sets a text encoding where UTF-8 is the default.


 * The service com.sun.star.io.TextOutputStream supporting com.sun.star.io.XTextOutputStream and com.sun.star.io.XActiveDataSource
 * The service is initialized by passing an object supporting  to the com.sun.star.io.XActiveDataSource:setOutputStream  method, for example, an object returned by com.sun.star.ucb.XSimpleFileAccess:openFileWrite.

Then the method com.sun.star.io.XTextOutputStream:writeString is used to write text to the output stream.

Date and Time Functions
LibreOffice Basic supports several Visual Basic compatible statements and functions to perform date and time calculations. The functions are,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  , and.

The function  returns the current system date as a string and the function Time returns the current system time as a string. The other functions are not explained.

In the UNO/toolkit controls context there are two other functions. The date field control method com.sun.star.awt.XDateField:setDate expects the date to be passed as a long value in a special ISO format and the com.sun.star.awt.XDateField:getDate  returns the date in this format.

The Basic runtime function  converts a date from the internal Basic date format to the required ISO date format. Since the string date format returned by the  function is converted to the internal Basic date format automatically,   can be used directly as an input parameter for  :

The runtime function  represents the reverse operation and converts a date from the ISO date format to the internal Basic date format.

Please see also Programming Dialogs and Dialog Controls in this context.

Numeric Functions
LibreOffice Basic supports standard numeric functions, such as:


 * calculating the cosine of an angle
 * calculating the sine of an angle
 * calculating the tangent of an angle
 * calculating the arctangent of a numeric value
 * calculating the base of the natural logarithm (e = 2.718282) raised to a power
 * calculating the natural logarithm of a number
 * calculating the square root of a numeric value
 * calculating the absolute value of a numeric value
 * returning -1 if the passed numeric value is negative, 1 if it is positive, 0 if it is zero.

String Functions
LibreOffice Basic supports several runtime functions for string manipulation. Some of the functions are explained briefly in the following:

All these functions are fully compatible with VBA and all functions returning a string can be specified with a trailing $ like.
 * returns the Unicode value of the first character of its string parameter.
 * returns a string containing the character that is specified by the ASCII or Unicode value passed to the function. This function is used to represent characters, such as the carriage return code, that cannot be written in the "" notation. This is not necessary for the " character, which can be included in a string literal by simply doubling it, eg.
 * converts a numeric expression to a string in a locale-independent manner (contrary to the  function).
 * converts a string to a numeric value.
 * converts all letters in a string to lowercase. Only uppercase letters within the string are converted. All lowercase letters and nonletter characters remain unchanged.
 * converts characters in a string to uppercase. Only lowercase letters in a string are affected. Uppercase letters and all other characters remain unchanged.
 * returns the leftmost “n” characters of a string expression.
 * returns the specified portion of a string expression.
 * returns the rightmost "n" characters of a string expression.
 * removes all leading and trailing spaces of a string expression.

Specific UNO Functions
The UNO specific runtime functions,  ,  ,  ,  ,   are described in LibreOffice Basic.

Accessing the UNO API
In LibreOffice Basic, the interaction between Basic and UNO is described on an elementary level. This section describes the interface between Basic and the UNO API at the level of the LibreOffice application.

This is realized by two predefined Basic properties:



The property  gives access to the global LibreOffice application API while the property   accesses the document related API.

StarDesktop
The property  is a shortcut for the service com.sun.star.frame.Desktop.

Example:

The displayed message box differs slightly because  displays "StarDesktop" as an object type of the desktop object in the first case and "com.sun.star.frame.Desktop" in the second. But the two objects are the same.

ThisComponent
The property  is used from document Basic, where it represents the document the Basic belongs to. The type of object accessed by  depends on the document type. The following example shows the differences.

Basic module in a LibreOffice document:

The execution of this Basic routine shows different results for a Text, Spreadsheet and Presentation document. Depending on the document type, a different set of interfaces are supported by the object. A portion of the interfaces are common to all these document types representing the general functionality that documents of any type offer. In particular, all LibreOffice documents support the com.sun.star.document.OfficeDocument service, including the interfaces com.sun.star.frame.XStorable and com.sun.star.view.XPrintable. Another interface is com.sun.star.frame.XModel.

The following list shows the interfaces supported by all document types:


 * com.sun.star.beans.XPropertySet
 * com.sun.star.container.XChild
 * com.sun.star.document.XDocumentInfoSupplier
 * com.sun.star.document.XEventBroadcaster
 * com.sun.star.document.XViewDataSupplier
 * com.sun.star.document.XEventsSupplier
 * com.sun.star.document.XLinkTargetSupplier
 * com.sun.star.frame.XModel
 * com.sun.star.frame.XStorable
 * com.sun.star.lang.XServiceInfo
 * com.sun.star.lang.XMultiServiceFactory
 * com.sun.star.lang.XEventListener
 * com.sun.star.style.XStyleFamiliesSupplier
 * com.sun.star.util.XModifiable
 * com.sun.star.view.XPrintable

For more information about the functionality of these interfaces, see Frame-Controller-Model Paradigm in LibreOffice. This section also goes into detail about the general document API.

In addition to the common services or interfaces, each document type supports specific services or interfaces. The following list outlines the supported services and important interfaces:

A Text document supports:


 * The service com.sun.star.text.TextDocument supports the interface com.sun.star.text.XTextDocument.
 * Several interfaces, especially from the com.sun.star.text package.

A Spreadsheet document supports:


 * The service com.sun.star.sheet.SpreadsheetDocument ,
 * The service com.sun.star.sheet.SpreadsheetDocumentSettings.
 * Several other interfaces, especially from the com.sun.star.sheet package.

Presentation and Drawing documents support:


 * The service com.sun.star.drawing.DrawingDocument.
 * Several other interfaces, especially from the com.sun.star.drawing package.

The usage of these services and interfaces is explained in the document type specific chapters Text Documents, Spreadsheet Documents and Drawing Documents and Presentation Documents.

As previously mentioned,  is used from document Basic, but it is also possible to use it from application Basic. In an application wide Basic module,  is identical to the current component that can also be accessed through. The only difference between the two is that if the BasicIDE is active,  refers to the BasicIDE itself while   always refers to the component that was active before the BasicIDE became the top window.

ThisDatabaseDocument
The property, introduced since OpenOffice.org 3.1, is only used from a Basic code which is embedded in a Base document. It refers to the Base document model.

Typically, when a macro is started by an event from a Form of the Base document,  represents the Base document, whereas   refers to the Form document.

Special Behavior of LibreOffice Basic
Threading and rescheduling of LibreOffice Basic differs from other languages which must be taken into consideration.

Threads
LibreOffice Basic does not support threads:


 * In situations it may be necessary to create new threads to access UNO components in a special way. This is not possible in LibreOffice Basic.
 * LibreOffice Basic is unable to control threads. If two threads use the Basic runtime system simultaneously, the result will be undefined results or even a crash. Please take precautions.

Rescheduling
The LibreOffice Basic runtime system reschedules regularly. It allows system messages to be dispatched continuously that have been sent to the LibreOffice process during the runtime of a Basic module. This is necessary to allow repainting operations, and access to controls and menus during the runtime of a Basic script as Basic runs in the LibreOffice main thread. Otherwise, it would not be possible to stop a running Basic script by clicking the corresponding button on the toolbar.

This behavior has an important consequence. Any system message, for example, clicking a push button control, can result in a callback into Basic if an corresponding event is specified. The Basic programmer must be aware of the fact that this can take place at any point of time when a script is running.

The following example shows how this effects the state of the Basic runtime system:

When  in this Basic module is executed, the two Boolean variables   and   are initialized. Then  is called where the execution runs into a loop. The loop is executed until the  flag is set to. This is done in  that is assigned to a push button in a writer document, but the   flag can only be set to   if the   flag is also. This flag is permanently toggled in the loop in.

The program execution may or may not be stopped if the push button is clicked. It depends on the point of time the push button is clicked. If the Basic runtime system has just executed the  statement, the execution is stopped because the   condition in   is   and the   flag can be set to. If the push button is clicked when the  variable is , the execution is not stopped. The Basic runtime system reschedules permanently, therefore it is unpredictable. This is an example to show what problems may result from the Basic rescheduling mechanism.

Callbacks to Basic that result from rescheduling have the same effect as if the Sub specified in the event had been called directly from the position in the Basic code that is executed in the moment the rescheduling action leading to the callback takes place. In this example, the Basic call stack looks like this if a breakpoint is placed in the :

Basic        Native code

0: Break <---  Callback due to push button event 1: Macro1 ---> Reschedule 2: Main

With the call to the native  method, the Basic runtime system is left and reentered when the push button events in a Callback to Basic. On the Basic stack this looks like a direct call from  to.

A similar situation occurs when a program raises a dialog using the execute method of the dialog object returned by. See Programming Dialogs and Dialog Controls. In this case, the Basic runtime system does not reschedule, but messages are processed by the dialog's message loop that also result in callbacks to Basic. When the Basic runtime system is called back due to an event at a dialog control, the resulting Basic stack looks analogous. For example:

If  is specified to be executed if an event occurs for one of the dialog controls, the Basic call stack looks like this if a breakpoint is placed in  :

Basic       Native code

0: DoIt <--- Callback due to control event 1: Main ---> execute ---> Reschedule

There is also a difference to the rescheduling done directly by the Basic runtime system. The rescheduling done by the dialog's message loop can not result in unpredictable behavior, because the Basic runtime system has called the dialog's  method and waits for its return. It is in a well-defined state.

Advanced Library Organization
Basic source code and Dialogs are organized in libraries. This section describes the structure and usage of the library system.

General Structure
The library system that is used to store Basic source code modules and Dialogs has three levels:

Library container
 * The library container represents the top level of the library hierarchy containing libraries. The libraries inside a library container are accessed by name.

Library
 * A library contains elements that logically belong together, for example, several Basic modules that form a program or a set of related dialogs together.

Library elements
 * Library elements are Basic source code modules or dialogs. The elements represent the lowest level in the library hierarchy. For Basic source code modules, the element type is string. Dialogs are represented by the interface com.sun.star.io.XInputStreamProvider that provides access to the XML data describing the dialog.

The hierarchy is separated for Basic source code and dialogs, that is, a Basic library container only contains Basic libraries containing Basic source code modules and a dialog library container only contains dialog libraries containing dialogs.

Basic source code and dialogs are stored globally for the whole office application and locally in documents. For the application, there is one Basic library container and one dialog library container. Every document has one Basic library container and one dialog library container as well. By including the application or document level, the library system actually has four levels. Illustration 1: Sample module structure depicts this structure.

As shown in the library hierarchy for Document 1, the Basic and dialog library containers do not have the same structure. The Basic library container has a library named Library1 and the dialog library container has a library named Library2. The library containers are separated for Basic and dialogs in the API.

It is not recommended to create a structure as described above because the library and dialog containers are not separated in the GUI, for example, in the LibreOffice Basic Macros dialog. When a user creates or deletes a new library in the LibreOffice Basic Macro Organizer dialog, the library is created or deleted in the Basic and the dialog library containers.



Library Container Properties in Basic
Currently, the library system is implemented using UNO interfaces, not as a UNO service. Therefore, the library system cannot be accessed by instantiating an UNO service. The library system has to be accessed directly from Basic using the built-in properties  and.

The  property refers to the Basic library container that belongs to the library container that the   property is accessed. In an application-wide Basic module, the property  accesses the application Basic library container and in a document Basic module, the property   contains the document Basic library container. The same applies to the  property.

Loading Libraries
Initially, most Basic libraries are not loaded. All the libraries in the application library container are known after starting LibreOffice, and all the library elements in a document are known when it is loaded, most of them are disabled until they are loaded explicitly. This mechanism saves time during the Basic initialization. When a Basic library is initialized, the source code modules are inserted into the Basic engine and compiled. If there are many libraries with big modules, it is tim consuming, especially if the libraries are not required.

The exception to this is that every library container contains a library named "Standard" that is always loaded. This library is used as a standard location for Basic programs and dialogs that do not need a complex structure. All other libraries have to be loaded explicitly. For example:

When Library1, Module1 looks like

the following code in library Standard, Module1

fails, unless the user loaded Library1 before using the Tools - Macro dialog. A runtime error "Property or method not found" occurs. To avoid this, load library Library1 before calling :

Accordingly in the dialog container, all the libraries besides the Standard library have to be loaded before the dialogs inside the library can be accessed. For example:

The code to instantiate and display the dialog is described in Programming Dialogs and Dialog Controls. The library representing  is only valid once   has been loaded.

The properties  and   refer to the container that includes the Basic source accessing these properties. Therefore in a document module Basic the properties  and   refer to the Basic and Dialog library container of the document. In most cases, libraries in the document have to be loaded. In other cases it might be necessary to access application-wide libraries from document Basic. This can be done using the GlobalScope property. The  property represents the root scope of the application Basic, therefore the application library containers can be accessed as properties of.

Example module in a Document Basic in library Standard:

Library Container API
The  and   support com.sun.star.script.XLibraryContainer2 that inherits from com.sun.star.script.XLibraryContainer, which is a com.sun.star.container.XNameContainer. Basic developers do not require the location of the interface to use a method, but a basic understanding is helpful when looking up the methods in the API reference.

The  handles existing library links and the write protection for libraries. It is also used to rename libraries:

The  creates and removes libraries and library links. Furthermore, it can test if a library has been loaded or, if necessary, load it.

The methods of  access and manage the libraries in the container:

These methods are accessed using the UNO API as described in LibreOffice Basic. Note however, these interfaces can only be used from LibreOffice Basic, not from other environments.

Libraries can be added to library containers in two different ways:

Creating a New Library
 * Creating a new library is done using the  method. A library created with this method belongs to the library container where   has been called. The implementation of the library container is responsible for saving and loading this library. This functionality is not currently covered by the interfaces, therefore the implementation determines how and where this is done. The method   returns a standard com.sun.star.container.XNameContainer interface to access the library elements and modify the library.


 * Initially, such a library is empty and new library elements are inserted. It is also possible to protect a library from changes using the  method. In a read-only library, no elements can be inserted or removed, and the modules or dialogs inside cannot be modified in the BasicIDE. For additional information, see LibreOffice Basic IDE. Currently, the read-only status can only be changed through API.

Creating a Link to an Existing Library
 * Creating a link to an existing library is accomplished using the method . Its   parameter describes the location where the library .xlb file is stored. For additional information about this topic, see the section on Library File Structure). A library link is only referenced by the library container and is not owned, therefore the library container is not responsible for the location to store the library. This is only described by the   parameter.


 * The  parameter sets the read-only status of the library link. This status is independent of the read-only status of the linked library. A linked library is only modified when the library and link to the library are not read only. For example, this mechanism provides read-only access to a library located on a network drive without forcing the library to be read-only, thus the library can be modified easily by an authorized person without changing its read-only status.

The following tables provides a brief overview about other methods supported by the library containers:

Variable Scopes
Some aspects of scoping in Basic depend on the library structure. This section describes which variables declared in a Basic source code module are seen from what libraries or modules. Generally, only variables declared outside Subs are affected by this issue. Variables declared inside Subs are local to the Sub and not accessible from outside of the Sub. For example:

Variables can also be declared outside of Subs. Then their scope includes at least the module they are declared in. To declare variables outside the Subs, the commands,   and   are used.

The  command is used to declare variables that can only be used locally in a module. If the same variable is declared as  in two different modules, they are used independently in each module. For example:

Library Standard, Module1:

Library Standard, Module2:

When  in Module1 is executed,   is displayed (  of Module1) and then   (  of Module2).

The  and   commands declare variables that can also be accessed from outside the module. They are identical in this context. Variables declared with  and   can be accessed from all modules that belong to the same library container. For example, based on the library structure shown in Illustration 12.39: Sample module structure, any variable declared with  and   in the Application Basic Modules Standard/Module1, Standard/Module2, Library1/Module1, Library1/Module2 can also be accessed from all of these modules, therefore the library container represents the logical root scope.

Programming Dialogs and Dialog Controls
The dialogs and dialog controls are UNO components that provide a graphical user interface belonging to the module com.sun.star.awt. The Toolkit controls follow the Model-View-Controller (MVC) paradigm, which separates the component into three logical units, the model, view, and controller. The model represents the data and the low-level behavior of the component. It has no specific knowledge of its controllers or its views. The view manages the visual display of the state represented by the model. The controller manages the user interaction with the model.

The following example of a text field illustrates the separation into model, view and controller.

The model contains the data which describes the text field; for example, the text to be displayed, text color and maximum text length. The text field model is implemented by the com.sun.star.awt.UnoControlEditModel service that extends the com.sun.star.awt.UnoControlModel service. All aspects of the model are described as a set of properties which are accessible through the com.sun.star.beans.XPropertySet interface.

The view is responsible for the display of the text field and its content. It is possible in general to have multiple views for the same model, but not for Toolkit dialogs. The view is notified about model changes; for example, changes to the text color property causes the text field to be repainted.

The controller handles the user input provided through the keyboard and mouse. If the user changes the text in the text field, the controller updates the corresponding model property. In addition, the controller updates the view; for example, if the user presses the delete button on the keyboard, the marked text in the text field is deleted. A more detailed description of the MVC paradigm can be found in the chapter about Forms.

The base for all the Toolkit controls is the com.sun.star.awt.UnoControl service that exports the following interfaces:


 * The com.sun.star.awt.XControl interface specifies control basics. For example, it gives access to the model, view and context of a control.
 * The com.sun.star.awt.XWindow interface specifies operations for a window component.
 * The com.sun.star.awt.XView interface provides methods for attaching an output device and drawing an object.

Dialog Handling
After you have designed a dialog, you can:
 * Show the dialog in your application
 * Obtain the dialog model
 * Use the dialog as a controls container
 * Modify the properties of the dialog
 * Add pages to the dialog

Showing a Dialog
After a dialog has been designed using the dialog editor, a developer wants to show the dialog from within the program code. The necessary steps are shown in the following example:

The dialog control is created by calling the runtime function  which takes an object as parameter that supports the com.sun.star.io.XInputStreamProvider interface. This object provides an input stream that represents an XML description of the dialog. The section Advanced Library Organization explains the accessing to the object inside the library hierarchy. The dialog control is shown by calling the  method of the com.sun.star.awt.XDialog interface. It can be closed by calling, or by offering a Cancel or OK Button on the dialog. For additional information, see Programming Dialogs and Dialog Controls.

Getting the Dialog Model
If a developer wants to modify any properties of a dialog or a control, it is necessary to have access to the dialog model. From a dialog, the model can be obtained by the  method of the com.sun.star.awt.XControl interface

or shorter

Dialog as Control Container
All controls belonging to a dialog are grouped together logically. This hierarchy concept is reflected by the fact that a dialog control is a container for other controls. The corresponding service com.sun.star.awt.UnoControlDialog therefore supports the com.sun.star.awt.XControlContainer interface that offers container functionality, namely access to its elements by name. Since in LibreOffice Basic, every method of every supported interface is called directly at the object without querying for the appropriate interface, a control with the name TextField1 can be obtained from a dialog object  simply by:

See LibreOffice Basic for additional information. The hierarchy between a dialog and its controls can be seen in the dialog model com.sun.star.awt.UnoControlDialogModel, which is a container for control models and therefore supports the com.sun.star.container.XNameContainer interface. A control model is obtained from a dialog model by:

or shorter:

The model of a control is also returned by the  method of the control. In short notation:

Dialog Properties
It is possible to make some modifications before a dialog is shown. An example is to set the dialog title that is shown in the title bar of a dialog window. This can be achieved by setting the Title property at the dialog model through the com.sun.star.beans.XPropertySet interface:

or shorter

Another approach is to use the  method of the com.sun.star.awt.XDialog interface:

or

Another property is the  property that sets a different background color for the dialog.

Common Properties
All Toolkit control models have a set of identical properties referred as the common properties. These are the properties,  ,  ,  ,  ,  ,  , and.

The,  ,  , and   properties change the position and size of a dialog, and control at runtime. When designing a dialog in the dialog editor, these properties are set automatically.

The  property is required, because all dialogs and controls are referenced by their name. In the dialog editor this name is created from the object name and a number, for example,.

The  property defines the order of focusing a control in a dialog when pressing the tabulator key. The index of the first element has the value 0. In the dialog editor the  property is set automatically when inserting a control. The order can also be changed through the property browser. Take care when setting this property at runtime.

The  property adds additional information to a control, such as a remark or number.

The  property is described in detail in the next section.

Multi-Page Dialogs
A dialog may have several pages that can be traversed by the user step by step. This feature is used in the LibreOffice autopilots. The dialog property  defines which page of the dialog is active. At runtime the next page of a dialog is displayed by increasing the step value by 1.

The  property of a control defines the page of the dialog on which the control is visible. For example, if a control has a step value of 1, it is only visible on page 1 of the dialog. If the step value of the dialog is increased from 1 to 2, then all controls with a step value of 1 disappear and all controls with a step value of 2 become visible.

The step value 0 has a special role. If a control has a step value of 0, the control is displayed on all dialog pages. If a dialog has a step value of 0, all controls of the dialog are displayed, regardless of the step value of the individual controls.

Dialog Controls
After you have created your dialog, you can add many different controls to it, for example buttons, images, labels, text, check boxes and scroll bars.

Command Button
The command button com.sun.star.awt.UnoControlButton allows the user to perform an action by clicking the button. Usually a button carries a label that is set through the  property of the control model:

or in short:

The label can also be set using the  method of the com.sun.star.awt.XButton interface:

or in short:

During runtime, you may want to enable or disable a button. This is achieved by setting the  property to   or. The  property defines the default action of a button where 0 is the Default, 1 is OK, 2 is Cancel, and 3 is Help. If a button has a  value of 2, it behaves like a cancel button, that is, pressing the button closes the dialog. In this case, the method  of the dialog returns with a value of 0. An OK button of  returns 1 on. The property  specifies that the command button is the default button on the dialog, that is, pressing the ENTER key chooses the button even if another control has the focus. The  property defines if a control can be reached with the TAB key.

The command button has the feature, to display an image by setting the  property, which contains the path to the graphics file.

All standard graphics formats are supported, such as .gif, .jpg, .tif, .wmf and .bmp. The property  defines the alignment of the image inside the button where 0 is Left, 1 is Top, 2 is Right, and 3 is the Bottom. If the size of the image exceeds the size of the button, the image is not scaled automatically, but cut off. In this respect, the image control offers more functionality.

Image Control
If the user wants to display an image without the button functionality, the image control com.sun.star.awt.UnoControlImageControl is selected. The location of the graphic for the command button is set by the  property. Usually, the size of the image does not match the size of the control, therefore the image control automatically scales the image to the size of the control by setting the  property to.

Check Box
The check box control com.sun.star.awt.UnoControlCheckBox is used in groups to display multiple choices so that the user can select one or more choices. When a check box is selected it displays a check mark. Check boxes work independently of each other, thus different from option buttons. A user can select any number of check boxes at the same time.

The property, where 0 is not checked, 1 is checked, 2 is don't know, accesses and changes the state of a checkbox. The tri-state mode of a check box is enabled by setting the  property to True. A tri-state check box provides the additional state "don't know", that is used to give the user the option of setting or unsetting an option.

The same result is achieved by using the com.sun.star.awt.XCheckBox interface:

Option Button
An option button control com.sun.star.awt.UnoControlRadioButton is a simple switch with two states, that is selected by the user. Usually option buttons are used in groups to display several options, that the user may select. While option buttons and check boxes seem to be similar, selecting one option button deselects all the other option buttons in the same group.

Usually a group box, or horizontal and vertical lines are used, because those controls visually group the option buttons together, but in principle this can be any control. There is no functional relationship between an option button and a group box. Option buttons are grouped through consecutive tab indices only.

The state of an option button is accessed by the  property of its Model, where 0 is not checked and 1 is checked.

The state of an option button is also returned by the  property of the control, where False is not checked and True is checked. The code is greatly simplified:

Label Field
A label field control com.sun.star.awt.UnoControlFixedText displays text that the user can not edit on the screen. For example, the label field is used to add descriptive labels to text fields, list boxes, and combo boxes. The actual text displayed in the label field is controlled by the Label property. The  property allows the user to set the alignment of the text in the control to the left (0), center (1) or right (2). By default, the label field displays the text from the  property in a single line. If the text exceeds the width of the control, the text is truncated. This behavior is changed by setting the  property to , so that the text is displayed on more than one line, if necessary. By default, the label field control is drawn without any border. However, the label field appears with a border if the  property is set, where 0 is no border, 1 is a 3D border, and 2 is a simple border. The font attributes of the text in the label field are specified by the  property. It is recommended to set this property with the property browser in the dialog editor.

Label fields are used to define shortcut keys for controls without labels. A shortcut key can be defined for any control with a label by adding a tilde (~) before the character that will be used as a shortcut. When the user presses the character key simultaneously with the key, the control automatically gets the focus. To assign a shortcut key to a control without a label, for example, a text field, the label field is used. The tilde prefixes the corresponding character in the Label property of the label field. As the label field cannot receive focus, the focus automatically moves to the next control in the tab order. Therefore, it is important that the label field and the text field have consecutive tab indices.

Text Field
The text field control com.sun.star.awt.UnoControlEdit is used to get input from the user at runtime. In general, the text field is used for editable text, but it can also be made read-only by setting the  property to. The actual text displayed in a text field is controlled by the  property. The maximum number of characters that can be entered by the user is specified with the  property. A value of 0 means that there is no limitation. By default, a text field displays a single line of text. This behavior is changed by setting the property  to. The properties  and   displays a horizontal and vertical scroll bar.

When a text field receives the focus by pressing the key the displayed text is selected and highlighted by default. The default cursor position within the text field is to the right of the existing text. If the user starts typing while a block of text is selected, the selected text is replaced. In some cases, the user may change the default selection behavior and set the selection manually. This is done using the com.sun.star.awt.XTextComponent interface:

Or in short:

The text field control is also used for entering passwords. The property  specifies the character that is displayed in the text field while the user enters the password. In this context, the  property is used to limit the number of characters that are typed in:

A user can enter any kind of data into a text field, such as numerical values and dates. These values are always stored as a string in the Text property, thus leading to problems when evaluating the user input. Therefore, consider using a date field, time field, numeric field, currency field or formatted field instead.

List Box
The list box control com.sun.star.awt.UnoControlListBox displays a list of items that the user can select one or more of. If the number of items exceeds what can be displayed in the list box, scroll bars automatically appear on the control. If the  property is set to , the list of items is displayed in a drop-down box. In this case, the maximum number of line counts in the drop-down box are specified with the  property. The actual list of items is controlled by the  property. All selected items are controlled by the  property. If the  property is set to , more than one entry can be selected.

It may be easier to use the com.sun.star.awt.XListBox interface when working with list boxes, because an item can be added to a list at a specific position with the  method. For example, an item is added at the end of the list by:

Multiple items are added with the help of the  method. The  method is used to remove items from a list. For example, the first entry in a list is removed by:

A list box item can be preselected with the,   and   methods. For example, the first entry in a list box can be selected by:

The currently selected item is obtained with the  method:

The position of the currently selected item is obtained with the  method:

Combo Box
The combo box control com.sun.star.awt.UnoControlComboBox presents a list of choices to the user. Additionally, it contains a text field allowing the user to input a selection that is not on the list. A combo box is used when there is only a list of suggested choices, whereas a list box is used when the user input is limited only to the list.

The features and properties of a combo box and a list box are similar. Also in a combo box the list of items can be displayed in a drop-down box by setting the  property to. The actual list of items is accessible through the  property. The text displayed in the text field of the combo box is controlled by the  property. For example, if a user selects an item from the list, the selected item is displayed in the text field and is obtained from the  property:

When a user types text into the text field of the combo box, the automatic word completion is a useful feature and is enabled by setting the  property to. It is recommended to use the com.sun.star.awt.XComboBox interface when accessing the items of a combo box:

Horizontal/Vertical Scroll Bar
If the visible area in a dialog is smaller than the displayable content, the scroll bar control com.sun.star.awt.UnoControlScrollBar provides navigation through the content by scrolling horizontally or vertically. In addition, the scroll bar control is used to provide scrolling to controls that do not have a built-in scroll bar.

The orientation of a scroll bar is specified by the  property and can be horizontal or vertical. A scroll bar has a thumb (scroll box) that the user can drag with the mouse to any position along the scroll bar. The position of the thumb is controlled by the  property. For a horizontal scroll bar, the left-most position corresponds to the minimum scroll value of 0 and the right-most position to the maximum scroll value defined by the  property. A scroll bar also has arrows at its end that when clicked or held, incrementally moves the thumb along the scroll bar to increase or decrease the scroll value. The change of the scroll value per mouse click on an arrow is specified by the  property. When clicking in a scroll bar in the region between the thumb and the arrows, the scroll value increases or decreases by the value set for the  property. The thumb position represents the portion of the displayable content that is currently visible in a dialog. The visible size of the thumb is set by the  property and represents the percentage of the currently visible content and the total displayable content.

The scroll bar control uses the adjustment event com.sun.star.awt.AdjustmentEvent to monitor the movement of the thumb along the scroll bar. In an event handler for adjustment events the developer may change the position of the visible content on the dialog as a function of the  property. In the following example, the size of a label field exceeds the size of the dialog. Each time the user clicks on the scrollbar, the macro  is called and the position of the label field in the dialog is changed according to the scroll value.

Group Box
The group box control com.sun.star.awt.UnoControlGroupBox creates a frame to visually group other controls together, such as option buttons and check boxes. Note that the group box control does not provide any container functionality for other controls, it only has visual functionality. For more details, see Option Button.

The group box contains a label embedded within the border and is set by the  property. In most cases, the group box control is only used passively.

Progress Bar
The progress bar control com.sun.star.awt.UnoControlProgressBar displays a growing or shrinking bar to give the user feedback during an operation, for example, the completion of a lengthy task. The minimum and the maximum progress value of the control is set by the  and the   properties. The progress value is controlled by the  property. By default, the progress bar is blue, but the fill color can be changed by setting the  property. The functionality of a progress bar is demonstrated in the following example:

Horizontal/Vertical Line
The line control com.sun.star.awt.UnoControlFixedLine creates simple lines in a dialog. In most cases, the line control is used to visually subdivide a dialog. The line control can have horizontal or vertical orientation that is specified by the  property. The label of a line control is set by the  property. Note that the label is only displayed if the control has a horizontal orientation.

Date Field
The date field control com.sun.star.awt.UnoControlDateField extends the text field control and is used for displaying and entering dates. The date displayed in the date field is controlled by the  property. The date value is of type  and must be specified in the format YYYYMMDD, for example, the date September 30th, 2020 is set in the following format:

The current date is set by using the Date and  runtime functions:

The minimum and the maximum date that the user can enter is defined by the  and the   property. The format of the displayed date is specified by the  and the   property, but the usage of   is deprecated. Some formats are dependent on the system settings. If the  property is set to True, the date entered by the user is checked during input. The  property enables a calendar that the user can drop down to select a date.

is currently not working by program, but you can set it with the Control Properties in the IDE.

Time Field
The time field control com.sun.star.awt.UnoControlDateField displays and enters time values. The time value are set and retrieved by the  property. The time value is of type  and is specified in the format HHMMSShh, where HH are hours, MM are minutes, SS are seconds and hh are hundredth seconds. For example, the time 15:18:23 is set by:

The minimum and maximum time value that can be entered is given by the  and   property. The format of the displayed time is specified by the  property.

The time value is checked during input by setting the  property to.

time format is currently not working.

Numeric Field
It is recommended to use the numeric field control com.sun.star.awt.UnoControlNumericField if the user input is limited to numeric values. The numeric value is controlled by the  property, which is of type. A minimum and maximum value for user input is defined by the  and the   property. The decimal accuracy of the numeric value is specified by the  property, for example, a value of 6 corresponds to 6 decimal places. If the  property is set to , a thousands separator is displayed. The numeric field also has a built-in spin button, enabled by the  property. The spin button is used to increment and decrement the displayed numeric value by clicking with the mouse, whereas the step is set by the  property.

Currency Field
The currency field control com.sun.star.awt.UnoControlCurrencyField is used for entering and displaying currency values. In addition to the currency value, a currency symbol is displayed, that is set by the  property. If the  property is set to , the currency symbol is displayed in front of the currency value.

Formatted Field
The formatted field control com.sun.star.awt.UnoControlFormattedField specifies a format that is used for formatting the entered and displayed data. A number formats supplier must be set in the  property and a format key for the used format must be specified in the   property. It is recommended to use the property browser in the dialog editor for setting these properties. Supported number formats are number, percent, currency, date, time, scientific, fraction and boolean values. Therefore, the formatted field can be used instead of a date field, time field, numeric field or currency field. The  is described in Office Development.

Pattern Field
The pattern field control com.sun.star.awt.UnoControlPatternField displays and enters a string according to a specified pattern. The entries that the user enters in the pattern field are defined in the  property as a special character code. The length of the edit mask determines the number of the possible input positions. If a character is entered that does not correspond to the edit mask, the input is rejected. For example, in the edit mask "NNLNNLLLLL" the character L has the meaning of a text constant and the character N means that only the digits 0 to 9 can be entered. A complete list of valid characters can be found in the LibreOffice online help. The  property contains the initial values that are displayed in the pattern field. The length of the literal mask should always correspond to the length of the edit mask. An example of a literal mask which fits to the above mentioned edit mask would be "__.__.2002". In this case, the user enters only 4 digits when entering a date.

More information at: Documentation/OOo3_User_Guides/Writer_Guide/Form_controls_reference_Pattern_field

File Control
The file control com.sun.star.awt.UnoControlFileControl has all the properties of a text field control, with the additional feature of a built-in command button. When the button is clicked, the file dialog shows up. The directory that the file dialog initially displays is set by the Text property.

The directory must be given as a system path, file URLs do not work at the moment. In Basic you can use the runtime function  to convert system paths to URLs.

Filters for the file dialog can not be set or appended for the file control. An alternative way is to use a text field and a command button instead of a file control and assign a macro to the button which instantiates the file dialog com.sun.star.ui.dialogs.FilePicker at runtime. An example is provided below.

Once the dialog is open, the user may write a directory address in the text field. Then he/she clicks the button. The file dialog will display the file names in that directory, or by default in the work directory. The selected file name is stored in the text field.

Creating Dialogs at Runtime
When using LibreOffice Basic, the dialog editor is a tool for designing dialogs. Refer to LibreOffice Basic IDE for additional information. Since OpenOffice.org 2.0.0, dialogs that have been built with the dialog editor can be loaded by a macro written in any of the supported scripting framework languages (BeanShell, JavaScript, Java, LibreOffice Basic) by using the com.sun.star.awt.XDialogProvider API. See section Using the Scripting Framework for more details.

In addition, it is also possible to create dialogs at runtime in a similar way as Java Swing components are created. Also, the event listeners are registered at runtime at the appropriate controls.



In the Java example described in this section, a simple modal dialog is created at runtime containing a command button and label field. Each time the user clicks on the button, the label field is updated and the total number of button clicks is displayed.

The dialog is implemented as a UNO component in Java that is instantiated with the service name. For details about writing a Java component and the implementation of the UNO core interfaces, refer to Storing the Service Manager for Further Use. The method that creates and executes the dialog is shown below.

First, a dialog model is created by prompting the  for the com.sun.star.awt.UnoControlDialogModel service. Then, the position, size and title of the dialog are set using the com.sun.star.beans.XPropertySet interface. In performance critical applications, the use of the com.sun.star.beans.XMultiPropertySet interface is recommended. At this point, the dialog model describes an empty dialog, which does not contain any control models.

All control models in a dialog container have the common properties "PositionX", "PositionY", "Width", "Height", "Name", "TabIndex", "Step" and "Tag". These properties are optional and only added if the control model is created by a special object factory, namely the dialog model. Therefore, a dialog model also supports the com.sun.star.lang.XMultiServiceFactory interface. If the control model is created by the, these common properties are missing.

After the control models for the command button and label field are created, their position, size, name, tab index and label are set. Then, the control models are inserted into the dialog model using the com.sun.star.container.XNameContainer interface. The model of the dialog has been fully described.

To display the dialog on the screen, a dialog control com.sun.star.awt.UnoControlDialog is created and the corresponding model is set. An action listener is added to the button control, because the label field is updated whenever the user clicks on the command button. The listener is explained below. Before the dialog is shown, a window or a peer is created on the screen. Finally, the dialog is displayed on the screen using the execute method of the com.sun.star.awt.XDialog interface.

The implementation of the action listener is shown in the following example.

The action listener is fired each time the user clicks on the command button. In the  method of the com.sun.star.awt.XActionListener interface, an internal counter for the number of button clicks is increased. Then, this number is updated in the label field. In addition, the disposing method of the parent interface com.sun.star.lang.XEventListener is implemented.

Our sample component executes the dialog from within the office by implementing the trigger method of the com.sun.star.task.XJobExecutor interface:

A simple LibreOffice Basic macro that instantiates the service of our sample component and executes the dialog is shown below.

In future versions of LibreOffice, a method for executing dialogs created at runtime will be provided.

Library File Structure
This section describes how libraries are stored. Generally all data is stored in XML format. Four different XML document types that arespecified in the DTD files installed in /share/dtd/officedocument are used:


 * A library container is described by a library container index file following the specification given in libraries.dtd. In this file, each library in the library container is described by its name, a flag if the library is a link, the StorageURL (describing where the library is stored) and, only in case of a link, the link read-only status.
 * A library is described by a library index file following the specification given in library.dtd. This file contains the library name, a flag for the read-only status, a flag if the library is password protected (see below) and the name of each library element.
 * A Basic source code module is described in a file following the specification given in module.dtd. This file contains the module name, the language (at the moment only LibreOffice Basic is supported) and the source code.
 * A dialog is described in a file following the specification given in dialog.dtd. The file contains all data to describe a dialog. As this format is extensive, it is not possible to describe it in this document.

Additionally, a binary format is used to store compiled Basic code for password protected Basic libraries. This is described in more detail in Library File Structure.

Besides the XML format of the library description files, it is necessary to understand the structure in which these files are stored. This is different for application and document libraries. Application libraries are stored directly in the system file system and document libraries are stored inside the document's package file. The following sections describe the structure and combination of library container and library structures.

Application Library Container
In an LibreOffice installation the application library containers for Basic and dialogs are located in the directory /share/basic or /user/basic. The library container index files are named script.xlc for the Basic and dialog.xlc for the Dialog library container. The "lc" in .xlc stands for library container.

The same directory contains the libraries created by the user. Initially only the library Standard exists for Basic and dialogs using the same directory. The structure of the library inside the directory is explained in the next section.

The user/basic directory is not the only place in the LibreOffice installation where libraries are stored. Most of the autopilots integrated in LibreOffice are realized in Basic, and the corresponding Basic and dialog libraries are installed in the directory /share/basic. These libraries are listed in the library container index file as read-only links.

It is necessary to distinguish between libraries created by the user and the autopilot libraries. The autopilot libraries are installed in a directory that is shared between different users. In a network installation, the share directory is located somewhere on a server, so that the autopilot libraries cannot be owned directly by the user-specific library containers.

In the file system, a library is represented by a directory. The directory's name is the same as the library name. The directory contains all files that are necessary for the library.

Basic libraries can be protected with a password, so that the source code cannot be read by unauthorized persons. Dialog libraries cannot be protected with a password. This can be handled using the LibreOffice Basic Macro Organizer dialog that is explained in Managing Basic and Dialog Libraries. The password protection of a Basic library also affects the file format.

Libraries without Password Protection
Every library element is represented by an XML file named like the element in the directory representing the library. For Basic modules these files, following the specification in module.dtd, have the extension .xba. For dialogs these files, following the specification in dialog.dtd, have the extension .xdl. Additionally, the directory contains a library index file (library.dtd). These index files are named script.xlb for Basic and dialog.xlb for dialog libraries.

In the following example, an Application Basic library Standard containing two modules Module1 and Module2 is represented by the following directory:

 Standard | |--script.xlb |--Module1.xba |--Module2.xba

An application dialog library Standard containing two dialogs  and   is represented by the following directory:

 Standard | |--dialog.xlb |--SmallDialog.xba |--BigDialog.xba

It is also possible that the same directory represents a Basic and a Dialog library. This is the standard case in the LibreOffice, See the chapter Library organization in LibreOffice. When the two example libraries above are stored in the same directory, the files from both libraries are together in the same directory:

 Standard | |--dialog.xlb |--script.xlb |--Module1.xba |--Module2.xba |--SmallDialog.xba |--BigDialog.xba

The two libraries do not affect each other, because all file names are different. This is also the case if a Basic module and a dialog are named equally, due the different file extensions.

Libraries with Password Protection
Only Basic libraries can be password protected. The password protection of a Basic library affects the file format, because binary data has to be stored. In plain XML format, the source code would be readable in the file even if it was not displayed in the Basic IDE. Also, the compiled Basic code has to be stored for each module together with the encrypted sources. This is necessary because, Basic could not access the source code and compile it as long as the password is unknown in contrast to libraries without password protection. Without storing the compiled code, Basic could only execute password-protected libraries once the user supplied the correct password. The whole purpose of the password feature is to distribute programs without giving away the password and source code, therefore this would not be feasible.

The following example shows a password-protected application Basic library Library1, containing three modules Module1, Module1 and Module3, is represented by the following directory:

 Library1 | |--script.xlb |--Module1.pba |--Module2.pba |--Module3.pba

The file script.xlb does not differ from the case without a password, except for the fact that the password protected status of the library is reflected by the corresponding flag.

Each module is represented by a .pba file. Like LibreOffice documents, these files are package files ("pba" stands for package basic) and contain a sub structure that can be viewed with any zip tool. ).

A module package file has the following content:

 Module1.pba | |-- Meta-Inf          ' Content is not displayed here |--code.bin |--source.xml

The Meta-Inf directory is part of every package file and will not be explained in this document. The file code.bin contains the compiled Basic code and the file source.xml contains the Basic source code encrypted with the password.

Document Library Container
While application libraries are stored directly in the file system, document libraries are stored inside the document's package file. In documents, the Basic library container and dialog library container are stored separately:


 * The root of the Basic library container hierarchy is a folder inside the package file named Basic. This folder is not created when the Basic library container contains an empty Standard library in the case of a new document.
 * The root of the dialog library container hierarchy is a folder inside the package file named Dialogs. This folder is not created when the dialog library container contains an empty Standard library in the case of a new document.

The libraries are stored as sub folders in these library container folders. The structure inside the libraries is basically the same as in an application. One difference relates to the stream - "files" inside the package or package folders – names. In documents, all XML stream or file names have the extension .xml. Special extensions like .xba, .xdl are not used. Instead of different extensions, the names are extended for the library and library container index files. In documents they are named script-lc.xml (Basic library container index file), script-lb.xml (Basic library index file), dialog-lc.xml (dialog library container index file) and dialog-lb.xml (dialog library index file).

In example 1, the package structure for a document with one Basic Standard library containing three modules:

 ExampleDocument1 | |-- Basic | |  |  |-- Standard      ' Folder: Contains library "Standard" | |  |  |  |  |--Module1.xml      ' Stream: Basic module file | |  |--Module2.xml      ' Stream: Basic module file | |  |--Module3.xml      ' Stream: Basic module file | |  |--script-lb.xml    ' Stream: Basic library index file | |  |  |--script-lc.xml       ' Stream: Basic library container index file | | ' From here the folders and streams have nothing to do with libraries |--<DIR> Meta-Inf |--content.xml |--settings.xml |--styles.xml

In example 2, package structure for a document with two Basic and one dialog libraries:

<Package> ExampleDocument2 | |--<DIR> Basic | |  |  |--<DIR> Standard      ' Folder: Contains library "Standard" | |  |  |  |  |--Module1.xml      ' Stream: Basic module file | |  |--Module2.xml      ' Stream: Basic module file | |  |--script-lb.xml    ' Stream: Basic library index file | |  |  |--<DIR> Library1      ' Folder: Contains library "Library1" | |  |  |  |  |--Module1.xml      ' Stream: Basic module file | |  |--script-lb.xml    ' Stream: Basic library index file | |  |  |--script-lc.xml       ' Stream: Basic library container index file | |--<DIR> Dialogs | |  |  |--<DIR> Standard      ' Folder: Contains library "Standard" | |  |  |  |  |--Dialog1.xml      ' Stream: Dialog file | |  |--dialog-lb.xml    ' Stream: Dialog library index file | |  |  |--<DIR> Library1      ' Folder: Contains library "Library1" | |  |  |  |  |--Dialog1.xml      ' Stream: Dialog file | |  |--Dialog2.xml      ' Stream: Dialog file | |  |--dialog-lb.xml    ' Stream: Dialog library index file | |  |  |--dialog-lc.xml       ' Stream: Dialog library container index file | | ' From here the folders and streams have nothing to do with libraries |--<DIR> Meta-Inf |--content.xml |--settings.xml |--styles.xml

If a document Basic library is password protected, the file structure does not differ as much from an unprotected library as in the Application Basic case. The differences are:


 * The module files of a password-protected Basic library have the same name as without the password protection, but they are scrambled with the password.
 * There is an additional binary file named like the library with the extension .bin for each module. Similar to the file code.bin in the Application Basic .pba files, this file contains the compiled Basic code that executes the module without access to the source code.

The following example shows the package structure for a document with two Basic and one dialog libraries where only the Basic library Library1 contains any of the modules:

<Package> ExampleDocument3 | |--<DIR> Basic | |  |  |--<DIR> Standard      ' Folder: Contains library "Standard" | |  |  |  |  |--script-lb.xml    ' Stream: Basic library index file | |  |  |--<DIR> Library1      ' Folder: Contains library "Library1" | |  |  |  |  |--Module1.xml      ' Stream: Scrambled Basic module source file | |  |--Module1.bin      ' Stream: Basic module compiled code file | |  |--Module2.xml      ' Stream: Scrambled Basic module source file | |  |--Module2.bin      ' Stream: Basic module compiled code file | |  |--Module3.xml      ' Stream: Scrambled Basic module source file | |  |--Module3.bin      ' Stream: Basic module compiled code file | |  |--script-lb.xml    ' Stream: Basic library index file | |  |  |--script-lc.xml       ' Stream: Basic library container index file | |--<DIR> Dialogs | |  |  |--<DIR> Standard      ' Folder: Contains library "Standard" | |  |  |  |  |--dialog-lb.xml    ' Stream: Dialog library index file | |  |  |--<DIR> Library1      ' Folder: Contains library "Library1" | |  |  |  |  |--dialog-lb.xml    ' Stream: Dialog library index file | |  |  |--dialog-lc.xml       ' Stream: Dialog library container index file | | ' From here the folders and streams have nothing to do with libraries |--<DIR> Meta-Inf |--content.xml |--settings.xml |--styles.xml

This example also shows that a Dialogs folder is created in the document package file although the library Standard and the library Library1 do not contain dialogs. This is done because the Dialog library Library1 would be lost after reloading the document. Only a single empty library Standard is assumed to exist, even if it is not stored explicitly.

Library Deployment
LibreOffice has a simple concept to add Basic libraries to an existing installation. Bringing Basic libraries into a LibreOffice installation involves the following steps:


 * Package your libraries as office extension *.oxt package.
 * Start the Extension Manager (Tools - Extension Manager), press the Add button, select the extension package you would like to install and press Ok.

Alternatively, you can install the extension also via the command line:

[<OfficePath>/program] $ unopkg add my_package.oxt

The tool analyzes the packages manifest file and install all referenced items accordingly to their mime types.

The opposite step is necessary to remove a package from your LibreOffice installation:


 * Start the Extension Manager (Tools - Extension Manager), select the package you want to remove and press Remove
 * or via the command line:

[<OfficePath>/program] $ unopkg remove my_package.oxt

You can run unopkg with the option '--help' or '-h' to get a comprehensive overview of all the switches.

Package Structure
An extension package (*.oxt) is a zip file containing Basic libraries, UNO components, type libraries and/or other files. The unopkg tool unzips the content found in the package directory into the cache directory, preserving the file structure of the zip file. Based on the package manifest.xml file the tool installs the referenced content items accordingly to the mime types. All other not referenced content is ignored and is simply unzipped in the cache directory for private usage from package (e.g. images, ...).

Basic libraries
 * The unopkg tool links Basic library files (.xlb) into LibreOffice by adding them to the Basic library container files (.xlc) that reside in the following paths:


 * {|class="wikitable"

!Library File !User Installation !Shared Installation
 * script.xlb
 * <OfficeUserPath>/user/basic/script.xlc
 * <OfficePath>/share/basic/script.xlc
 * dialog.xlb
 * <OfficeUserPath>/user/basic/dialog.xlc
 * <OfficePath>/share/basic/dialog.xlc
 * }
 * <OfficePath>/share/basic/dialog.xlc
 * }


 * The files share/basic/*.xlc are created when new libraries are shared among all users using the unopkg option --shared in a network installation.


 * The name of a Basic library is determined by the name of its parent directory. Therefore, package complete library folders, including the parent folders into the UNO Basic package. For example, if your library is named, there has to be a corresponding folder /MyLib in your development environment. This folder must be packaged completely into the UNO package, so that the *.oxt file contains a structure similar to the following:

my_package.oxt: META-INF/mainfest.xml description.xml MyLib/ script.xlb dialog.xlb Module1.xba Dialog1.xba

The appropriate manifest.xml file would look like the following:

Other package components


 * More detailed information about unopkg or Extensions and Extensions deployment in general can be found in the Extensions chapter. Recommended are at least the File Format and the description.xml section.

Path Settings
The package directories are called uno-packages by default. There can be one in <OfficePath>/share for shared installations and another one in <OfficePath>/user for single users. The cache directories are created automatically within the respective uno-packages directory. LibreOffice has to be configured to look for these paths in the uno.ini file (on Windows, unorc on Unix) in <OfficePath>/program. When unopkg is launched, it checks this file for package entries. If they do not exist, the following default values are added to uno(.ini|rc).

[Bootstrap] UNO_SHARED_PACKAGES=${$SYSBINDIR/bootstrap.ini::BaseInstallation}/share/uno_packages UNO_SHARED_PACKAGES_CACHE=$UNO_SHARED_PACKAGES/cache UNO_USER_PACKAGES=${$SYSBINDIR/bootstrap.ini::UserInstallation}/user/uno_packages UNO_USER_PACKAGES_CACHE=$UNO_USER_PACKAGES/cache

The settings reflect the default values for the shared package and cache directory, and the user package and cache directory as described above.

In a network installation, all users start the office from a common directory on a file server. The administrator installs the extensions package with the --shared option to make it available for all users of this network installation. Note: for shared installation administrator rights are necessary and most often extensions get installed per user.

Additional Options
By default, the tool logs all actions into the <cache-dir>/log.txt file. You can switch to another log file through the --log-file option. Option -v (–verbose) logs to stdout, in addition to the log file.

The tool handles errors loosely. It continues after errors even if a package cannot be inflated or a shared library cannot be registered. The tool logs these errors and proceeds silently. If you want the tool to stop on every error, switch on the –strict_error handling.

If there is some inconsistency with the cache and you want to renew it from the ground up, repeating the installation using the expert command unopkg reinstall to force a reinstallation of all deployed extensions.