Содержимое

# ScriptForge.Basic service

The ScriptForge.Basic service proposes a collection of LibreOffice Basic methods to be executed in a Python context. Basic service methods reproduce the exact syntax and behaviour of Basic builtin functions.

Typical example:

       bas.MsgBox('Display this text in a message box from a Python script')

ScriptForge.Basic service is limited to Python scripts.

## Вызов службы

Before using the Basic service, import the CreateScriptService() method from the scriptforge module:

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

## Свойства

Имя | ReadOnly | Тип | Описание
--- | --- | --- | ---
MB_OK, MB_OKCANCEL, MB_RETRYCANCEL, MB_YESNO, MB_YESNOCANCEL | Да | Integer | Values: 0, 1, 5, 4, 3
MB_ICONEXCLAMATION, MB_ICONINFORMATION, MB_ICONQUESTION, MB_ICONSTOP | Да | Integer | Values: 48, 64, 32, 16
MB_ABORTRETRYIGNORE, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3 | Да | Integer | Values: 2, 128, 256, 512
IDABORT, IDCANCEL, IDIGNORE, IDNO, IDOK, IDRETRY, IDYES | Да | Integer | Values: 3, 2, 5, 7, 1, 4, 6 Constants indicating MsgBox selected button.
StarDesktop | Да | Объект UNO | Returns the StarDesktop object that represents the LibreOffice application.
ThisComponent | Да | Объект UNO | If the current component refers to a LibreOffice document, this method returns the UNO object representing the document. This property returns None when the current component does not correspond to a document.
ThisDatabaseDocument | Да | Объект UNO | If the script is being executed from a Base document or any of its subcomponents this method returns the main component of the Base instance. This property returns None otherwise.

List of Methods in the Basic Service
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

## CDate

Converts a numeric expression or a string to a datetime.datetime Python native object.

This method exposes the Basic builtin function CDate to Python scripts.

### Синтаксис:

svc.CDate(expression: any): obj

### Параметры:

expression: a numeric expression or a string representing a date.

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 LibreOffice - PreferencesTools - Options - 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.

### Пример:

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

## CDateFromUnoDateTime

Converts a UNO date/time representation to a datetime.datetime Python native object.

### Синтаксис:

svc.CDateFromUnoDateTime(unodate: uno): obj

### Параметры:

unodate: A UNO date/time object of one of the following types: com.sun.star.util.DateTime, com.sun.star.util.Date or com.sun.star.util.Time

### Пример:

The following example creates a com.sun.star.util.DateTime object and converts it to a datetime.datetime Python object.

        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

Converts a date representation into a com.sun.star.util.DateTime object.

### Синтаксис:

svc.CDateToUnoDateTime(date: obj): uno

### Параметры:

date: A Python date/time object of one of the following types: datetime.datetime, datetime.date, datetime.time, float (time.time) or time.struct_time.

### Пример:

        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

Returns a system path file name for the given file: URL.

### Синтаксис:

svc.ConvertFromUrl(url: str): str

### Параметры:

url: An absolute file: URL.

### Return value:

A system path file name.

### Пример:

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

## ConvertToUrl

Returns a file: URL for the given system path.

### Синтаксис:

svc.ConvertToUrl(systempath: str): str

### Параметры:

systempath: A system file name as a string.

### Return value:

A file: URL as a string.

### Пример:

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

## CreateUnoService

Instantiates a UNO service with the ProcessServiceManager.

### Синтаксис:

svc.CreateUnoService(servicename: str): uno

### Параметры:

servicename: A fully qualified service name such as com.sun.star.ui.dialogs.FilePicker or com.sun.star.sheet.FunctionAccess.

### Пример:

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

## CreateUnoStruct

Returns an instance of a UNO structure of the specified type.

### Синтаксис:

svc.CreateUnoStruct(unostructure: str): uno

### Параметры:

unostructure: A fully qualified structure name such as com.sun.star.beans.Property or com.sun.star.util.DateTime.

### Пример:

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

## DateAdd

Adds a date or time interval to a given date/time a number of times and returns the resulting date.

### Синтаксис:

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

### Параметры:

interval: A string expression from the following table, specifying the date or time interval.

interval (string value) | Описание
--- | ---
yyyy | Год
q | Квартал
m | Месяц
y | День года
w | День недели
ww | Неделя года
d | День
h | Час
n | Минута
s | Секунда

number: A numerical expression specifying how often the interval value will be added when positive or subtracted when negative.

date: A given datetime.datetime value, the interval value will be added number times to this datetime.datetime value.

### Return value:

A datetime.datetime value.

### Пример:

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

## DateDiff

Returns the number of date or time intervals between two given date/time values.

### Синтаксис:

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

### Параметры:

interval: A string expression specifying the date interval, as detailed in above DateAdd method.

date1, date2: The two datetime.datetime values to be compared.

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

firstdayofweek value | Описание
--- | ---
0 | Используется системное значение по умолчанию
1 | Воскресенье (по умолчанию)
2 | Понедельник
3 | Вторник
4 | Среда
5 | Четверг
6 | Пятница
7 | Суббота

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

firstweekofyear value | Описание
--- | ---
0 | Используется системное значение по умолчанию
1 | Неделя 1 — неделя, которая содержит 1 января (по умолчанию)
2 | Неделя 1 — первая неделя, в которой содержится не менее четырёх дней данного года
3 | Неделя 1 — первая неделя, в которой содержатся только дни нового года

### Return value:

Число.

### Пример:

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

## DatePart

The DatePart function returns a specified part of a date.

### Синтаксис:

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

### Параметры:

interval: A string expression specifying the date interval, as detailed in above DateAdd method.

date: The date/time from which the result is calculated.

firstdayofweek, firstweekofyear: optional parameters that respectively specify the starting day of a week and the starting week of a year, as detailed in above DateDiff method.

### Return value:

The extracted part for the given date/time.

### Пример:

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

## DateValue

Computes a date value from a date string.

### Синтаксис:

svc.DateValue(date: str): datetime

### Параметры:

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

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

### Return value:

The computed date.

### Пример:

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

## Format

Преобразует число в строку и затем форматирует её согласно указанному формату.

### Синтаксис:

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

### Параметры:

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 value:

Text string.

### Коды форматирования

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

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.

.:Десятичный заполнитель определяет количество десятичных разрядов слева и справа от десятичного разделителя.

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.

%: 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.

Если экспонента является отрицательной, знак минус отображается непосредственно перед экспонентой с E-, E+, e-, e+. Если экспонента является положительной, знак плюс отображается только перед экспонентами с Е+ или е+.

The thousands delimiter is displayed if the format code contains the delimiter enclosed by digit placeholders (0 or #).

Использование точки как разделителя групп разрядов или десятичного разделителя определяется параметрами региональных стандартов операционной системы. При вводе числа непосредственно в исходный код Basic всегда используйте в качестве десятичного разделителя точку. Фактически отображаемый в качестве десятичного разделителя символ определяется форматом чисел, заданным в системных параметрах.

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

Чтобы показать другие символы, необходимо предварить их обратной косой чертой (\) или заключить в кавычки (" ").

\ : 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.

Элементы, которые должны предваряться обратной косой чертой в коде формата для того, чтобы они отображались как символы, - это символы для форматирования даты и времени (a, c, d, h, m, n, p, q, s, t, w, y, /, :), символы для числового форматирования (#, 0, %, E, e, запятая, точка) и символы для форматирования строк (@, &, <, >, !).

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.

Если используются предопределённые форматы, их имена должны быть заключены в кавычки.

### Predefined Formats

General Number. Числа отображаются так, как они введены.

Currency. Знак рубля помещается за числом, отрицательные числа заключаются в скобки.

Fixed. По крайней мере один разряд показывается перед десятичным разделителем.

Standard. Числа отображаются с разделителем групп разрядов.

Percent:. Число умножается на 100, и к этому числу добавляется знак процента.

Scientific. Числа отображаются в научном формате (например, 1,00E+03 для числа 1000).

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 LibreOffice - PreferencesTools - Options - 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.

То же самое относится и к параметрам языка для форматов даты, времени и валюты. Код формата Basic будет интерпретироваться и отображаться в соответствии с определённым пользователем языком.

### Пример:

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

## GetDefaultContext

Возвращает контекст по умолчанию для службы процессов (если она существует); в противном случае возвращает нулевую ссылку.

GetDefaultContext is an alternative to the getComponentContext() method available from XSCRIPTCONTEXT global variable or from uno.py module.

### Синтаксис:

svc.GetDefaultContext(): uno

### Return value:

The default component context is used, when instantiating services via XMultiServiceFactory. See the Professional UNO chapter in the Developer's Guide on api.libreoffice.org for more information.

### Пример:

        ctx = bas.GetDefaultContext()

## GetGuiType

Returns a numerical value that specifies the graphical user interface. This function is only provided for backward compatibility with previous versions.

Refer to system() method from platform Python module to identify the operating system.

### Синтаксис:

svc.GetGuiType(): int

### Пример:

        n = bas.GetGuiType()

## GetPathSeparator

Returns the operating system-dependent directory separator used to specify file paths.

Use os.pathsep from os Python module to identify the path separator.

### Синтаксис:

svc.GetPathSeparator(): str

### Пример:

        sep = bas.GetPathSeparator()

## GetSystemTicks

Returns the number of system ticks provided by the operating system. You can use this function to optimize certain processes. Use this method to estimate time in milliseconds:

### Синтаксис:

svc.GetSystemTicks(): int

### Пример:

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

## GlobalScope.BasicLibraries

Returns the UNO object containing all shared Basic libraries and modules.

This method is the Python equivalent to GlobalScope.BasicLibraries in Basic scripts.

### Синтаксис:

svc.GlobalScope.BasicLibraries(): uno

### Return value:

com.sun.star.script.XLibraryContainer

### Пример:

The following example loads the Gimmicks Basic library if it has not been loaded yet.

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

## GlobalScope.DialogLibraries

Returns the UNO object containing all shared dialog libraries.

This method is the Python equivalent to GlobalScope.DialogLibraries in Basic scripts.

### Синтаксис:

svc.GlobalScope.DialogLibraries(): uno

### Return value:

com.sun.star.comp.sfx2.DialogLibraryContainer

### Пример:

The following example shows a message box with the names of all available dialog libraries.

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

## InputBox

### Синтаксис:

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

### Параметры:

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 value:

String

### Пример:

        txt = s.InputBox('Please enter a phrase:', "Dear user")
        s.MsgBox(txt, s.MB_ICONINFORMATION, "Confirmation of phrase")

For in-depth information please refer to Input/Output to Screen with Python on the Wiki.

## MsgBox

Displays a dialog box containing a message and returns an optional value.
MB_xx constants help specify the dialog type, the number and type of buttons to display, plus the icon type. By adding their respective values they form bit patterns, that define the MsgBox dialog appearance.

### Синтаксис:

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

### Параметры:

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 value:

An optional integer as detailed in above IDxx properties.

### Пример:

        txt = s.InputBox('Please enter a phrase:', "Dear user")
        s.MsgBox(txt, s.MB_ICONINFORMATION, "Confirmation of phrase")

For in-depth information please refer to Input/Output to Screen with Python on the Wiki.

## Now

Returns the current system date and time as a datetime.datetime Python native object.

### Синтаксис:

svc.Now(): datetime

### Пример:

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

## RGB

Returns an integer color value consisting of red, green, and blue components.

### Синтаксис:

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

### Параметры:

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.

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

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 value:

Integer

### Пример:

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

## Xray

Inspect Uno objects or variables.

### Синтаксис:

svc.Xray(obj: any)

### Параметры:

obj: A variable or UNO object.

### Пример:

        bas.Xray(bas.StarDesktop)

All ScriptForge Basic routines or identifiers that are prefixed with an underscore character "_" are reserved for internal use. They are not meant be used in Basic macros or Python scripts.

См. также

GlobalScope specifier

Programming with Python Scripts

uno.fileUrlToSystemPath()

uno.systemPathToFileUrl()

Input/Output to Screen with Python on the wiki

XSCRIPTCONTEXT.getComponentContext()

uno.getComponentContext()

platform.system()

os.pathsep()