Serviço.ScriptForge Basic

O serviço ScriptForge.Basic disponibiliza um conjunto de métodos LibreOffice Basic para serem executados num contexto Python. Os métodos do serviço Basic reproduzem exatamente a sintaxe e o comportamento das funções integradas do Basic.

Exemplo típico:


   bas.MsgBox('Exibir este texto numa caixa de mensagem a partir de um script Python')
  
warning

O serviço ScriptForge.Basic está limitado a scripts em Python.


Chamada de serviço

note

Antes de utilizar o serviço Basic, importe o método CreateScriptService() do módulo scriptforge:



    from scriptforge import CreateScriptService
    bas = CreateScriptService("Basic")
  

Propriedades

Nome

Somente leitura

Tipo

Descrição

MB_OK, MB_OKCANCEL, MB_RETRYCANCEL, MB_YESNO, MB_YESNOCANCEL

Sim

Integer

Valores: 0, 1, 5, 4, 3

MB_ICONEXCLAMATION, MB_ICONINFORMATION, MB_ICONQUESTION, MB_ICONSTOP

Sim

Integer

Valores: 48, 64, 32, 16

MB_ABORTRETRYIGNORE, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3

Sim

Integer

Valores: 2, 128, 256, 512

IDABORT, IDCANCEL, IDIGNORE, IDNO, IDOK, IDRETRY, IDYES

Sim

Integer

Valores: 3, 2, 5, 7, 1, 4, 6
Constantes que indicam o botão selecionado MsgBox.

StarDesktop

Sim

Objeto
UNO

Devolve o objeto StarDesktop que representa a aplicação LibreOffice.

ThisComponent

Sim

Objeto
UNO

Se o componente atual se referir a um documento LibreOffice, este método devolve o objeto UNO que representa o documento. Esta propriedade devolve None quando o componente atual não corresponde a um documento.

ThisDatabaseDocument

Sim

Objeto
UNO

Se o script estiver a ser executado a partir de um documento Base ou de qualquer um dos seus subcomponentes, este método devolve o componente principal da instância Base. Caso contrário, esta propriedade devolve None.


Lista de métodos do serviço básico

CDate
CDateFromUnoDateTime
CDateToUnoDateTime
ConvertFromUrl (*)
ConvertToUrl (*)
CreateUnoService
CreateUnoStruct (*)
DateAdd

DateDiff
DatePart
DateValue
Format
GetDefaultContext
GetGuiType (*)
GetPathSeparator (*)
GetSystemTicks

GlobalScope.BasicLibraries
GlobalScope.DialogLibraries
InputBox (*)
MsgBox (*)
Now
RGB
Xray


note

Existem alternativas em Python para os métodos assinalados com (*).


CDate

Converte uma expressão numérica ou uma cadeia de caracteres num objeto nativo do Python do tipo datetime.datetime.

note

Este método disponibiliza a função incorporada do Basic CDate para scripts Python.


Sintaxe:

svc.CDate(expression: any): obj

Parâmetros:

expression: uma expressão numérica ou uma cadeia de caracteres que representa uma data.

When you convert a string expression, the date and time must be entered either in one of the date acceptance patterns defined for your locale setting (see - Languages and Locales - General) or in ISO date format (momentarily, only the ISO format with hyphens, e.g. "2012-12-31" is accepted). In numeric expressions, values to the left of the decimal represent the date, beginning from December 31, 1899. Values to the right of the decimal represent the time.

Exemplo:


    d = bas.CDate(1000.25)
    bas.MsgBox(str(d)) # 1902-09-26 06:00:00
    bas.MsgBox(d.year) # 1902
  

CDateFromUnoDateTime

Converte uma representação de data/hora do UNO num objeto nativo do Python do tipo datetime.datetime.

Sintaxe:

svc.CDateFromUnoDateTime(unodate: uno): obj

Parâmetros:

unodate: Um objeto de data/hora UNO de um dos seguintes tipos: com.sun.star.util.DateTime, com.sun.star.util.Date ou com.sun.star.util.Time

Exemplo:

O exemplo seguinte cria um objeto com.sun.star.util.DateTime e converte-o num objeto Python datetime.datetime.


    uno_date = bas.CreateUnoStruct('com.sun.star.util.DateTime')
    uno_date.Year = 1983
    uno_date.Month = 2
    uno_date.Day = 23
    new_date = bas.CDateFromUnoDateTime(uno_date)
    bas.MsgBox(str(new_date)) # 1983-02-23 00:00:00
  

CDateToUnoDateTime

Converte uma representação de data num objeto com.sun.star.util.DateTime.

Sintaxe:

svc.CDateToUnoDateTime(date: obj): uno

Parâmetros:

data: Um objeto de data/hora em Python de um dos seguintes tipos: datetime.datetime, datetime.date, datetime.time, float (time.time) ou time.struct_time.

Exemplo:


    from datetime import datetime
    current_datetime = datetime.now()
    uno_date = bas.CDateToUnoDateTime(current_datetime)
    bas.MsgBox(str(uno_date.Year) + "-" + str(uno_date.Month) + "-" + str(uno_date.Day))
  

ConvertFromUrl

Devolve um nome de ficheiro com o caminho do sistema para o URL file: indicado.

Sintaxe:

svc.ConvertFromUrl(url: str): str

Parâmetros:

url: Um URL file: absoluto.

Return type:

Um nome de ficheiro no caminho do sistema.

Exemplo:


    filename = bas.ConvertFromUrl( "file:///C:/Program%20Files%20(x86)/LibreOffice/News.txt" )
    bas.MsgBox(filename)
  
tip

O módulo uno O método fileUrlToSystemPath() devolve um caminho do sistema utilizando uma sintaxe idêntica.



    import uno
    filename = uno.fileUrlToSystemPath( "file:///C:/Program%20Files%20(x86)/LibreOffice/News.txt" )
    bas.MsgBox(filename)
  

ConvertToUrl

Devolve um URL file: para o caminho de sistema indicado.

Sintaxe:

svc.ConvertToUrl(systempath: str): str

Parâmetros:

systempath: Um nome de ficheiro do sistema na forma de uma cadeia de caracteres.

Return type:

Um URL file: na forma de uma cadeia de caracteres.

Exemplo:


    url = bas.ConvertToUrl( 'C:\Program Files(x86)\LibreOffice\News.txt' )
    bas.MsgBox(url)
  
tip

O método systemPathToFileUrl() do módulo uno devolve um URL de ficheiro para o caminho de sistema indicado.



    from uno import systemPathToFileUrl as ConvertToUrl
    filename = ConvertToUrl( 'C:\Program Files(x86)\LibreOffice\News.txt' )
    bas.MsgBox(filename)
  

CreateUnoService

Instancia um serviço UNO com o ProcessServiceManager.

Sintaxe:

svc.CreateUnoService(servicename: str): uno

Parâmetros:

servicename: Um nome de serviço totalmente qualificado, como com.sun.star.ui.dialogs.FilePicker ou com.sun.star.sheet.FunctionAccess.

Exemplo:


    dsk = bas.CreateUnoService('com.sun.star.frame.Desktop')
  

CreateUnoStruct

Devolve uma instância de uma estrutura UNO do tipo especificado.

Sintaxe:

svc.CreateUnoStruct(unostructure: str): uno

Parâmetros:

unostrutura: Um nome de estrutura totalmente qualificado, como com.sun.star.beans.Property ou com.sun.star.util.DateTime.

Exemplo:


    date_struct = CreateUnoStruct('com.sun.star.util.DateTime')
  
tip

módulo Uno O método createUnoStruct() cria uma instância de um tipo de estrutura Uno.



    import uno
    p = uno.createUnoStruct( 'com.sun.star.beans.Property' )
    bas.MsgBox(p)
  

DateAdd

Adiciona um intervalo de tempo a uma determinada data/hora um determinado número de vezes e devolve a data resultante.

Sintaxe:

svc.DateAdd(interval: str, number: num, date: datetime): datetime

Parâmetros:

interval: Uma expressão de cadeia de caracteres da tabela seguinte, que especifica o intervalo de data ou hora.

interval (string value)

Explicação

yyyy

Ano

q

Trimestre

m

Mês

y

Dia do ano

w

Dia da semana

ww

Semana do ano

d

Dia

h

Hora

n

Minuto

s

Segundo


number: Uma expressão numérica que especifica com que frequência o valor do interval será somado, se for positivo, ou subtraído, se for negativo.

data: Um determinado valor datetime.datetime; o valor interval será adicionado number vezes a este valor datetime.datetime.

Return type:

Um valor datetime.datetime.

Exemplo:


    dt = datetime.datetime(2004, 1, 31)
    dt = bas.DateAdd("m", 1, dt)
    print(dt)
  

DateDiff

Devolve o número de intervalos de data ou hora entre dois valores de data/hora especificados.

Sintaxe:

svc.DateDiff(interval: str, date1: datetime, date2: datetime, firstdayofweek = 1, firstweekofyear = 1): int

Parâmetros:

interval: Uma expressão de cadeia de caracteres que especifica o intervalo de datas, conforme detalhado no método DateAdd acima.

date1, date2: Os dois valores datetime.datetime a comparar.

firstdayofweek: An optional parameter that specifies the starting day of a week.

firstdayofweek value

Explicação

0

Utilizar o valor do sistema

1

domingo (padrão)

2

segunda-feira

3

terça-feira

4

quarta-feira

5

quinta-feira

6

sexta-feira

7

sábado


firstweekofyear: An optional parameter that specifies the starting week of a year.

firstweekofyear value

Explicação

0

Utilizar o valor do sistema

1

Semana 1 é a semana de 1 de janeiro (padrão)

2

Semana 1 é a primeira semana que contém quatro ou mais dias desse ano

3

Semana 1 é a primeira semana que só contém dias do novo ano


Return type:

Um número.

Exemplo:


    date1 = datetime.datetime(2005,1, 1)
    date2 = datetime.datetime(2005,12,31)
    diffDays = bas.DateDiff('d', date1, date2)
    print(diffDays)
  

DatePart

A função DatePart devolve uma parte específica de uma data.

Sintaxe:

svc.DatePart(interval: str, date: datetime, firstdayofweek = 1, firstweekofyear = 1): int

Parâmetros:

interval: Uma expressão de cadeia de caracteres que especifica o intervalo de datas, conforme detalhado no método DateAdd acima.

date: A data e hora a partir da qual o resultado é calculado.

firstdayofweek, firstweekofyear: parâmetros opcionais que especificam, respetivamente, o dia inicial da semana e a semana inicial do ano, conforme detalhado no método DateDiff acima.

Return type:

A parte extraída para a data/hora indicada.

Exemplo:


    print(bas.DatePart("ww", datetime.datetime(2005,12,31)
    print(bas.DatePart('q', datetime.datetime(1999,12,30)
  

DateValue

Calcula um valor de data a partir de uma cadeia de caracteres de data.

Sintaxe:

svc.DateValue(date: str): datetime

Parâmetros:

date: A string that contains the date that will be converted to a Date object.

note

The string passed to DateValue must be expressed in one of the date formats defined by your locale setting (see - Languages and Locales - General) or using the ISO date format "yyyy-mm-dd" (year, month and day separated by hyphens).


Return type:

A data calculada.

Exemplo:


    dt = bas.DateValue("23-02-2011")
    print(dt)
  

Format

Converte um número numa cadeia de caracteres e, em seguida, formata-o de acordo com o formato que especificar.

Sintaxe:

svc.Format(expression: any, format = ''): str

Parâmetros:

expression: Numeric expression that you want to convert to a formatted string.

format: String that specifies the format code for the number. If format is omitted, the Format function works like the LibreOffice Basic Str() function.

Return type:

Text string.

Códigos de formatação

In BASIC, a format code can be divided into three sections that are separated by semicolons. The first part defines the format for positive values, the second part for negative values, and the third part for zero. If you only specify one format code, it applies to all numbers.

You can set the locale used for controlling the formatting numbers, dates and currencies in LibreOffice Basic in - Languages and Locales - General. In Basic format codes, the decimal point (.) is always used as placeholder for the decimal separator defined in your locale and will be replaced by the corresponding character.

O mesmo é aplicável às configurações regionais para data, hora e moeda. O código de formatação do Basic será interpretado e mostrado de acordo com a configuração regional do utilizador.

The following list describes the codes that you can use for formatting a numeric expression:

Code

Description

0

If expression has a digit at the position of the 0 in the format code, the digit is displayed, otherwise a zero is displayed.

If expression has fewer digits than the number of zeros in the format code, (on either side of the decimal), leading or trailing zeros are displayed. If the expression has more digits to the left of the decimal separator than the amount of zeros in the format code, the additional digits are displayed without formatting.

Decimal places in the expression are rounded according to the number of zeros that appear after the decimal separator in the format code.

#

If expression contains a digit at the position of the # placeholder in the format code, the digit is displayed, otherwise nothing is displayed at this position.

This symbol works like the 0, except that leading or trailing zeroes are not displayed if there are more # characters in the format code than digits in the expression. Only the relevant digits of the expression are displayed.

. (period)

The decimal placeholder determines the number of decimal places to the left and right of the decimal separator.

If the format code contains only # placeholders to the left of this symbol, numbers less than 1 begin with a decimal separator. To always display a leading zero with fractional numbers, use 0 as a placeholder for the first digit to the left of the decimal separator.

A utilização do ponto como separador de milhares e decimal depende da configuração regional. Ao introduzir um número no código fonte do Basic, utilize sempre um ponto como separador decimal. O carácter mostrado como separador decimal depende do formato numérico nas definições do sistema.

%

Multiplies the expressionby 100 and inserts the percent sign (%) where the expression appears in the format code.

E- E+ e- e+

If the format code contains at least one digit placeholder (0 or #) to the right of the symbol E-, E+, e-, or e+, the expression is formatted in the scientific or exponential format. The letter E or e is inserted between the number and the exponent. The number of placeholders for digits to the right of the symbol determines the number of digits in the exponent.

Se o expoente for negativo, é mostrado um sinal negativo antes de um expoente com E-, E+, e-, e+. Se o expoente for positivo, só é mostrado o sinal de mais antes dos expoentes com E+ ou e+.

- + $ ( ) space

: A plus (+), minus (-), dollar ($), space, or brackets entered directly in the format code is displayed as a literal character.

\

Para mostrar diferentes dos que aqui estão listados, terá de precedê-los com uma barra invertida (\) ou colocá-los entre aspas (" ").

The backslash displays the next character in the format code.

Characters in the format code that have a special meaning can only be displayed as literal characters if they are preceded by a backslash. The backslash itself is not displayed, unless you enter a double backslash (\\) in the format code.

Os caracteres que têm de ser precedidos por uma barra invertida no código do formato para serem mostrados como caracteres literais são os caracteres de formatação da data e hora (a, c, d, h, m, n, p, q, s, t, w, y, /, :), caracteres de formatação numérica (#, 0, %, E, e, vírgula, ponto final) e os caracteres de formatação de cadeias (@, &, <, >, !).


Predefined formats

You can also use the following predefined number formats. Except for "General Number", all of the predefined format codes return the number as a decimal number with two decimal places.

Se utilizar formatos pré-definidos, o nome do formato terá de estar entre aspas.

Code

Description

"<"

Convert expression to lower case

">"

Convert expression to upper case.

"c" or "General Date"

Returns the numeric expression in short date format, optionally with "H:MM:SS AM/PM". If expression is a string, returns the string.

"n"

Returns the minute of the numeric expression, with 1 or 2 digits.

"nn"

Returns the minute of the numeric expression with two digits.

"w"

Returns the week day of the numeric expression. 1 is Sunday and 7 is Saturday.

"General Number"

Returns the numeric expression with 12 digits (0.############).

"Currency"

Returns the numeric expression in the currency of the locale.

"Fixed"

Returns the numeric expression with 2 decimal places (0.00).

"Standard"

Returns the numeric expression with thousands separators and 2 decimals (@0.00).

"Percent"

Returns the numeric expression as percent value (0.00%).

"Scientific"

Returns the numeric expression in scientific notation (#.00E+00);

"Yes/No"

Returns "Yes" if the numeric expression is not equal to zero, "No" otherwise. "Yes" and "No" are localized.

"True/False"

Returns "True" if the numeric expression is not equal to zero, "False" otherwise. "True" and "False" are localized.

"On/Off"

Returns "On" if the numeric expression is not equal to zero, "Off" otherwise. "On" and "Off" are localized.

"Long Date" or "dddddd"

Returns the numeric expression in system long date format, and depends on the locale.

"Medium Date"

Returns the numeric expression in date format DD-MMM-YY, and depends on the locale.

"Short Date" or "ddddd"

Returns the numeric expression in system short date format, and depends on the locale.

"Long Time" or "ttttt"

Returns the numeric expression in system long time format, and depends on the locale("H:MM:SS AM/PM").

"Medium Time"

Returns the numeric expression in system medium time format, and depends on the locale (HH:MM AM/PM)

"Short Time"

Returns the numeric expression in system short time format, and depends on the locale (HH:MM).


You can set the locale used for controlling the formatting numbers, dates and currencies in LibreOffice Basic in - Languages and Locales - General. In Basic format codes, the decimal point (.) is always used as placeholder for the decimal separator defined in your locale and will be replaced by the corresponding character.

O mesmo é aplicável às configurações regionais para data, hora e moeda. O código de formatação do Basic será interpretado e mostrado de acordo com a configuração regional do utilizador.

Exemplo:


    txt = bas.Format(6328.2, '##.##0.00')
    print(txt)
  

GetDefaultContext

Devolve o contexto predefinido da fábrica de serviços do processo, se existir; caso contrário, devolve uma referência nula.

GetDefaultContext é uma alternativa ao método getComponentContext()disponível a partir da variável global XSCRIPTCONTEXT ou do módulo uno.py.

Sintaxe:

svc.GetDefaultContext(): uno

Return type:

É utilizado o contexto de componente predefinido ao instanciar serviços através de XMultiServiceFactory. Consulte o capítulo Professional UNO no Guia do Desenvolvedor em api.libreoffice.org para obter mais informações.

Exemplo:


    ctx = bas.GetDefaultContext()
  

GetGuiType

Devolve um valor numérico que especifica a interface gráfica do utilizador. Esta função é fornecida apenas para garantir a compatibilidade com versões anteriores.

Consulte o método system() do módulo Python platform para identificar o sistema operativo.

Sintaxe:

svc.GetGuiType(): int

Exemplo:


    n = bas.GetGuiType()
  
note

Wiser script instructions are available from Identifying the operating system help page.


tip

• ScriptForge.Platform service provides a collection of properties about the current execution environment and context, that include platform detection.

• Extensive operating system name identification is available from INFO("system") Calc formula.


GetPathSeparator

Devolve o separador de diretórios específico do sistema operativo utilizado para especificar os caminhos dos ficheiros.

Utilize os.pathsep do módulo os do Python para identificar o separador de caminho.

Sintaxe:

svc.GetPathSeparator(): str

Exemplo:


    sep = bas.GetPathSeparator()
  

GetSystemTicks

Devolve o número de ticks do sistema fornecidos pelo sistema operativo. Pode utilizar esta função para otimizar determinados processos. Utilize este método para estimar o tempo em milissegundos:

Sintaxe:

svc.GetSystemTicks(): int

Exemplo:


    ticks_ini = bas.GetSystemTicks()
    time.sleep(1)
    ticks_end = bas.GetSystemTicks()
    bas.MsgBox("{} - {} = {}".format(ticks_end, ticks_ini,ticks_end - ticks_ini))
  

GlobalScope.BasicLibraries

Devolve o objeto UNO que contém todas as bibliotecas e módulos Basic partilhados.

Este método é o equivalente em Python a GlobalScope.BasicLibraries nos scripts Basic.

Sintaxe:

svc.GlobalScope.BasicLibraries(): uno

Return type:

com.sun.star.script.XLibraryContainer

Exemplo:

O exemplo seguinte carrega a biblioteca Gimmicks Basic, caso ainda não tenha sido carregada.


    libs = bas.GlobalScope.BasicLibraries()
    if not libs.isLibraryLoaded("Gimmicks"):
        libs.loadLibrary("Gimmicks")
  

GlobalScope.DialogLibraries

Devolve o objeto UNO que contém todas as bibliotecas de diálogos partilhadas.

Este método é o equivalente em Python a GlobalScope.DialogLibraries nos scripts Basic.

Sintaxe:

svc.GlobalScope.DialogLibraries(): uno

Return type:

com.sun.star.comp.sfx2.DialogLibraryContainer

Exemplo:

O exemplo seguinte mostra uma caixa de mensagem com os nomes de todas as bibliotecas de diálogos disponíveis.


    dlg_libs = bas.GlobalScope.DialogLibraries()
    lib_names = dlg_libs.getElementNames()
    bas.MsgBox("\n".join(lib_names))
  

InputBox

Sintaxe:

svc.InputBox(prompt: str, [title: str], [default: str], [xpostwips: int, ypostwips: int]): str

Parâmetros:

prompt: String expression displayed as the message in the dialog box.

title: String expression displayed in the title bar of the dialog box.

default: String expression displayed in the text box as default if no other input is given.

xpostwips: Integer expression that specifies the horizontal position of the dialog. The position is an absolute coordinate and does not refer to the window of LibreOffice.

ypostwips: Integer expression that specifies the vertical position of the dialog. The position is an absolute coordinate and does not refer to the window of LibreOffice.

If xpostwips and ypostwips are omitted, the dialog is centered on the screen. The position is specified in twips.

Return type:

String

Exemplo:


    txt = s.InputBox('Introduza uma frase:', "Caro utilizador")
    s.MsgBox(txt, s.MB_ICONINFORMATION, "Confirmação da frase")
  
note

Para obter informações mais detalhadas, consulte Entrada/Saída para o ecrã com Python na Wiki.


MsgBox

Exibe uma caixa de diálogo com uma mensagem e devolve um valor opcional.
As constantes MB_xx ajudam a especificar o tipo de caixa de diálogo, o número e o tipo de botões a exibir, bem como o tipo de ícone. Ao somar os seus respetivos valores, formam padrões de bits que definem a aparência da caixa de diálogo MsgBox.

Sintaxe:

bas.MsgBox(prompt: str, [buttons: int], [title: str])[: int]

Parâmetros:

prompt: String expression displayed as a message in the dialog box. Line breaks can be inserted with Chr$(13).

title: String expression displayed in the title bar of the dialog. If omitted, the title bar displays the name of the respective application.

buttons: Any integer expression that specifies the dialog type, as well as the number and type of buttons to display, and the icon type. buttons represents a combination of bit patterns, that is, a combination of elements can be defined by adding their respective values:

Return type:

Um número inteiro opcional, conforme descrito nas propriedades IDxx acima.

Exemplo:


    txt = s.InputBox('Introduza uma frase:', "Caro utilizador")
    s.MsgBox(txt, s.MB_ICONINFORMATION, "Confirmação da frase")
  
note

Para obter informações mais detalhadas, consulte Entrada/Saída para o ecrã com Python na Wiki.


Now

Devolve a data e a hora atuais do sistema como um objeto nativo do Python do tipo datetime.datetime.

Sintaxe:

svc.Now(): datetime

Exemplo:


    bas.MsgBox(bas.Now(), bas.MB_OK, "Now")
  

RGB

Devolve um valor de cor inteiro composto pelos componentes vermelho, verde e azul.

Sintaxe:

svc.RGB(red:int, green: int, blue: int): int

Parâmetros:

red: Any integer expression that represents the red component (0-255) of the composite color.

green: Any integer expression that represents the green component (0-255) of the composite color.

blue: Any integer expression that represents the blue component (0-255) of the composite color.

The resulting Long value is calculated with the following formula:
Result = red×65536 + green×256 + blue.

warning

Under VBA compatibility mode (Option VBASupport 1), the Long value is calculated as
Result = red + green×256 + blue×65536
See RGB Function [VBA]


tip

The color picker dialog helps computing red, green and blue components of a composite color. Changing the color of text and selecting Custom color displays the color picker dialog.


Return type:

Integer

Exemplo:


    YELLOW = bas.RGB(255,255,0)
  

Xray

Inspecionar objetos ou variáveis do Uno.

Sintaxe:

svc.Xray(obj: any)

Parâmetros:

obj: Uma variável ou um objeto UNO.

Exemplo:


    bas.Xray(bas.StarDesktop)
  
warning

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.