Necessitamos da sua ajuda!

ScriptForge.Session serviço

O serviço Session reúne vários métodos de uso geral relacionados com:

Chamada de serviço

Antes de utilizar o serviço Session, é necessário carregar ou importar a biblioteca ScriptForge:

Ícone de nota

• As macros básicas requerem o carregamento da biblioteca ScriptForge através da seguinte instrução:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Os scripts Python requerem a importação do módulo scriptforge:
from scriptforge import CreateScriptService


Em Basic

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

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

Constantes

Segue-se uma lista de constantes disponíveis para facilitar a indicação da biblioteca que contém um script em Basic ou Python a ser executado. Utilize-as na forma session.CONSTANT.

CONSTANT

Valor

Onde fica a biblioteca?

Aplicável

SCRIPTISEMBEDDED

"document"

no documento

Basic + Python

SCRIPTISAPPLICATION

"application"

em qualquer biblioteca partilhada

Basic

SCRIPTISPERSONAL

"user"

em As minhas macros

Python

SCRIPTISPERSOXT

"user:uno_packages"

numa extensão instalada para o utilizador atual

Python

SCRIPTISSHARED

"share"

em Macros da aplicação

Python

SCRIPTISSHAROXT

"share:uno_packages"

numa extensão instalada para todos os utilizadores

Python

SCRIPTISOXT

"uno_packages"

numa extensão, mas os parâmetros de instalação são desconhecidos

Python


Lista de métodos do serviço de sessão

ExecuteBasicScript
ExecuteCalcFunction
ExecutePythonScript
GetPDFExportOptions
HasUnoMethod

HasUnoProperty
OpenURLInBrowser
RunApplication
SendMail
SetPDFExportOptions

UnoMethods
UnoProperties
UnoObjectType
WebService


Ícone da dica

Os métodos Execute... no serviço Session comportam-se da seguinte forma:
Os argumentos são passados por valor. As alterações feitas pela função chamada aos argumentos não atualizam os seus valores no script de chamada.
É devolvido ao script de chamada um único valor ou um conjunto de valores.


ExecuteBasicScript

Executar o script BASIC, indicando o seu nome e localização, e obter o seu resultado, caso exista.

Se o script não devolver nada, o que acontece no caso de procedimentos definidos com Sub, o valor devolvido é Empty.

Sintaxe:

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

Parâmetros:

scope: String que especifica onde o script está armazenado. Pode ser «document» (constante session.SCRIPTISEMBEDDED) ou «application» (constante session.SCRIPTISAPPLICATION).

script: Cadeia de caracteres que especifica o script a ser chamado no formato «biblioteca.módulo.método», sendo que se distingue entre maiúsculas e minúsculas.

args: Os argumentos a passar ao script chamado.

Exemplo:

Considere a seguinte função básica denominada DummyFunction, que se encontra armazenada em «As minhas macros», na biblioteca «Padrão», dentro de um módulo denominado «Módulo1».

A função recebe simplesmente dois valores inteiros, v1 e v2, e devolve a soma de todos os valores que começam em v1 e terminam em v2.


    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
  

Os exemplos abaixo mostram como chamar DummyFunction a partir de scripts em Basic e Python.

Em 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
  
Em 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

Execute uma função do Calc utilizando o seu nome em inglês e com base nos argumentos fornecidos.
Se os argumentos forem matrizes, a função é executada como uma fórmula de matriz.

O método devolve um escalar (cadeia de caracteres ou valor numérico) ou o conjunto de matrizes devolvido pela chamada à função.

Sintaxe:

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

Parâmetros:

calcfunction: O nome da função do Calc a ser chamada, em inglês.

args: Os argumentos a passar à função Calc chamada.
Cada argumento pode ser

Exemplo:

Em 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)  ' Gera um erro
    ' --------
    table1 = Array("Símbolo", "H", "He", "Li")
    table2 = Array("Número Atómico", 1,0, 2,0, 3,0)
    table3 = Array("Massa", 1,008, 4,0026, 6,94)
    table = Array(table1, table2, table3)  ' matriz de matrizes
    search = Array("Símbolo", "Número Atómico", "Massa")
    result = session.ExecuteCalcFunction("XLOOKUP", "Mass", search, table)
    MsgBox result(0)(3)  ' 6,94
  
Em 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

Executar o script Python com base na sua localização e nome e, caso haja, obter o seu resultado. O resultado pode ser um único valor ou um conjunto de valores.

Se o script não for encontrado, ou se não devolver qualquer resultado, o valor devolvido é Vazio.

A estrutura de scripts da Interface de Programação de Aplicações (API) LibreOfficeDev suporta a execução de scripts entre linguagens, nomeadamente entre Python e Basic, ou outras linguagens de programação compatíveis. Os argumentos podem ser transmitidos entre chamadas, desde que representem tipos de dados primitivos reconhecidos por ambas as linguagens e partindo do princípio de que a estrutura de scripts os converte adequadamente.

Sintaxe:

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

Parâmetros:

scope: One of the applicable constants listed above. The default value is session.SCRIPTISSHARED.

script: Either "library/module.py$method" or "module.py$method" or "myExtension.oxt|myScript|module.py$method" as a case-sensitive string.

args: The arguments to be passed to the called script.

Exemplo:

Consider the Python function odd_integers defined below that creates a list with odd integer values between v1 and v2. Suppose this function is stored in a file named my_macros.py in your user scripts folder.


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

Read the help page Python Scripts Organization and Location to learn more about where Python scripts can be stored.


The following examples show how to call the function odd_integers from within Basic and Python scripts.

Em 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)
  
Em 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.

Ícone da dica

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


Sintaxe:

session.GetPDFExportOptions(): obj

Exemplo:

Em 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
    ' ...
  
Ícone de nota

Este método só está disponível para scripts Basic.


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.

Sintaxe:

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

Parâmetros:

unoobject: The object to inspect.

methodname: the method as a case-sensitive string

Exemplo:

Em Basic

    Dim a As Variant
    a = CreateUnoService("com.sun.star.sheet.FunctionAccess")
    MsgBox session.HasUnoMethod(a, "callFunction") ' True
  
Em 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.

Sintaxe:

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

Parâmetros:

unoobject: The object to inspect.

propertyname: the property as a case-sensitive string

Exemplo:

Em Basic

    Dim svc As Variant
    svc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
    MsgBox session.HasUnoProperty(svc, "Wildcards")
  
Em 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.

Sintaxe:

session.OpenURLInBrowser(url: str)

Parâmetros:

url: The URL to open.

Exemplo:


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

Sintaxe:

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

Parâmetros:

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.

Exemplo:

Em Basic

    session.RunApplication("Notepad.exe")
    session.RunApplication("C:\\myFolder\\myDocument.odt")
    session.RunApplication("kate", "/home/user/install.txt") ' GNU/Linux
  
Em 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.

Sintaxe:

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

Parâmetros:

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.

Exemplo:

Em Basic

    session.SendMail("someone@example.com" _
        , Cc := "b@other.fr, c@other.be" _
        , FileNames := "C:\myFile1.txt, C:\myFile2.txt")
  
Em 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.

Ícone da dica

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


Sintaxe:

session.SetPDFExportOptions(pdfoptions: obj): bool

Parâmetros:

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.

Exemplo:

Em 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)
  
Ícone de nota

Este método só está disponível para scripts Basic.


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.

Sintaxe:

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

Parâmetros:

unoobject: The object to inspect.

Exemplo:

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

Sintaxe:

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

Parâmetros:

unoobject: The object to inspect.

Exemplo:

Em Basic

    Dim svc As Variant
    svc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
    MsgBox SF_Array.Contains(session.UnoProperties(svc), "Wildcards") ' True
  
Em 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.

Sintaxe:

session.UnoObjectType(unoobject: uno): str

Parâmetros:

unoobject: The object to identify.

Exemplo:

Em 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"
  
Em 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.

Sintaxe:

session.WebService(uri: str): str

Parâmetros:

uri: URI address of the web service.

Exemplo:

Em Basic

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

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

Todas as rotinas ou identificadores do ScriptForge Basic que tenham o caractere de sublinhado «_» como prefixo estão reservados para uso interno. Não se destinam a ser utilizados em macros do Basic ou em scripts Python.