Extensions development basic fr

From Apache OpenOffice Wiki
Revision as of 07:55, 13 October 2006 by Jfnif (Talk | contribs)

Jump to: navigation, search

Comment démarrer

Cette page est un guide de démarrage qui vous permettra d'écrire des macros en OpenOffice.org Basic. Une connaisance préalable de la programmation est un pré-requis. Merci d'éditer cette page pour la rendre plus lisible. J'espère que vous la trouverez utile.

Si vous maîtrisez les bases, alors vous pouvez consulter le CookBook qui donne des exemples et des (wrappers).


Où le code est-il enregistré ?

Le code OpenOffice.org Basic est enregistré dans des modules eux-mêmes placés dans les bibliothèques. Une bibliothèque peut être :

  • Partagée (pour une installation en réseau - OOo Macros & Dialogues)
  • Uniquement pour l'utilisateur courant (Mes Macros & Dialogues)
  • Incorporée à un document ou à un modèle de telle manière que son code ne soit disponible que lorsque ce document est ouvert.

Lorsque des bibliothèques ne sont stockées ni dans un document ni dans un modèle, c'est-à-dire lorsque les bibliothèques sont partagées ou pour l'utilisateur courant, on les appelle Bibliothèques OpenOffice.org.

Pour connaître les dossiers qui contiennent les bibliothèques OpenOffice.org voir :
Outils > Options… > OpenOffice.org > Chemins > BASIC.

Note Ne copiez pas ni ne déplacez les bibliothèques en utilisant les commandes du système d'exploitation. Préférez le gestionnaire de macros ou le gestionnaire de packages.


La taille autorisée pour les modules placés à l'intérieur des bibliothèques est limitée à 64 Ko. Une bilbiothèque peut contenir jusqu'à 16.000 modules.

Pour plus d'information, reportez-vous à l'aide en ligne, rubrique : Modules et bibliothèques.

Accéder à l'IDE

Pour accéder à l'IDE (environnement de développement intégré) pour la première fois :

OpenOffice.org 1.1.x: Outils > Macros > Macro… >

OpenOffice.org 1.9.x et ultérieur : Outils > Macros > Gérer les macros > OpenOffice.org Basic… >

Pour commencer, nous allons utiliser le Module1 de la bibliothèque Standard, présente pour l'utilisateur courant uniquement :

Entrons un nom pour notre nouvelle macro : HelloWorld

Dans la macro, sélectionnons Standard dans la boîte de liste.

Cliquons Nouveau

Nous devons maintenant trouver quelque chose comme çà :

[oobas] REM ***** BASIC *****

Sub Main

End Sub

Sub HelloWorld

End Sub Le curseur est positionné au début de la ligne Sub HelloWorld.

Note Maintenant que l'IDE est actif, il peut être accédé depuis le menu Fenêtre d'OpenOffice.org ou par la barre des tâches du système d'exploitation.

Saisie de code

Selectionnons et effaçons :

[oobas] REM ***** BASIC *****

Sub Main

End Sub Au-dessous de la ligne "Sub HelloWorld" entrons msgbox "Hello World!", de manière que l'éditeur ressemble à ceci :

[oobas] Sub HelloWorld

 msgbox "Hello World!"

End Sub

Notes: L'IDE ne fournit aucune fonctionnalité de code completion ni d'aide sur la syntaxe des commandes lors de la frappe. Pour obtenir de l'aide sur une commande Basic, plaçons le curseur dans la commande et tapons F1.
Les commande OpenOffice.org Basic ne sont pas sensibles à la casse. C'est pourquoi msgbox, MSGBOX et Msgbox sont équivalents.
Les chaînes sont entourées de guillements doubles.

Exécution du code

Le code Basic peut être exécuté de plusieurs façons :

Directement dans l'IDE. La barre des macro comprte un bouton Exécter (par défaut, le troisième de la seconde barre d'outils). Ce bouton lance la première macro du module en cours.

Depuis le menu Outils :

(Version 1.1.x) Outils > Macros > Macro…;

(Version 1.9.x et supérieures) Outils > Macros > Exécuter la macro…

Par assignation de la macro à une touche.

Par assignation de la macro à une entrée de menu.

Par assignation de la macro à un bouton de barre d'outil.

En créant un contrôle dans un document.

Par assignation de la macro à un évènement.

Pour l'instant essayons de lancer la procédure "HelloWorld" en cliquant le bouton Exécuter. Un dialogue intitulé "soffice" et comportant le texte "Hello World!" ainsi qu'un bouton OK doit s'afficher.

Enregistrement du code

Le code est enregistré automatiquement chaque fois que son conteneur est lui-même enregistré. Par conséquent, si le code se trouve dans une bibliothèque OpenOffice (partagée ou de l'utilisateur), il est automatiquement enregistré lorsque OpenOffice est refermé. Si le code se trouve dans une bilbiothèque qui fait partie d'un document, alors il est enregistré lorsque le document l'est.

Un bouton Enregistrer figure sur la barre d'outils Standard (celle du haut par défaut). Si le code se trouve à l'intérieur d'un document ou modèle, alors la totalité du document est enregistrée. Si le code se trouve à l'intérieur d'une bibliothèque OpenOffice.org alors seule la bilbiothèque courante est enregistrée.

Les variables

Nous pouvons forcer la déclaration des variables en insérant Option Explicit au début du module. Pour consulter une discussion consacrée à la déclaration ou non des variables, voir : [cette discussion].

Dans cette discussion, on voit que l'auteur de [NdT : la version anglaise de] cette page défendait initialement la déclaration systématique des variables. Depuis lors il a changé d'avis et ne les déclare plus du tout. Bref, c'est une question de préférence personnelle. Dans un cas comme dans l'autre, les préférences de l'auteur vont au nommage des variables selon la convention suivante, qui sera utilisée tout au long des exemples de ce wiki :

La première lettre du nom de la variable indique le type de valeur contenue, telle que présentée à la table ci-dessous (basée sur un tableau dans Tutorial.pdf de Sun)

Lettre Signification
a Structure
b Boolaen (TRUE ou FALSE)
e Enumeration. Cette variable ne peut prendre qu'une valeur parmi un ensemble limité de valeurs.
f Float [NdT : Réel] (de 3.402823 x 1038 à 1.401298 x 10-45. Une variable de type "single" peut occuper jusqu'à quatre octets)
Double (de 1.79769313486232 x 10308 à 4.94065645841247 x 10-324. Une variable de ce type peut occuper jusqu'à huit octets)
Currency (de -922337203685477.5808 à +922337203685477.5807 et occupe jusqu'à huit octets en mémoire)
m Array (aka sequence aka matrice)
n Integer (de -32768 à 32767.) ou
Long (de -2147483648 à 2147483647).
o Object, service ou interface
s String (Une variable string peut mémoriser jusqu'à 65535 caractères Unicode).
x Interface, montre que seules les opérations portant sur une interface particulière d'un objet sont utilisées
v Variant, N'importe quel valeur


Utilisons des noms descriptifs suffisamment longs et employons le style "Camel case" [NdT : usage conjoint des majuscules et des minuscules pour faire ressortir les éléments du nom]

Note: Les variables définies par l'utilisateur en OpenOffice.org Basic ne sont pas sensibles à la casse. Les constantes UNO-API le sont.


Les variables indexant les boucles constituent une exception conventionnelle aux longs noms descriptifs. Des symboles tels que i, j et k sont en effet d'usage fréquent. De même, lorsqu'une chaîne est construite, on utilise fréquemment s..

Editons la routine sub HelloWorld de manière qu'elle ressemble à ceci et exécutons-la :

[oobas] sub HelloWorld dim i as integer 'ligne optionnelle

 for i = 0 to 2
   'Ces lignes sont indentées par souci de lisiblité uniquement
   'Notre code devrait toujours être structuré ainsi pour lui donner des chances de survie
   msgbox "Hello World " & i
 next i

end sub Pour plus d'informations sur les variables, reportons-nous à l'aide en ligne, rubrique "utilisation des variables".

Understanding the OpenOffice.org API

This section will start with an example. The remainder of this section aims to give information so that the example can be understood and expanded upon.

Try running the following code with different types of documents being active.

[oobas] sub main 'basicLibraries.loadLibrary("Xray") 'xray.xray thisComponent msgbox fnWhichComponent(thisComponent) end sub


function fnWhichComponent(oDoc) as string if HasUnoInterfaces(oDoc, "com.sun.star.lang.XServiceInfo") then

  if thisComponent.supportsService ("com.sun.star.text.GenericTextDocument") then
     fnWhichComponent = "Text"
  elseif thisComponent.supportsService("com.sun.star.sheet.SpreadsheetDocument") then
     fnWhichComponent = "Spreadsheet"
  elseif thisComponent.supportsService("com.sun.star.presentation.PresentationDocument") then
     fnWhichComponent = "Presentation"
  elseif thisComponent.supportsService("com.sun.star.drawing.GenericDrawingDocument") then
     fnWhichComponent = "Drawing"
  else
     fnWhichComponent = "Oops current document something else"
  end if

else

  fnWhichComponent = "Not a document"

end if End function

Subroutine naming convention

In the above example the user defined function has a name that starts with the letters "fn". This is the initial author's convention so that people know that this is a user defined function. Similarly, the initial author uses the convention that user defined subroutines start with the letters "sub". When learning a language and an API it can be difficult to know what is built-in and what has been defined elsewhere. This document/wiki will use this convention for naming functions and subroutines.

Introducing the OpenOffice.org API

This section introduces the following terms:

  • Interface
  • Module
  • Service
  • Method
  • Property

Understanding the difference between an interface and a service and what a module is, is not essential to being able to write extensions for OpenOffice.org, but it does help interpreting the documentation, and for introspection purposes. You may need to read this section at least twice.

An interface is a definition of a set of methods (and their arguments) that a service which implements that interface must have.

Interfaces are grouped together in modules for naming purposes. All interfaces (and services) start with the name "com.sun.star" then the name of the module then the name of the interface (or service).

For example most services provide the com.sun.star.beans.XPropertySet interface. This interface is stored in the module "beans" and provides access to the properties of a service. A property is a value whereas a method is an action.

An OpenOffice.org object can have many services.

An OpenOffice.org object may have a service, which implements an interface, in which a method description says that another OpenOffice.org object is returned.

Introspection

HasUnoInterfaces is an OpenOffice.org Basic function for introspection. See this [link] for information on introspection in other languages.

HasUnoInterfaces returns true if all of the specified interfaces are available for the specified object.

Most OpenOffice.org objects provide the method supportsService because they have the interface com.sun.star.lang.XServiceInfo.

In the above example, the OpenOffice.org Basic command, HasUnoInterfaces checks that the current document has the interface com.sun.star.lang.XServiceInfo, because if it doesn't have that interface then it doesn't have the method supportsService, and a run time error would occur if such an object tried to access its nonexistent method.

SupportsService is a method which returns true if the specified service is available. The above examples checks for a service to determine the type of document that is currently active.


X-Ray tool

Using HasUnoInterfaces and supportsService gives information about an object at run time, but checking an object like this would be a nightmare for learning? Thankfully Bernard Marcelly has come to our rescue with the X-Ray tool. The X-Ray tool is available from: [ooomacros]. Download the zip file, unzip the document, open the document in OpenOffice.org, follow the instructions for installation and set-up.

Part of the X-Ray tool set-up is to specify a local copy of the OpenOffice.org SDK. Download the OpenOffice.org SDK from and extract it.

In the above example, at the start of the code, there are two commented lines (comments start with an apostrophe):

[oobas] 'basicLibraries.loadLibrary("Xray") 'xray.xray thisComponent Now that you have the X-Ray tool installed, uncomment these lines (remove the apostrophes) and rerun the macro. From version 5 of Xray the command simply becomes xray.

BasicLibraries is an OpenOffice.org Basic command that returns an object for accessing the OpenOffice.org libraries. The loadLibrary method ensures that the routines in that library are available for use.

xray.xray specifies the xray library and the xray subroutine within that library, thisComponent is the object that is being passed to xray for introspection.

To find the object that you want to work with often requires finding or creating it starting from either StarDesktop or thisComponent.


Desktop, documents, and current selection

StarDesktop and ThisComponent are OpenOffice.org Basic commands that refer to the application and currently active document respectively.

Unlike Microsoft Office, OpenOffice.org is one application with different components. When running some code it maybe useful to check which component is currently active. The above code demonstrates how that checking process can be done.

The Desktop that StarDesktop refers to is conceptual (historically it actually existed) and can be thought of as the OpenOffice.org application.


Creating new documents

To create a new text document:

[oobas] oDoc = StarDesktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, Array()) To create a new spreadsheet document:

[oobas] oDoc = StarDesktop.loadComponentFromURL("private:factory/scalc", "_blank", 0, Array()) An easier approach would be to write a simple function:

[oobas] function fnNewDoc(sDocType as string) fnNewDoc = StarDesktop.loadComponentFromURL("private:factory/" & sDocType , "_blank", 0, Array()) end function Then creating new documents can be achieved with:

[oobas] oDoc = fnNewDoc("swriter") oDoc = fnNewDoc("scalc") oDoc = fnNewDoc("simpress") oDoc = fnNewDoc("sdraw") oDoc = fnNewDoc("smath") See http://api.openoffice.org/docs/common/ref/com/sun/star/frame/XComponentLoader.html .

To open a document

The following example shows how to open a file. For information on URLs in OpenOffice.org see URL Basics.

[oobas] sFile = "C:\Documents and Settings\danny\Desktop\MyCalc.sxc" ' Windows sFile = "/home/danny/Desktop/MyCalc.sxc" ' Linux sURL = ConvertToURL(sFile) oDoc = StarDesktop.loadComponentFromURL(sURL, "_blank", 0, Array()) Again it may make sense to make this easier by writing a simple function:

[oobas] function fnOpenDoc(sFile) sURL = ConvertToURL(sFile) fnOpenDoc = StarDesktop.loadComponentFromURL(sURL, "_blank", 0, Array()) end function Examples of calling the function:

[oobas] oDoc = fnOpenDoc("C:\Documents and Settings\danny\Desktop\MyCalc.sxc") ' Windows oDoc = fnOpenDoc("/home/danny/Desktop/MyCalc.sxc") ' Linux

Current Selection

It is common to want to run some code that effects the current selection. ThisComponent has the method getCurrentSelection. Since many different types of objects could possibly be selected it is common to check that the currently selected object has the service that contains the method that we want to apply to the object.

Edit the main subroutine to the following and rerun it on a text document with different selections. (To select more than one block of text hold down the control key).

[oobas] sub main basicLibraries.loadLibrary("Xray") if fnWhichComponent(thisComponent) = "Text" then

       oCurSelection = thisComponent.getCurrentSelection()
       'xray.xray oCurSelection
       if oCurSelection.supportsService("com.sun.star.text.TextRanges") then
               msgbox "There are " & oCurSelection.getCount() & _
                " selections in the current text document."
       end if

end if end sub With nothing selected the number of selections is one - the insertion point, with one block of text selected the count is still one, but with two blocks of text the count is three - the insertion point and the two blocks of selected text.

Exercise 1: Modify the above code so that it works on selected cell ranges in a spreadsheet.

Question1: For two blocks of cells selected, what would be the count for the number of selections?


Properties

Uncomment 'xray.xray oCurSelection so that xray runs, to see that the object that oCurSelection points to has a "property" called Count with a description of "pseudo-prop, read only". It is possible in OpenOffice.org Basic to write oCurSelection.count, but as this is not possible in all other languages accessing the OpenOffice.org API, this Wiki will try to always use the method approach. (I say try because I have not been in the habit of doing this and sometimes I may forget).

This next example demonstrates changing a property value for the current selections.

[oobas] sub main basicLibraries.loadLibrary("Xray") if fnWhichComponent(thisComponent) = "Text" then

  oCurSelection = thisComponent.getCurrentSelection()
  if oCurSelection.supportsService("com.sun.star.text.TextRanges") then
     nCount = oCurSelection.Count
     'xray.xray oCurSelection.getByIndex(0)
     'Warning: The insertion point will have the same action applied twice
     'in this case it doesn't matter, but in others it might.
     for i = 0 to nCount - 1
        oCurSelection.getByIndex(i).setPropertyValue("CharStyleName", "Strong Emphasis")
     next
  end if

end if end sub In OpenOffice.org Basic it is possible to shorten the assignment line to:

[oobas] oCurSelection(i).CharStyleName = "Strong Emphasis" This wiki will try to use the full methods for both indexing and assigning properties. The rationale is that this makes converting the code to other languages easier and also helps the learner to understand what is happening (again I have not been in the habit of doing this so some examples may slip past me).

Exercise 2: Rewrite the above code so that the warning can be removed.

See Current selection.


Iterative Access to Subordinate Objects (Enumeration access)

Sometimes to access the desired object an enumeration is required. For example paragraphs, within a document or within a selection.

When a Writer document is active and some text is selected, both thisDocument.getText() and thisComponent.getCurrentSelection().getByIndex(i) have the service: com.sun.star.text.TextRange which has the interface: com.sun.star.container.XContentEnumerationAccess, it is possible to create an enumeration of the paragraphs for the current document or for a particular selection.

[oobas] ' Create enumeration object oTextElementEnum = thisComponent.getText().createEnumeration() 'or thisComponent.getCurrentSelection().getByIndex(i).createEnumeration()

' loop over all text elements while oTextElementEnum.hasMoreElements()

       oTextElement = oTextElementEnum.nextElement
       if oTextElement.supportsService("com.sun.star.text.TextTable") then
               MsgBox "The current block contains a table."
       end if
       if oTextElement.supportsService("com.sun.star.text.Paragraph") then
               MsgBox "The current block contains a paragraph."
       end if

wend Exercise 3: Extend the above example to display in a message box all text portions that are bold.


Named access

Some objects provide named access to a particular type of subordinate object, some others indexed access, and some both named and indexed access.

For example if the current document in OpenOffice.org is a spreadsheet then to access a particular sheet can be done by index access:

[oobas] oSheet = thisComponent.getSheets.getByIndex(0) or named access:

[oobas] oSheet = thisComponent.getSheets.getByName("Sheet1") To check if an object with a particular name already exists use hasByName, for example:

[oobas] if thisComponent.getSheets.hasByName("Sheet1") then To loop through all the available object names can be done like:

[oobas] mNames = thisComponent.getSheets.getElementnames for i = lbound(mNames) to ubound(mNames)

       msgbox mNames(i)

next


Some named subordinate objects also provide the interface: com.sun.star.container.XNameContainer. This interface defines that such objects should have the following methods: insertByName, replaceByname and removeByName.

E.g.

[oobas] thisComponent.getSheets.insertByName("NewSheet")

Create new objects

Some objects have services which implement interfaces to provide specific methods for creating a particular type of object.

For example if the current document is a Writer document then thisComponent.getText is an object that provides the service com.sun.star.text.Text which implements the interface com.sun.star.text.XSimpleText which defines the methods createTextCursor and createTextCursorByRange. Both of these methods create a text cursor for accessing the text of the document. These cursors are quite independent of the view cursor . The view cursor is visible on the screen and is manipulated by the user (and can be manipulated by program control), where as a text cursor is not visible on the screen and is solely used by program control. The following code snippet demonstrates creating a new text cursor, such that it starts at the same location as the viewCursor and is then moved independent of the view cursor.

[oobas] oVC = thisComponent.getCurrentController.getViewCursor oCursor = oVC.getText.createTextCursorByRange(oVC) oCursor.gotoStartOfSentence(false) oCursor.gotoEndOfSentence(true) msgbox oCursor.getString

Some objects are context dependent and get created using the method createInstance which is defined in the interface com.sun.star.lang.XMultiServiceFactory. For example to add a rectangle to the first page of a drawing document:

[oobas] dim aPoint as new com.sun.star.awt.Point dim aSize as new com.sun.star.awt.Size

aPoint.x = 1000 aPoint.y = 1000

aSize.Width = 10000 aSize.Height = 10000

oRectangleShape = thisComponent.createInstance("com.sun.star.drawing.RectangleShape") oRectangleShape.Size = aSize oRectangleShape.Position = aPoint

thisComponent.getDrawPages.getByIndex(0).add(oRectangleShape)

This example also uses UNO structs see below for more information on UNO stucts.

Some objects are context independent to create these objects use the OpenOffice.org Basic command createUnoService. For example to create the equivalent to StarDesktop:

[oobas] oDesktop = createUnoService("com.sun.star.frame.Desktop")

The process that I use to determine how to access or create an object is as follows:

Does the object already exist if so I should be able to access it from something like thisComponent.

Will the new object belong to another object, if so does the owner have a specific method for creating the object, if so use it.

The new object will belong to another object, but that object doesn't provide a specific method for creating it, but does provide createInstance. If the object doesn't provide createInstance are you sure you are using the correct object, or is it context independent.

I have found working out how to create an object to be quite difficult with existing documentation so I hope that this document/wiki will eventually make this clear.


UNO structs

UNO structures can be declared using the OpenOffice.org Basic command dim:

[oobas] dim aPoint as new com.sun.star.awt.Point Or by using the OpenOffice.org Basic command createUnoStruct:

[oobas] aPoint = createUnoStruct("com.sun.star.awt.Point")

Note: When declaring UNO structs case is important. Note that everything upto the name of the struct is lowercase, and that the name of the struct is in TitleCase.



Creating Listeners and Handlers

Through the user interface it is possible to assign macros to some events:

OpenOffice.org versions 1.1.x: Tools > Configure… > Events.

OpenOffice.org versions 1.9.x and above: Tools > Customize… > Events.

It is also possible to assign macros to a wider range of events using the OpenOffice.org Basic command CreateUnoListener. This same command is used for creating both listeners and handlers. A listener checks for an event and always allows other listeners to respond to the event as well. A handler listens for an event, and can optionally consume the event so that other listeners don't get to act on it.

The following example creates a keyHandler:

[oobas] global IannzExampleKeyHandler

sub SetupKeyHandler oController = thisComponent.currentController IannzExampleKeyHandler = CreateUnoListener("KeyHandler_","com.sun.star.awt.XKeyHandler") oController.addKeyHandler(IannzExampleKeyHandler) ' Register the listener end sub


sub RemoveKeyHandler thisComponent.currentController.removeKeyHandler(IannzExampleKeyHandler) end sub


sub KeyHandler_disposing end sub


function KeyHandler_keyReleased(oKeyEvent as new com.sun.star.awt.KeyHandler) as boolean

       KeyHandler_keyReleased = False    

end function


function KeyHandler_keyPressed(oKeyEvent as new com.sun.star.awt.KeyHandler) as boolean KeyHandler_keyPressed = false 'Let other listeners handle the event if oKeyEvent.modifiers = com.sun.star.awt.KeyModifier.MOD2 then 'Control key was pressed

       if oKeyEvent.keyCode = com.sun.star.awt.Key.Q then
               msgbox "Alt + Q was pressed"
               KeyHandler_keyPressed = true    'Don't let other listeners process this event
       end if

end if end function A variable declared as global keeps its value even after the macro exits. In this case we want to be able to use this variable later to remove the handler. As variables declared globally could be used in other libraries to try and avoid conflict I start all my global variables with Iannz my registered name for the OpenOffice.org web site.

sub SetupKeyHandler sets up the handler. The first parameter to CreateUnoListener is the staring name for the methods that will be called when that type of event occurs in this example ."KeyHandler_".

The second parameter is the name of the interface for the listener or handler, "com.sun.star.awt.XKeyHandler". The name is case sensitive, everything up to and including the module name is always lowercase, the name of the interface always starts with "X" and the remainder is in TitleCase.

Use the SDK to find out what methods the interface must supply. You must supply routines for all of these methods even if you don't intend to use them. You also need to supply a disposing method. The names of these routines start with the string given in the first parameter to CreateUnoListener , in this example "KeyHandler_".

Thus in the example there is KeyHandler_disposing and KeyHandler_keyReleased which don't actually do anything but are required, and KeyHandler_keyPressed which actually does the job.

sub RemoveKeyHandler demonstrates how to remove the handler.

OpenOffice.org constants

The above example uses OpenOffice.org constants.

E.g. com.sun.star.awt.KeyModifier.MOD2

OpenOffice.org constants are case sensitive. Everything up to and including the module name is always lowercase. The constant group is in TitleCase. The actual constant name is always UPPERCASE.

Programmers not using OpenOffice.org Basic may not have access to these constants.


Using the recorder

See The OpenOffice.org recorder and UNO dispatch calls section for a discussion on recording UNO Dispatch commands versus writing API calls.

See also

Personal tools