Wobsah

# Słužba ScriptForge.Session

Słužba Session hromadźi wšelake wšozaměrowe metody wo:

- wokolinje instalacije abo wuwjedźenja

- introspekciji UNO

- wuwołanju eksternych skriptow abo programow

## Słužbowe wuwołanje

Před wužiwanjom słužby Session dyrbi so biblioteka ScriptForge začitać abo importować:

• Makra Basic sej wužaduja, zo so biblioteka ScriptForge z pomocu slědowaceho přikaza začituje:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
• Skripty Python sej import z modula scriptforge wužaduja:
from scriptforge import CreateScriptService

##### W Basic

        GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
        Dim session As Variant
        session = CreateScriptService("Session")

##### W Python

        from scriptforge import CreateScriptService
        session = CreateScriptService("Session")

## Konstanty

Deleka je lisćina konstantow, kotrež su k dispoziciji, zo by so postajenje biblioteki wosnadnja, kotraž skript Basic abo Python wobsahuje, kotryž so ma wuwołać. Wužiwajće je jako session.CONSTANT.

CONSTANT | Hódnota | Hdźe biblioteku namakam? | Nałožujomny
--- | --- | --- | ---
SCRIPTISEMBEDDED | "document" | w dokumenće | Basic + Python
SCRIPTISAPPLICATION | "application" | w zhromadnej bibliotece | Basic
SCRIPTISPERSONAL | "user" | w Moje makra | Python
SCRIPTISPERSOXT | "user:uno_packages" | w rozšěrjenju, kotrež je so wot aktualneho wužiwarja instalowało | Python
SCRIPTISSHARED | "share" | w Nałoženske makra | Python
SCRIPTISSHAROXT | "share:uno_packages" | w rozšěrjenju, kotrež je so za wšěch wužiwarjow instalowało | Python
SCRIPTISOXT | "uno_packages" | w rozšěrjenju, ale instalaciske parametry su njeznate | Python

Lisćina metodow w słužbje Session
ExecuteBasicScript ExecuteCalcFunction ExecutePythonScript GetPDFExportOptions HasUnoMethod | HasUnoProperty OpenURLInBrowser RunApplication SendMail SetPDFExportOptions | UnoMethods UnoProperties UnoObjectType WebService

Metody Execute… w słužbje Session so takle zadźeržuja:
Argumenty so po hódnoće přepodawaja. Změny, kotrež su so přez wuwołanu funkcije na argumentach wuwjedli, swoje hódnoty we wuwołowacym skripće njeaktualizuja.
Jednotliwa hódnota abo matriks so na wuwołowacy skript wróćeja.

## ExecuteBasicScript

Wuwjedźće skript BASIC ze swojim mjenom a městnow a wotwołajće jeho wuslědk, jeli tajki eksistuje.

Jeli skript ničo njewróća, štož za procedury trjechi, kotrež su ze Sub definowane, je wróćena hódnota Empty.

### Syntaksa:

session.ExecuteBasicScript(scope: str, script: str, args: any[0..*]): any

### Parametry:

scope: Znamješkowy rjećazk, kotryž podawa, hdźež so skript składuje. Móže pak "document" (konstanta session.SCRIPTISEMBEDDED) pak "application" (konstanta session.SCRIPTISAPPLICATION) być.

script: Znamješkowy rjećazk, kotryž skript podawa, kotryž so ma w formaće "library.module.method" jako znamješkowy rjećazk wuwołać, kotryž na wulkopisanje dźiwa.

- Biblioteka so do składa začita, jeli trjeba.

- Modul njesmě klasowy modul być.

- Metoda móže Sub abo Function być.

args: Argumenty, kotrež so maja wuwołanemu skriptej přepodać.

### Přikład:

Hladajće na slědowacu funkciju Basic z mjenom DummyFunction, kotraž je w "Moje makra" w bibliotece "Standard" w modulu z mjenom "Module1" składowana.

Funkcija prosće dwě cyłoličbowej hódnoće v1 a v2 přijima a wróća sumu wšěch hódnotow, kotrež so w v1 započinaja a so w v2 kónča.

        Function DummyFunction(v1 as Integer, v2 as Integer) As Long
            Dim result as Long, i as Integer
            For i = v1 To v2
                result = result + i
            Next i
            DummyFunction = result
        End Function

Slědowace přikłady pokazuja, kak so DummyFunction ze skriptow Basic a Python wuwołuje.

##### W Basic

        Dim session : session = CreateScriptService("Session")
        Dim b_script as String, result as Long
        b_script = "Standard.Module1.DummyFunction"
        result = session.ExecuteBasicScript("application", b_script, 1, 10)
        MsgBox result ' 55

##### W Python

        session = CreateScriptService("Session")
        bas = CreateScriptService("Basic")
        b_script = 'Standard.Module1.DummyFunction'
        result = session.ExecuteBasicScript('application', b_script, 1, 10)
        bas.MsgBox(result) # 55

## ExecuteCalcFunction

Wuwjedźe funkciju Calc z jeje jendźelskim mjenom a na zakładźe podatych argumentow.
Jeli argumenty su matriksy, so funkcija jako matriksowa formla wuwjedźe.

Metoda skalar (znamješkowy rjećazk abo numeriski) abo matriks matriksow wróća, wróćenej přez wuwołanje funkcije.

### Syntaksa:

session.ExecuteCalcFunction(calcfunction: str, args: any[0..*]): any

### Parametry:

calcfunction: Mjeno funkcije Calc w jendźelšćinje, kotraž so ma wuwołać.

args: Argumenty, kotrež so maja funkciji Calc přepodać, kotraž so ma wuwołać.
Kóždy argument móže być

- znamješkowy rjećazk, numeriska hódnota, datum pak logiska hódnota (boolean)

- 1D-matriks, 2D-matriks abo matriks matriksow, kotrež horjeka naspomnjene datowe typy kombinuja

- objekt UNO com.sun.star.table.XCellRange

### Přikład:

##### W Basic

        session.ExecuteCalcFunction("AVERAGE", 1, 5, 3, 7) ' 4
        session.ExecuteCalcFunction("ABS", Array(Array(-1, 2, 3), Array(4, -5, 6), Array(7, 8, -9)))(2)(2) ' 9
        session.ExecuteCalcFunction("LN", -3)  ' Generates an error
        ' --------
        table1 = Array("Symbol", "H", "He", "Li")
        table2 = Array("RjadowyLičbnik", 1.0, 2.0, 3.0)
        table3 = Array("Masa", 1.008, 4.0026, 6.94)
        table = Array(table1, table2, table3) ' matriks matriksow
        search = Array("Symbol", "RjadowyLičbnik", "Masa")
        result = session.ExecuteCalcFunction("XLOOKUP", "Masa", search, table)
        MsgBox result(0)(3)  ' 6,94

##### W Python

        session.ExecuteCalcFunction("AVERAGE", 1, 5, 3, 7) # 4
        session.ExecuteCalcFunction("ABS", ((-1, 2, 3), (4, -5, 6), (7, 8, -9)))[2][2] # 9
        session.ExecuteCalcFunction("LN", -3) # Error
        # --------
        table = ( ("Symbol", "H", "He", "Li"),
                  ("AtomicNumber", 1.0, 2.0, 3.0),
                  ("Mass", 1.008, 4.0026, 6.94) )
        search = ("Symbol", "AtomicNumber", "Mass")
        result = session.ExecuteCalcFunction("XLOOKUP", "Mass", search, table)
        basic = CreateScriptService('Basic')
        basic.MsgBox(result[0][3]) # 6.94

## ExecutePythonScript

Wuwjedźće skript Python z jeho městna a z jeho mjenom, wotwołajće jeho wuslědk, štož eksistuje. Wuslědk móže jednotliwa hódnota abo matriks hódnotow być.

Jeli so skript njenamaka, abo jeli ničo njewróća, je wróćena hódnota Empty.

Skriptowa wokolina nałoženskeje programowanskeje tykački (Application Programming Interface, API) wuwjedźenje skriptow mjez Python a Basic abo druhimi podpěranymi programowanskimi rěčemi podpěruje. Argumenty dadźa so mjez wuwołanjemi tam a sem přepodać, jeli su primitiwne datowe typy, kotrež wobě rěči znajetej, a pod wuměnjenjom, zo skriptowa wokolina je porjadnje přetworja.

### Syntaksa:

session.ExecutePythonScript(scope: str, script: str, args: any[0..*]): any

### Parametry:

scope: Jedna z nałožujomnych konstantow, kotrež su horjeka nalistowane. Standardna hódnota je session.SCRIPTISSHARED.

script: Pak "biblioteka/modul.py$metoda" pak "modul.py$metoda" pak "mojeRozšěrjenje.oxt|mójSkript|modul.py$metoda" jako znamješkowy rjećazk, kotryž na wulkopisanje dźiwa.

- library: Rjadowakowa šćežka k modulej Python.

- myScript: Rjadowak, kotryž modul Python wobsahuje.

- module.py: Modul Python.

- method: Funkcija Python.

args: Argumenty, kotrež so maja wuwołanemu skriptej přepodać.

### Přikład:

Wobhladajće sej funkciju Python odd_integers, kotraž je deleka definowana, kotraž lisćinu njerunych cyłych ličbow mjez v1 a v2 wutworja. Předstajće sej, zo so tuta funkcija w dataji z mjenom my_macros.py we wašim rjadowaku wužiwarskich skriptow.

        def odd_integers(v1, v2):
            odd_list = [v for v in range(v1, v2 + 1) if v % 2 != 0]
            return odd_list

Čitajće stronu pomocy Organizacija a městno skriptow Python, zo byšće wjace wo tym zhonił, hdźež so skripty Python składuja.

Slědowace přikłady pokazuja, kak so funkcija odd_integers ze skriptow Basic a Python wuwołuje.

##### W Basic

        Dim script as String, session as Object
        script = "my_macros.py$odd_integers"
        session = CreateScriptService("Session")
        Dim result as Variant
        result = session.ExecutePythonScript(session.SCRIPTISPERSONAL, script, 1, 9)
        MsgBox SF_String.Represent(result)

##### W Python

        session = CreateScriptService("Session")
        script = "my_macros.py$odd_integers"
        result = session.ExecutePythonScript(session.SCRIPTISPERSONAL, script, 1, 9)
        bas.MsgBox(repr(result))

## GetPDFExportOptions

Returns the current PDF export settings defined in the PDF Options dialog, which can be accessed by choosing File - Export as - Export as PDF.

Export options set with the PDF Options dialog are kept for future use. Hence GetPDFExportOptions returns the settings currently defined. In addition, use SetPDFExportOptions to change current PDF export options.

This method returns a Dictionary object wherein each key represent export options and the corresponding values are the current PDF export settings.

Read the PDF Export wiki page to learn more about all available options.

### Syntaksa:

session.GetPDFExportOptions(): obj

### Přikład:

##### W Basic

        Dim expSettings As Object, msg As String, key As String, optLabels As Variant
        expSettings = session.GetPDFExportOptions()
        optLabels = expSettings.Keys
        For Each key in optLabels
            msg = msg + key & ": " & expSettings.Item(key) & Chr(10)
        Next key
        MsgBox msg
        ' Zoom: 100
        ' Changes: 4
        ' Quality: 90
        ' ...

This method is only available for Basic scripts.

## HasUnoMethod

Returns True if an UNO object contains the given method. Returns False when the method is not found or when an argument is invalid.

### Syntaksa:

session.HasUnoMethod(unoobject: uno, methodname: str): bool

### Parametry:

unoobject: The object to inspect.

methodname: the method as a case-sensitive string

### Přikład:

##### W Basic

        Dim a As Variant
        a = CreateUnoService("com.sun.star.sheet.FunctionAccess")
        MsgBox session.HasUnoMethod(a, "callFunction") ' True

##### W Python

        bas = CreateScriptService("Basic")
        a = bas.CreateUnoService("com.sun.star.sheet.FunctionAccess")
        result = session.HasUnoMethod(a, "callFunction")
        bas.MsgBox(result) # True

## HasUnoProperty

Returns True if a UNO object has the given property. Returns False when the property is not found or when an argument is invalid.

### Syntaksa:

session.HasUnoProperty(unoobject: uno, propertyname: str): bool

### Parametry:

unoobject: The object to inspect.

propertyname: the property as a case-sensitive string

### Přikład:

##### W Basic

        Dim svc As Variant
        svc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
        MsgBox session.HasUnoProperty(svc, "Wildcards")

##### W Python

        bas = CreateScriptService("Basic")
        a = bas.CreateUnoService("com.sun.star.sheet.FunctionAccess")
        result = session.HasUnoProperty(a, "Wildcards")
        bas.MsgBox(result) # True

## OpenURLInBrowser

Open a Uniform Resource Locator (URL) in the default browser.

### Syntaksa:

session.OpenURLInBrowser(url: str)

### Parametry:

url: The URL to open.

### Přikład:

        ' Basic
        session.OpenURLInBrowser("help.libreoffice.org/")

        # Python
        session.OpenURLInBrowser("help.libreoffice.org/")

## RunApplication

Executes an arbitrary system command and returns True if it was launched successfully.

### Syntaksa:

session.RunApplication(command: str, parameters: str): bool

### Parametry:

command: The command to execute. This may be an executable file or a document which is registered with an application so that the system knows what application to launch for that document. This method equally starts .bat or shell scripts.The command must be expressed in the current SF_FileSystem.FileNaming notation.

parameters: A list of space separated parameters as a single string. The method does not validate the given parameters, but only passes them to the specified command.

### Přikład:

##### W Basic

        session.RunApplication("Notepad.exe")
        session.RunApplication("C:\\myFolder\\myDocument.odt")
        session.RunApplication("kate", "/home/user/install.txt") ' GNU/Linux

##### W Python

        session.RunApplication("Notepad.exe")
        session.RunApplication(r"C:\\myFolder\\myDocument.odt")
        session.RunApplication("kate", "/home/user/install.txt") # GNU/Linux

## SendMail

Send a message - with optional attachments - to recipients from the user's mail client. The message may be edited by the user before sending or, alternatively, be sent immediately.

### Syntaksa:

session.SendMail(recipient: str, cc: str = '', bcc: str = '', subject: str = '', body: str = '', filenames: str = '', editmessage: bool = True)

### Parametry:

recipient: An email address (the "To" recipient).

cc: A comma-separated list of email addresses (the "carbon copy" recipients).

bcc: A comma-separated list of email addresses (the "blind carbon copy" recipients).

subject: the header of the message.

body: The contents of the message as an unformatted text.

filenames: a comma-separated list of file names. Each file name must respect the SF_FileSystem.FileNaming notation.

editmessage: When True (default), the message is edited before being sent.

### Přikład:

##### W Basic

        session.SendMail("someone@example.com" _
            , Cc := "b@other.fr, c@other.be" _
            , FileNames := "C:\myFile1.txt, C:\myFile2.txt")

##### W Python

        session.SendMail("someone@example.com",
                         cc="john@other.fr, mary@other.be"
                         filenames=r"C:\myFile1.txt, C:\myFile2.txt")

## SetPDFExportOptions

Modifies the PDF export settings defined in the PDF Options dialog, which can be accessed by choosing File - Export as - Export as PDF.

Calling this method changes the actual values set in the PDF Options dialog, which are used by the ExportAsPDF method from the Document service.

This method returns True when successful.

Read the PDF Export wiki page to learn more about all available options.

### Syntaksa:

session.SetPDFExportOptions(pdfoptions: obj): bool

### Parametry:

pdfoptions: Dictionary object that defines the PDF export settings to be changed. Each key-value pair represents an export option and the value that will be set in the dialog.

### Přikład:

##### W Basic

The following example changes the maximum image resolution to 150 dpi and exports the current document as a PDF file.

        Dim newSettings As Object, oDoc As Object
        Set oDoc = CreateScriptService("Document")
        Set newSettings = CreateScriptService("Dictionary")
        newSettings.Add("ReduceImageResolution", True)
        newSettings.Add("MaxImageResolution", 150)
        session.SetPDFExportOptions(newSettings)
        oDoc.ExportAsPDF("C:\Documents\myFile.pdf", Overwrite := True)

This method is only available for Basic scripts.

## UnoMethods

Returns a list of the methods callable from an UNO object. The list is a zero-based array of strings and may be empty.

### Syntaksa:

session.UnoMethods(unoobject: uno): str[0..*]

### Parametry:

unoobject: The object to inspect.

### Přikład:

##### W Basic

        Dim svc : svc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
        Dim methods : methods = session.UnoMethods(svc)
        Dim msg as String
        For Each m in methods
            msg = msg & m & Chr(13)
        Next m
        MsgBox msg

##### W Python

        bas = CreateScriptService("Basic")
        a = bas.CreateUnoService("com.sun.star.sheet.FunctionAccess")
        methods = session.UnoMethods(a)
        msg = "\n".join(methods)
        bas.MsgBox(msg)

## UnoProperties

Returns a list of the properties of an UNO object. The list is a zero-based array of strings and may be empty.

### Syntaksa:

session.UnoProperties(unoobject: uno): str[0..*]

### Parametry:

unoobject: The object to inspect.

### Přikład:

##### W Basic

        Dim svc As Variant
        svc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
        MsgBox SF_Array.Contains(session.UnoProperties(svc), "Wildcards") ' True

##### W Python

        bas = CreateScriptService("Basic")
        svc = bas.CreateUnoService("com.sun.star.sheet.FunctionAccess")
        properties = session.UnoProperties(a)
        b = "Wildcards" in properties
        bas.MsgBox(str(b)) # True

## UnoObjectType

Identify the type of a UNO object as a string.

### Syntaksa:

session.UnoObjectType(unoobject: uno): str

### Parametry:

unoobject: The object to identify.

### Přikład:

##### W Basic

        Dim svc As Variant, txt As String
        svc = CreateUnoService("com.sun.star.system.SystemShellExecute")
        txt = session.UnoObjectType(svc) ' "com.sun.star.comp.system.SystemShellExecute"
        svc = CreateUnoStruct("com.sun.star.beans.Property")
        txt = session.UnoObjectType(svc) ' "com.sun.star.beans.Property"

##### W Python

        bas = CreateScriptService("Basic")
        svc = bas.CreateUnoService("com.sun.star.system.SystemShellExecute")
        txt = session.UnoObjectType(svc) # "com.sun.star.comp.system.SystemShellExecute"
        svc = bas.CreateUnoService("com.sun.star.beans.Property")
        txt = session.UnoObjectType(svc) # "com.sun.star.beans.Property"

## WebService

Get some web content from a URI.

### Syntaksa:

session.WebService(uri: str): str

### Parametry:

uri: URI address of the web service.

### Přikład:

##### W Basic

        session.WebService("wiki.documentfoundation.org/api.php?" _
            & "hidebots=1&days=7&limit=50&action=feedrecentchanges&feedformat=rss")

##### W Python

        session.WebService(("wiki.documentfoundation.org/api.php?"
                           "hidebots=1&days=7&limit=50&action=feedrecentchanges&feedformat=rss"))

Wšě rutiny Basic ScriptForge abo identifikatory, kotrež so z podsmužku „_“ započinaja, su za interne wužiwanje wuměnjene. Njejsu za to myslene, so w makrach Basic abo skriptach Python wužiwać.

Podobne temy

Array Function

Using Calc Functions in Macros

Skripty Python z Basic wuwołać

Słužba ScriptForge.Basic

Słužba ScriptForge.FileSystem

Prošu podpěrajće nas!