Contenido
Índice 🔎︎

# Servicio ScriptForge.UI

The UI (User Interface) service simplifies the identification and the manipulation of the different windows composing the whole LibreOffice application:

- Selección de ventanas

- Redimensionamiento y traslado de ventanas

- Configuración de la barra de estado

- Presentación de una barra de progreso flotante

- Creación de ventanas nuevas

- Acceso a los «documentos» subyacentes

The UI service is the starting point to open, create or access to the content of new or existing documents from a user script.

## Definiciones

### WindowName

A window can be designated using various ways:

- a full path and file name

- the last component of the full file name or even only the last component without its suffix

- el título de la ventana

- para documentos nuevos, algo como «Sin título 1»

- una de las ventanas especiales «BASICIDE» y «WELCOMESCREEN»

El nombre de las ventanas distingue mayúsculas y minúsculas.

### Objeto Document

The methods CreateDocument, CreateBaseDocument, GetDocument, OpenBaseDocument and OpenDocument, described below, generate document objects. When a window contains a document, an instance of the Document class represents that document. A counterexample the Basic IDE is not a document but is a window in our terminology. Additionally a document has a type: Calc, Impress, Writer, ...

The specific properties and methods applicable on documents are implemented in a document class.

The implementation of the document objects class is done in the SFDocuments associated library. See its "Document" service.

## Invocación del servicio

Antes de utilizar el servicio UI, es necesario cargar o importar la biblioteca ScriptForge:

• Para cargar la biblioteca ScriptForge que necesitan las macros de Basic se debe usar la siguiente declaración:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
• Los scripts de Python necesitan importar el módulo 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")

## Propiedades

Nombre | De solo lectura | Tipo | Descripción
--- | --- | --- | ---
ActiveWindow | Sí | String | a valid and unique WindowName for the currently active window. When the window cannot be identified, a zero-length string is returned.
Documents | Sí | String array | The list of the currently open documents. Special windows are ignored. This list consists of a zero-based one dimensional array either of filenames (in SF_FileSystem.FileNaming notation) or of window titles for unsaved documents.
Height | Sí | Integer | Devuelve la altura en píxeles de la ventana activa.
Width | Sí | Integer | Devuelve la anchura de la ventana activa en píxeles.
X | Sí | Integer | Returns the X coordinate of the active window, which is the distance to the left edge of the screen in pixels.
Y | Sí | Integer | Returns the Y coordinate of the active window, which is the distance to the top edge of the screen in pixels. This value does not consider window decorations added by your operating system, so even when the window is maximized this value may not be zero.

## Constantes

Nombre | Valor | Descripción
--- | --- | ---
MACROEXECALWAYS | 2 | Las macros se ejecutan siempre
MACROEXECNEVER | 1 | Las macros no se ejecutan nunca
MACROEXECNORMAL | 0 | La ejecución de macros depende de la configuración del usuario

### Ejemplo:

The examples below show a MsgBox with the names of all currently open documents.

##### 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)

Lista de métodos en el servicio UI
Activate CreateBaseDocument CreateDocument (*) GetDocument Maximize | Minimize OpenBaseDocument OpenDocument (*) Resize | RunCommand SetStatusBar (*) ShowProgressBar WindowExists

Note, as an exception, that the methods marked (*) are not applicable to Base documents.

## Activate

Make the specified window active. The method returns True if the given window is found and can be activated. There is no change in the actual user interface if no window matches the selection.

### Sintaxis:

svc.Activate(windowname: str): bool

### Parámetros:

windowname: vea las definiciones más arriba.

### Ejemplo:

##### En BASIC

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

##### En Python

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

## CreateBaseDocument

Crea y almacena un documento nuevo de LibreOffice Base que incrusta una base de datos vacía del tipo indicado. El método devuelve una instancia del servicio Document.

### Sintaxis:

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

### Parámetros:

filename : Identifies the file to create. It must follow the SF_FileSystem.FileNaming notation. If the file already exists, it is overwritten without warning

embeddeddatabase: puede ser «HSQLDB» (valor predeterminado), «FIREBIRD» o «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.

### Ejemplo:

##### 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.

### Sintaxis:

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

### Parámetros:

documenttype: «Calc», «Writer», etc. Si está ausente, debe existir el argumento templatefile.

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.

### Ejemplo:

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

Devuelve un objeto de documento abierto que hace referencia a la ventana activa, una ventana determinada o el documento activo.

### Sintaxis:

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

svc.GetDocument(windowname: uno): svc

### Parámetros:

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.

### Ejemplo:

##### 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)

Para acceder al nombre de la ventana actualmente activa, vea la propiedad ActiveWindow.

## Maximize

Maximiza la ventana activa o la ventana dada.

### Sintaxis:

svc.Maximize(windowname: str)

### Parámetros:

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

### Ejemplo:

##### En BASIC

          ui.Maximize("Untitled 1")

##### En Python

         ui.Maximize("Untitled 1")

## Minimize

Minimiza la ventana activa o la ventana indicada.

### Sintaxis:

svc.Minimize(windowname: str)

### Parámetros:

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

### Ejemplo:

##### En BASIC

         ui.Minimize()

##### En Python

         ui.Minimize()

## OpenBaseDocument

Abre un documento existente de LibreOffice Base. El método devuelve un objeto de documento.

### Sintaxis:

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

### Parámetros:

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.

### Ejemplo:

##### 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)

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

## OpenDocument (*)

Abre un documento existente de LibreOffice con las opciones especificadas. Devuelve un objeto de documento o una de sus subclases. El método devuelve Nothing (en BASIC) o None (en Python) si falla la apertura, aun si esta falla es resultado de la decisión del usuario.

### Sintaxis:

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

### Parámetros:

filename: identifica el archivo que se debe abrir. Debe seguir la notación de FileNaming del servicio FileSystem.

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: el valor predeterminado es 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: el nombre del filtro que debe utilizarse para cargar el documento. Si está presente, el filtro debe existir.

filteroptions: una cadena facultativa de opciones relacionadas al filtro.

### Ejemplo:

##### 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.

### Sintaxis:

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

### Parámetros:

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

width, height: dimensiones nuevas para la ventana, en píxeles.

### Ejemplo:

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)

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.

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

### Sintaxis:

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

### Parámetros:

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.

### Ejemplo:

##### En BASIC

El ejemplo siguiente ejecuta la orden .uno:About en la ventana actual.

        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.

        ' Argumentos pasados a la orden:
        ' 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)

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.

### Sintaxis:

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

### Parámetros:

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

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

### Ejemplo:

##### En BASIC

          Dim i As Integer
          For i = 0 To 100
              ui.SetStatusbar("Progress ...", i)
              Wait 50
          Next i
          ' Restablece la barra de estado
          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.

### Sintaxis:

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

### Parámetros:

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.

### Ejemplo:

##### En BASIC

          Dim i As Integer
          For i = 0 To 100
              ui.ShowProgressBar("Window Title", "Progress ..." & i & "/100", i)
              Wait 50
          Next i
          ' Cierra la ventana de la barra de progreso
          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)
         # Cierra la ventana de la barra de progreso
         ui.ShowProgressBar()

## WindowExists

Returns True if the given window could be identified.

### Sintaxis:

svc.WindowExists(windowname: str): bool

### Parámetros:

windowname: vea las definiciones más arriba.

### Ejemplo:

##### En BASIC

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

##### En Python

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

Temas relacionados

Servicio ScriptForge.Basic

SFDocuments.Calc service

Servicio SFDocuments.Document