Innhald
Innhaldsliste 🔎︎

# Tenesta ScriptForge.UI

T Tenesta UI (User Interface = brukargrensesnitt) gjer identifikasjonen og handsaminga av dei ulike vindauga som heile LibreOffice-programmet er bygd opp av.

- Windows selection

- Flytting og endring av storleiken på vindauga

- Innstillingar for statuslinja

- Å visa ei flytande framdriftslinje

- Laga nye vindauge

- Tilgang til dei underliggjande «dokumenta»

UI-tenesta er utgangspunktet for å opna, laga eller få tilgang til innhaldet i nye eller eksisterande dokument frå eit brukarskript.

## Definisjonar

### WindowName

Eit vindauge kan beskrivast på mange ulike måtar:

- ein full sti med filnamn

- den siste komponenten i det fulle filnamnet, eller endatil den siste komponenten utan filetternamnet

- tittelen på vindauget

- for nye dokument, noko som liknar på «Utan tittel 1»

- eit av spesialvindauga «BASICIDE» og «WELCOMESCREEN»

Namnet på vindauget skil mellom store og små bokstavar.

### Document-objektet

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

Dei spesifikke eigenskapane og metodane som kan brukast på dokument er implementerte i ein dokument-klasse.

Implementeringa av dokument-objektklassen vert gjort i det tilknytte biblioteket SFDocuments. Sjå tenesta for dette i "Document".

## Oppkall av tenester

Before using the UI service the ScriptForge library needs to be loaded or imported:

• Basic macros require to load ScriptForge library using the following statement:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
• Python scripts require an import from scriptforge module:
from scriptforge import CreateScriptService

##### I Basic

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

##### I Python

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

## Eigenskapar

Namn | Skriveverna | Type | Beskriving
--- | --- | --- | ---
ActiveWindow | Ja | String | eit gyldig og unikt WindowName til det gjeldande aktive vindauget. Når vindauget ikkje kan identifiserast, vert det returnert ein streng med null lengd.
Documents | Ja | String array | Lista over gjeldande opne dokument. Spesialvindauge vert ignorerte. Denne lista består av ei null-basert eindimensjonal matrise av anten filnamn (i SF_FileSystem.FileNaming-notasjon) eller av titlar på dokument som ikkje er lagra.
Height | Yes | Integer | Returns the height of the active window in pixels.
Width | Yes | Integer | Returns the width of the active window in pixels.
X | Yes | Integer | Returns the X coordinate of the active window, which is the distance to the left edge of the screen in pixels.
Y | Yes | 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.

## Konstantar

Namn | Verdi | Beskriving
--- | --- | ---
MACROEXECALWAYS | 2 | Makroar vert alltid utført
MACROEXECNEVER | 1 | Makroar vert aldri utført
MACROEXECNORMAL | 0 | Køyringa av makroar er avhengig av brukarinnstillingane

### Eksempel:

Eksemplet nedanfor viser ein MsgBox med namna på alle gjeldande opne dokument.

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

##### I Python

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

Liste over metodar i tenesta UI
Activate CreateBaseDocument CreateDocument (*) GetDocument Maximize | Minimize OpenBaseDocument OpenDocument (*) Resize | RunCommand SetStatusBar (*) ShowProgressBar WindowExists

Merk, som eit unnatak, at metodane merkt med (*) ikkje kan brukast i Basedokument.

## Activate

Gjer det gjevne vindauget aktivt. Metoden returnerer Sann viss det gjevne vindauget vert funne og kan aktiverast. Det er ingen endring i det gjeldande brukargrensesnittet viss ingen vindauge samsvarar med valet.

### Syntaks:

svc.Activate(windowname: str): bool

### Parametrar:

windowname: sjå definisjonane ovanfor.

### Eksempel:

##### I Basic

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

##### I Python

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

## CreateBaseDocument

Opprettar og lagrar eit nytt LibreOffice Base-dokument som byggjar inn ein tom database av den gjevne typen. Metoden returnerer ein førekomst av tenesta Document.

### Syntaks:

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

### Parametrar:

filname: Identifiserer fila som skal opprettast. Det må følgja SF_FileSystem.FileNaming-notasjonen. Viss fila finst frå før, vert ho overskrive utan varsel

embeddeddatabase: Anten «HSQLDB» (standard), «FIREBIRD» eller «CALC».

registrationname : Namnet som vert brukt til å lagra den nye databasen i databaseregisteret. Når = "" (standard), vert ingenting registrert. Viss namnet er i bruk frå før, vert det overskrive utan varsel.

calcfilename: Berre når embeddeddatabase = "CALC", representerer calcfilename fila som inneheld tabellane som Calc-ark. Fila må finnast frå før, elles vert det generert det ein feil.

### Eksempel:

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

##### I 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 (*)

Opprett eit nytt LibreOffice-dokument av ein gjeven type eller basert på ein gjeven mal. Metoden returnerer eit dokumentobjekt.

### Syntaks:

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

### Parametrar:

documenttype : «Calc», «Writer»,osv. Viss denne manglar, må argumentet templatefile vera til stades.

templatefile: Det fullstendige FileName på malen som det nye dokumentet skal byggjast på. Viss fila ikkje finst, vert det sett bort frå argumentet. Tenesta FileSystem inneheld eigenskapane TemplatesFolder og UserTemplatesFolder som hjelper til med å byggja argumentet.

hidden: viss Sann, opnar du det nye dokumentet i bakgrunnen (standard = Usann). Må brukast med varsemd sidan å aktivering eller lukking seinare berre kan skje programmatisk.

### Eksempel:

I begge eksempla nedanfor set det første kallet til metoden CreateDocument opp eit tomt Calc-dokument, medan det andre set opp eit dokument frå ei malfil.

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

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

### Syntaks:

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

svc.GetDocument(windowname: uno): svc

### Parametrar:

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.

### Eksempel:

##### I Basic

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

##### I Python

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

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

## Maximize

Maximizes the active window or the given window.

### Syntaks:

svc.Maximize(windowname: str)

### Parametrar:

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

### Eksempel:

##### I Basic

          ui.Maximize("Untitled 1")

##### I Python

         ui.Maximize("Untitled 1")

## Minimize

Minimizes the active window or the given window.

### Syntaks:

svc.Minimize(windowname: str)

### Parametrar:

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

### Eksempel:

##### I Basic

         ui.Minimize()

##### I Python

         ui.Minimize()

## OpenBaseDocument

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

### Syntaks:

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

### Parametrar:

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.

### Eksempel:

##### I Basic

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

##### I 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 (*)

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

### Syntaks:

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

### Parametrar:

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.

### Eksempel:

##### I Basic

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

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

### Syntaks:

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

### Parametrar:

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.

### Eksempel:

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

##### I Basic

          ui.Resize(, ,500, 500)

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

### Syntaks:

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

### Parametrar:

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.

### Eksempel:

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

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

### Syntaks:

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

### Parametrar:

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

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

### Eksempel:

##### I Basic

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

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

### Syntaks:

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

### Parametrar:

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.

### Eksempel:

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

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

### Syntaks:

svc.WindowExists(windowname: str): bool

### Parametrar:

windowname: see the definitions above.

### Eksempel:

##### I Basic

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

##### I Python

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

Liknande emne

Tenesta ScriptForge.Basic

SFDocuments.Calc

Tenesta SFDocuments.Document