Service ScriptForge.UI

Le service UI (User Interface) simplifie l'identification et la manipulation des diffĂ©rentes fenĂȘtres composant l'ensemble de l'application LibreOffice :

tip

Le service UI est le point de départ pour ouvrir, créer ou accéder au contenu de documents nouveaux ou existants à partir d'un script utilisateur.


Définitions

WindowName

Une fenĂȘtre peut ĂȘtre Ă©bauchĂ©e de diffĂ©rentes maniĂšres :

Le nom de la fenĂȘtre est sensible Ă  la casse.

Objet du document

Les mĂ©thodes CreateDocument, CreateBaseDocument, GetDocument, OpenBaseDocument et OpenDocument, dĂ©crites ci-dessous, gĂ©nĂšrent des objets de document. Lorsqu'une fenĂȘtre contient un document, une instance de la classe Document reprĂ©sente ce document. Un contre-exemple, l'EDI Basic n'est pas un document mais une fenĂȘtre dans notre terminologie. De plus, un document a un type : Calc, Impress, Writer, ...

Les propriétés et méthodes spécifiques applicables aux documents sont implémentées dans une classe de document.

tip

L'implémentation de la classe d'objets document se fait dans la bibliothÚque associée SFDocuments. Voir son service "Document".


Invocation du service

Avant d'utiliser le service UI, la bibliothĂšque ScriptForge doit ĂȘtre chargĂ©e ou importĂ©e :

note

‱ Les macros Basic nĂ©cessitent de charger la bibliothĂšque ScriptForge Ă  l'aide de l'instruction suivante :
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

‱ Les scripts Python nĂ©cessitent un import depuis le module scriptforge :
from scriptforge import CreateScriptService


En Basic :

    Dim ui As Variant
    GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
    Set ui = CreateScriptService("UI")
  
En Python

    from scriptforge import CreateScriptService
    ui = CreateScriptService("UI")
  

Propriétés

Nom

Lecture seule

Type

Description

ActiveWindow

Oui

String

un WindowName valide et unique pour la fenĂȘtre actuellement active. Lorsque la fenĂȘtre ne peut pas ĂȘtre identifiĂ©e, une chaĂźne de longueur nulle est renvoyĂ©e.

Documents

Oui

String array

La liste des documents actuellement ouverts. Les fenĂȘtres spĂ©ciales sont ignorĂ©es. Cette liste se compose d'une matrice unidimensionnelle de base zĂ©ro soit de noms de fichiers (en notation SF_FileSystem.FileNaming) soit de titres de fenĂȘtres pour les documents non enregistrĂ©s.

Height

Oui

Integer

Renvoie la hauteur de la fenĂȘtre active en pixels.

Width

Oui

Integer

Renvoie la largeur de la fenĂȘtre active en pixels.

X

Oui

Integer

Renvoie la coordonnĂ©e X de la fenĂȘtre active, qui correspond Ă  la distance jusqu'au bord gauche de l'Ă©cran en pixels.

Y

Oui

Integer

Renvoie la coordonnĂ©e Y de la fenĂȘtre active, qui correspond Ă  la distance jusqu'au bord supĂ©rieur de l'Ă©cran en pixels. Cette valeur ne prend pas en compte les dĂ©corations de fenĂȘtre ajoutĂ©es par votre systĂšme d'exploitation. Ainsi, mĂȘme lorsque la fenĂȘtre est agrandie, cette valeur peut ne pas ĂȘtre nulle.


Constantes

Nom

Valeur

Description

MACROEXECALWAYS

2

Les macros sont toujours exécutées

MACROEXECNEVER

1

Les macros ne sont jamais exécutées

MACROEXECNORMAL

0

L'exécution des macros dépend des paramÚtres de l'utilisateur


Exemple :

Les exemples ci-dessous montrent une MsgBox avec les noms de tous les documents actuellement ouverts.

En Basic :

      Dim openDocs as Object, strDocs as String
     Set openDocs = ui.Documents()
     strDocs = openDocs(0)
     For i = 1 to UBound(openDocs)
         strDocs = strDocs & Chr(10) & openDocs(i)
     Next i
     MsgBox strDocs
   
En Python

     ui = CreateScriptService("UI")
     bas = CreateScriptService("Basic")
     openDocs = ui.Documents()
     strDocs = "\n".join(openDocs)
     bas.MsgBox(strDocs)
   

Liste des méthodes dans le service UI

Activate
CreateBaseDocument
CreateDocument (*)
GetDocument
Maximize

Minimize
OpenBaseDocument
OpenDocument (*)
Resize

RunCommand
SetStatusBar (*)
ShowProgressBar
WindowExists


warning

Notez, par exception, que les méthodes marquées (*) ne sont pas applicables aux documents Base.


Activate

Rendez la fenĂȘtre spĂ©cifiĂ©e active. La mĂ©thode renvoie True si la fenĂȘtre donnĂ©e est trouvĂ©e et peut ĂȘtre activĂ©e. Il n'y a aucun changement dans l'interface utilisateur rĂ©elle si aucune fenĂȘtre ne correspond Ă  la sĂ©lection.

Syntaxe :

svc.Activate(windowname: str): bool

ParamĂštres :

windowame : voir les définitions ci-dessus.

Exemple :

En Basic :

      ui.Activate("C:\Documents\My file.odt")
    
En Python

      ui.Activate(r"C:\Documents\My file.odt")
    

CreateBaseDocument

Crée et stocke un nouveau document LibreOffice Base intégrant une base de données vide du type donné. La méthode renvoie une instance de service Document.

Syntaxe :

svc.CreateBaseDocument(filename: str, embeddeddatabase: str = 'HSQLDB', registrationname: str = '', opt calcfilename: str): svc

ParamĂštres :

filename : identifie le fichier à créer. Il doit suivre la notation SF_FileSystem.FileNaming. Si le fichier existe déjà, il est écrasé sans avertissement

embeddeddatabase : soit "HSQLDB" (par défaut), "FIREBIRD" ou "CALC".

registrationname : The name used to store the new database in the databases register. When = "" (default), no registration takes place. If the name already exists it is overwritten without warning.

calcfilename : Only when embeddeddatabase = "CALC", calcfilename represents the file containing the tables as Calc sheets. The file must exist or an error is raised.

Exemple :

En Basic :

      Dim myBase As Object, myCalcBase As Object
      Set myBase = ui.CreateBaseDocument("C:\Databases\MyBaseFile.odb", "FIREBIRD")
      Set myCalcBase = ui.CreateBaseDocument("C:\Databases\MyCalcBaseFile.odb", _
          "CALC", , "C:\Databases\MyCalcFile.ods")
   
En Python

     myBase = ui.CreateBaseDocument(r"C:\Databases\MyBaseFile.odb", "FIREBIRD")
     myCalcBase = ui.CreateBaseDocument(r"C:\Databases\MyCalcBaseFile.odb", \
         "CALC", calcfilename = r"C:\Databases\MyCalcFile.ods")
   

CreateDocument (*)

Create a new LibreOffice document of a given type or based on a given template. The method returns a document object.

Syntaxe :

svc.CreateDocument(documenttype: str = '', templatefile: str = '', hidden: bool = False): svc

ParamĂštres :

documenttype : "Calc", "Writer", etc. If absent, the templatefile argument must be present.

templatefile : The full FileName of the template to build the new document on. If the file does not exist, the argument is ignored. The FileSystem service provides the TemplatesFolder and UserTemplatesFolder properties to help to build the argument.

hidden: if True, open the new document in the background (default = False). To use with caution: activation or closure afterwards can only happen programmatically.

Exemple :

In both examples below, the first call to CreateDocument method creates a blank Calc document, whereas the second creates a document from a template file.

En Basic :

      Dim myDoc1 As Object, myDoc2 As Object, FSO As Object
      Set myDoc1 = ui.CreateDocument("Calc")
      Set FSO = CreateScriptService("FileSystem")
      Set myDoc2 = ui.CreateDocument(, FSO.BuildPath(FSO.TemplatesFolder, "personal/CV.ott"))
   
En Python

     myDoc1 = ui.CreateDocument("Calc")
     fs = CreateScriptService("FileSystem")
     myDoc2 = ui.CreateDocument(templatefile = fs.BuildPath(fs.TemplatesFolder, "personal/CV.ott"))
   

GetDocument

Returns an open document object referring to either the active window, a given window or the active document.

Syntaxe :

svc.GetDocument(windowname: str = ''): svc

svc.GetDocument(windowname: uno): svc

ParamĂštres :

windowname: See the definitions above. If this argument is absent, the active window is used. UNO objects of types com.sun.star.lang.XComponent or com.sun.star.comp.dba.ODatabaseDocument are also accepted. Thus passing ThisComponent or ThisDatabaseDocument as argument creates a new SFDocuments.Document, Base or Calc service.

Exemple :

En Basic :

      Dim myDoc As Object
      Set myDoc = ui.GetDocument("C:\Documents\My file.odt")
      Set myBase = ui.GetDocument(ThisDatabaseDocument)
   
En Python

     from scriptforge import CreateScriptService
     bas = CreateScriptService("Basic")
     myDoc = ui.GetDocument(r"C:\Documents\My file.odt")
     myDoc = ui.GetDocument(bas.ThisComponent)
   
tip

To access the name of the currently active window, refer to the ActiveWindow property.


Maximize

Maximizes the active window or the given window.

Syntaxe :

svc.Maximize(windowname: str)

ParamĂštres :

windowname: see the definitions above. If this argument is absent, the active window is maximized.

Exemple :

En Basic :

      ui.Maximize("Untitled 1")
   
En Python

     ui.Maximize("Untitled 1")
   

Minimize

Minimizes the active window or the given window.

Syntaxe :

svc.Minimize(windowname: str)

ParamĂštres :

windowname: see the definitions above. If this argument is absent, the active window is minimized.

Exemple :

En Basic :

     ui.Minimize()
   
En Python

     ui.Minimize()
   

OpenBaseDocument

Open an existing LibreOffice Base document. The method returns a document object.

Syntaxe :

svc.OpenBaseDocument(filename: str = '', registrationname: str = '', macroexecution: int = 0): svc

ParamĂštres :

filename: Identifies the file to open. It must follow the SF_FileSystem.FileNaming notation.

registrationname: The name to use to find the database in the databases register. It is ignored if FileName <> "".

macroexecution: 0 = behaviour is defined by the user configuration, 1 = macros are not executable, 2 = macros are executable.

Exemple :

En Basic :

      Dim myBase As Object
      Set myBase = ui.OpenBaseDocument("C:\Documents\myDB.odb", MacroExecution := ui.MACROEXECALWAYS)
   
En Python

     ui.OpenBaseDocument(r"C:\Documents\myDB.odb", macroexecution = ui.MACROEXECALWAYS)
   
tip

To improve code readability you can use predefined constants for the macroexecution argument, as in the examples above.


OpenDocument (*)

Opens an existing LibreOffice document with the given options. Returns a document object or one of its subclasses. The method returns Nothing (in BASIC) or None (in Python) if the opening failed, even when the failure is caused by a user decision.

Syntaxe :

svc.Opendocument(filename: str, password: str = '', readonly: bool = False, hidden: bool = False, macroexecution: int = 0, filtername: str = '', filteroptions: str = ''): svc

ParamĂštres :

filename: Identifies the file to open. It must follow the FileNaming notation of the FileSystem service.

password: To use when the document is protected. If wrong or absent while the document is protected, the user will be prompted to enter a password.

readonly: Default = False.

hidden: if True, open the new document in the background (default = False). To use with caution: activation or closure afterwards can only happen programmatically.

macroexecution: 0 = behaviour is defined by the user configuration, 1 = macros are not executable, 2 = macros are executable.

filtername: The name of a filter that should be used for loading the document. If present, the filter must exist.

filteroptions: An optional string of options associated with the filter.

Exemple :

En Basic :

      Dim myDoc As Object, FSO As Object
      Set myDoc = ui.OpenDocument("C:\Documents\myFile.odt", ReadOnly := True)
   
En Python

     ui.OpenDocument(r"C:\Documents\myFile.odt", readonly = True)
   

Resize

Resizes and/or moves the active window. Absent and negative arguments are ignored. If the window is minimized or maximized, calling Resize without arguments restores it.

Syntaxe :

svc.Resize(left: int = -1, top: int = -1, width: int = -1, height: int = -1)

ParamĂštres :

left, top: Distances of the top-left corner from top and left edges of the screen, in pixels.

width, height: New dimensions of the window, in pixels.

Exemple :

In the following examples, the width and height of the window are changed while top and left are left unchanged.

En Basic :

      ui.Resize(, ,500, 500)
   
En Python

     ui.Resize(width = 500, height = 500)
   
tip

To resize a window that is not active, first activate it using the Activate method.


RunCommand

Runs a UNO command on the current window. A few typical commands are: Save, SaveAs, ExportToPDF, Undo, Copy, Paste, etc.

Commands can be run with or without arguments. Arguments are not validated before running the command. If the command or its arguments are invalid, then nothing will happen.

tip

For a complete list of UNO commands that can be run in LibreOffice, refer to the Wiki page Development/DispatchCommands.


Syntaxe :

svc.RunCommand(command: str, [args: any])

ParamĂštres :

command: Case-sensitive string containing the UNO command name. The inclusion of the prefix ".uno:" in the command is optional. The command itself is not checked for correctness. If nothing happens after the command call, then the command is probably wrong.

args: For each argument to be passed to the command, specify a pair containing the argument name and value.

Exemple :

En Basic :

The following example runs the .uno:About command in the current window.


    Set ui = CreateScriptService("UI")
    ui.RunCommand("About")
  

Below is an example that runs the UNO command .uno:BasicIDEAppear and passes the arguments required to open the Basic IDE at a specific line of a module.


    ' Arguments passed to the command:
    ' Document  = "LibreOffice Macros & Dialogs"
    ' LibName = "ScriptForge"
    ' Name = "SF_Session"
    ' Line = 600
    ui.RunCommand(".uno:BasicIDEAppear", "Document", "LibreOffice Macros & Dialogs", _ 
                  "LibName", "ScriptForge", "Name", "SF_Session", "Line", 600)
  

Note that calling the command BasicIDEAppear without arguments will simply open the Basic IDE.

En Python

    ui = CreateScriptService("UI")
    ui.RunCommand("About")
  

    ui.RunCommand(".uno:BasicIDEAppear", "Document", "LibreOffice Macros & Dialogs", \
                  "LibName", "ScriptForge", "Name", "SF_Session", "Line", 600)
  

In Python it is also possible to call RunCommand using keyword arguments:


    ui.RunCommand(".uno:BasicIDEAppear", Document = "LibreOffice Macros & Dialogs", \
                  LibName = "ScriptForge", Name = "SF_Session", Line = 600)
  
tip

Each LibreOffice component has its own set of commands available. One easy way to learn commands is going to Tools - Customize - Keyboard. When you position your mouse over a function in the Function list, a tooltip will appear with the corresponding UNO command.


SetStatusbar (*)

Display a text and a progressbar in the status bar of the active window. Any subsequent calls in the same macro run refer to the same status bar of the same window, even if the window is not visible anymore. A call without arguments resets the status bar to its normal state.

Syntaxe :

svc.SetStatusbar(text: str = '', percentage: int = -1)

ParamĂštres :

text: An optional text to be displayed in front of the progress bar.

percentage: an optional degree of progress between 0 and 100.

Exemple :

En Basic :

      Dim i As Integer
      For i = 0 To 100
          ui.SetStatusbar("Progress ...", i)
          Wait 50
      Next i
      ' Resets the statusbar
      ui.SetStatusbar
   
En Python

     from time import sleep
     for i in range(101):
         ui.SetStatusbar("Test:", i)
         sleep(0.05)
     ui.SetStatusbar()
   

ShowProgressBar

Displays a non-modal dialog box. Specify its title, an explicatory text and a percentage of progress to be represented on a progressbar. The dialog will remain visible until a call to the method without arguments or until the user manually closes the dialog.

Syntaxe :

svc.ShowProgressBar(title: str = '', text: str = '', percentage: str = -1)

ParamĂštres :

title : The title appearing on top of the dialog box. Default = "ScriptForge".

text: An optional text to be displayed above the progress bar.

percentage: an optional degree of progress between 0 and 100.

Exemple :

En Basic :

      Dim i As Integer
      For i = 0 To 100
          ui.ShowProgressBar("Window Title", "Progress ..." & i & "/100", i)
          Wait 50
      Next i
      ' Closes the Progress Bar window
      ui.ShowProgressBar
   
En Python

     from time import sleep
     for i in range(101):
         ui.ShowProgressBar("Window Title", "Progress ... " + str(i) + "/100", i)
         sleep(0.05)
     # Closes the Progress Bar window
     ui.ShowProgressBar()
   

WindowExists

Returns True if the given window could be identified.

Syntaxe :

svc.WindowExists(windowname: str): bool

ParamĂštres :

windowname: see the definitions above.

Exemple :

En Basic :

      If ui.WindowExists("C:\Document\My file.odt") Then
          ' ...
   
En Python

     if ui.WindowExists(r"C:\Document\My file.odt"):
         # ...