|
|
|
|
SSL scriptforge.pyi
Sprache: unbekannt
|
|
# -*- coding: utf-8 -*-
# Copyright 2020-2024 Jean-Pierre LEDURE, Rafael LIMA, @AmourSpirit, Alain ROMEDENNE
# =====================================================================================================================
# === The ScriptForge library and its associated libraries are part of the LibreOffice project. ===
# === Full documentation is available on https://help.libreoffice.org/ ===
# =====================================================================================================================
# ScriptForge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# ScriptForge is free software; you can redistribute it and/or modify it under the terms of either (at your option):
# 1) The Mozilla Public License, v. 2.0. If a copy of the MPL was not
# distributed with this file, you can obtain one at http://mozilla.org/MPL/2.0/ .
# 2) The GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. If a copy of the LGPL was not
# distributed with this file, see http://www.gnu.org/licenses/ .
"""
ScriptForge libraries are an extensible and robust collection of macro scripting resources for LibreOffice
to be invoked from user Basic or Python macros. Users familiar with other BASIC macro variants often face hard
times to dig into the extensive LibreOffice Application Programming Interface even for the simplest operations.
By collecting most-demanded document operations in a set of easy to use, easy to read routines, users can now
program document macros with much less hassle and get quicker results.
The use of the ScriptForge interfaces in user scripts hides the complexity of the usual UNO interfaces.
However, it does not replace them. At the opposite their coexistence is ensured.
Indeed, ScriptForge provides a number of shortcuts to key UNO objects.
The scriptforge.py module
- describes the interfaces (classes and attributes) to be used in Python user scripts
to run the services implemented in the standard modules shipped with LibreOffice
- implements a protocol between those interfaces and, when appropriate, the corresponding ScriptForge
Basic libraries implementing the requested services.
The scriptforge.pyi module
- provides the static type checking of all the visible interfaces of the ScriptForge API.
- when the user uses an IDE like PyCharm or VSCode, (s)he might benefit from the typing
hints provided by them thanks to the actual scriptforge.pyi module.
Specific documentation about the use of ScriptForge from Python scripts:
https://help.libreoffice.org/latest/en-US/text/sbasic/shared/03/sf_intro.html?DbPAR=BASIC
"""
# IMPORTS
from __future__ import annotations
import datetime
import time
from typing import Any, Dict, List, Literal, NewType, Optional, overload, Sequence, Tuple, TypeVar, Union
# List the available service types
# SFScriptForge
ARRAY = SFScriptForge.SF_Array
BASIC = SFScriptForge.SF_Basic
DICTIONARY = SFScriptForge.SF_Dictionary
EXCEPTION = SFScriptForge.SF_Exception
FILESYSTEM = SFScriptForge.SF_FileSystem
L10N = SFScriptForge.SF_L10N
PLATFORM = SFScriptForge.SF_Platform
REGION = SFScriptForge.SF_Region
SESSION = SFScriptForge.SF_Session
STRING = SFScriptForge.SF_String
TEXTSTREAM = SFScriptForge.SF_TextStream
TIMER = SFScriptForge.SF_Timer
UI = SFScriptForge.SF_UI
# SFDatabases
DATABASE = SFDatabases.SF_Database
DATASET = SFDatabases.SF_Dataset
DATASHEET = SFDatabases.SF_Datasheet
# SFDialogs
DIALOG = SFDialogs.SF_Dialog
DIALOGCONTROL = SFDialogs.SF_DialogControl
# SFDocuments
DOCUMENT = SFDocuments.SF_Document
BASE = SFDocuments.SF_Base
CALC = SFDocuments.SF_Calc
CALCREFERENCE = SFDocuments.SF_CalcReference
CHART = SFDocuments.SF_Chart
FORM = SFDocuments.SF_Form
FORMCONTROL = SFDocuments.SF_FormControl
FORMDOCUMENT = SFDocuments.SF_FormDocument
WRITER = SFDocuments.SF_Writer
# SFWidgets
MENU = SFWidgets.SF_Menu
CONTEXTMENU = SFWidgets.SF_ContextMenu
POPUPMENU = SFWidgets.SF_PopupMenu
TOOLBAR = SFWidgets.SF_Toolbar
TOOLBARBUTTON = SFWidgets.SF_ToolbarButton
# Aggregate
SERVICE = Union[ARRAY, BASIC, DICTIONARY, EXCEPTION, FILESYSTEM, L10N, PLATFORM, REGION, SESSION, STRING,
TEXTSTREAM, TIMER, UI,
DATABASE, DATASET, DATASHEET,
DIALOG, DIALOGCONTROL,
DOCUMENT, BASE, CALC, CALCREFERENCE, CHART, FORM, FORMCONTROL, FORMDOCUMENT, WRITER,
MENU, CONTEXTMENU, POPUPMENU, TOOLBAR, TOOLBARBUTTON]
# UNO
UNO = TypeVar('UNO', Any, Any)
# Other
FILE = TypeVar('FILE', str, str)
""" File or folder name expressed in accordance with the ``FileSystem.FileNaming`` notation. """
SHEETNAME = TypeVar('SHEETNAME', str, str)
""" A sheet in a Calc document, as a string. It must not contain next characters: "[]*?:\\\/". The apostrophe (')
is forbidden in the first and last positions. The "~" (tilde) character designates the active sheet. """
RANGE = TypeVar('RANGE', str, str)
""" A set of contiguous cells located in a sheet.
The sheet name is optional. If no sheet name is provided, then the active sheet is used.
The use of single quotes to enclose the sheet name is required if the name contains blank spaces " " or periods ".".
Otherwise surrounding single quotes and $ signs are allowed but ignored.
The shortcut "~" (tilde) represents the current selection or the first selected range if multiple ranges are selected.
The shortcut "*" represents all used cells.
Examples
- ``$'SheetX'.D2``, ``$D$2`` - Single cells
- ``$'SheetX'.D2:F6``, ``D2:D10`` - Single ranges with multiple cells
- ``$'SheetX'.*`` - All used cells in the given sheet
- ``$'SheetX'.A:A``, ``3:5`` - All cells in contiguous columns or rows up to the last used cell
- ``myRange`` - A range named "myRange" at spreadsheet level
- ``~.someRange``, ``SheetX.someRange`` - Range names at sheet level
- ``~.~`` or ``~`` - The current selection in the active sheet
"""
SCRIPT_URI = TypeVar('SCRIPT_URI', str, str)
""" String reference to a Basic or Python macro as described in
``https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework#Scripting_Framework_URI_Specification``
"""
SQL_SELECT = TypeVar('SQL_SELECT', str, str)
""" A SQL command containing a SELECT statement, a tablename or a queryname.
In a SELECT statement, table-, query- and field names may be surrounded by square brackets. """
SQL_ACTION = TypeVar('SQL_ACTION', str, str)
""" A SQL command containing an action statement (CREATE TABLE, INSERT, DELETE, ...).
Table- and field names may be surrounded by square brackets. """
SCALAR = Union[int, float, str, datetime.datetime]
VECTOR = Sequence[SCALAR]
MATRIX = Sequence[VECTOR]
# Define the used UNO types
try:
# Next code can succeed only when types-unopy is installed
from com.sun.star.awt import XControl
from com.sun.star.awt import XControlModel
from com.sun.star.awt import XTabControllerModel
from com.sun.star.awt import XWindow
from com.sun.star.awt.tree import XMutableTreeDataModel
from com.sun.star.awt.tree import XMutableTreeNode
from com.sun.star.beans import PropertyValue
from com.sun.star.chart import XDiagram
from com.sun.star.document import XEmbeddedScripts
from com.sun.star.drawing import XShape
from com.sun.star.form import ListSourceType
from com.sun.star.form import XForm
from com.sun.star.frame import XDesktop
from com.sun.star.lang import XComponent
from com.sun.star.script import XLibraryContainer
from com.sun.star.script.provider import XScriptProvider
from com.sun.star.sdb import XOfficeDatabaseDocument
from com.sun.star.sdbc import XConnection as UNOXConnection
from com.sun.star.sdbc import XDatabaseMetaData
from com.sun.star.sheet import XSheetCellCursor
from com.sun.star.sheet import XSpreadsheet
from com.sun.star.table import XCellRange
from com.sun.star.awt import XRectangle
from com.sun.star.table import XTableChart
from com.sun.star.uno import XComponentContext
from com.sun.star.uno import XInterface
from com.sun.star.util import Date as UNODate
from com.sun.star.util import DateTime as UNODateTime
from com.sun.star.util import Time as UNOTime
except ImportError:
# types-unopy is not installed
XControl = NewType('XControl', UNO)
XControlModel = NewType('XControlModel', UNO)
XTabControllerModel = NewType('XTabControllerModel', UNO)
XWindow = NewType('XWindow', UNO)
XMutableTreeDataModel = NewType('XMutableTreeDataModel', UNO)
XMutableTreeNode = NewType('XMutableTreeNode', UNO)
PropertyValue = NewType('PropertyValue', UNO)
XDiagram = NewType('XDiagram', UNO)
XEmbeddedScripts = NewType('XEmbeddedScripts', UNO)
XShape = NewType('XShape', UNO)
ListSourceType = NewType('ListSourceType', UNO)
XForm = NewType('XForm', UNO)
XDesktop = NewType('XDesktop', UNO)
XComponent = NewType('XComponent', UNO)
XLibraryContainer = NewType('XLibraryContainer', UNO)
XScriptProvider = NewType('XScriptProvider', UNO)
XOfficeDatabaseDocument = NewType('XOfficeDatabaseDocument', UNO)
UNOXConnection = NewType('UNOXConnection', UNO)
XDatabaseMetaData = NewType('XDatabaseMetaData', UNO)
XSheetCellCursor = NewType('XSheetCellCursor', UNO)
XSpreadsheet = NewType('XSpreadsheet', UNO)
XCellRange = NewType('XCellRange', UNO)
XRectangle = NewType('XRectangle', UNO)
XTableChart = NewType('XTableChart', UNO)
XComponentContext = NewType('XComponentContext', UNO)
XInterface = NewType('XInterface', UNO)
UNODate = NewType('UNODate', UNO)
UNODateTime = NewType('UNODateTime', UNO)
UNOTime = NewType('UNOTime', UNO)
# Docstring rules to display readable text both in PyCharm and VS Code
# Indentation and punctuation are required like in the example below.
# def ImportFromCSVFile(self, filename: FILE, delimiter: str = ',',
# dateformat: Literal['YYYY-MM-DD', 'DD-MM-YYYY', 'MM-DD-YYYY'] = ...) -> Tuple[str, ...]:
# """
# Import the data contained in a comma-separated values (CSV) file. The comma may be replaced
# by any character.
# Difference with the Basic version: dates are returned in their iso format,
# not as any of the datetime objects.
# Args <<<<< No colon (:)
# ``filename``: The name of the text file containing the data.
# The name must be expressed according to the current FileNaming property of the FileSystem
# service.
# <<<<< When multiple arguments, a linefeed is required here
# ``dateformat``: A special mechanism handles dates when ``dateformat`` is not the empty string.
# The dash (-) may be replaced by a dot (.), a slash (/) or a space. Other date formats
# will be ignored.
# Returns <<<<< No colon (:)
# A ``list`` of ``lists``.
# """
# ...
# #####################################################################################################################
# ScriptForge CLASS ###
# #####################################################################################################################
class ScriptForge(object, metaclass = ...):
"""
The ScriptForge class encapsulates the core of the ScriptForge run-time
- Bridge with the LibreOffice process
- Implementation of the interlanguage protocol with the Basic libraries
- Identification of the available services interfaces
- Dispatching of services
- Coexistence with UNO
The class may be instantiated several times. Only the first instance will be retained ("Singleton").
"""
def __init__(self, hostname: str = ..., port: int = ..., pipe: str = ...):
"""
The ScriptForge class encapsulates the core of the ScriptForge run-time
- Bridge with the LibreOffice process
- Implementation of the interlanguage protocol with the Basic libraries
- Identification of the available services interfaces
- Dispatching of services
- Coexistence with UNO
The class may be instantiated several times. Only the first instance will be retained ("Singleton").
Both arguments are mandatory when Python and LibreOffice run in separate processes.
Otherwise, do not call this routine or leave both arguments out.
To execute at most once by LibreOffice session.
Args
``hostname``: probably 'localhost'
``port``: port number
``pipe``: pipe name
"""
...
# #####################################################################################################################
# SFServices CLASS (ScriptForge services superclass) ###
# #####################################################################################################################
class SFServices(object):
"""
Generic implementation of a parent Service class.
Every service must subclass this class to be recognized as a valid service.
A service instance is created by the ``CreateScriptService`` method.
It can have a mirror in the ``Basic`` world or be totally defined in ``Python``.
"""
def Dispose(self) -> None:
""" Free up the object's resources after usage. """
...
def GetProperty(self, propertyname: str, arg: Any = ...) -> Any:
""" Get the given property from the Basic world """
...
def Properties(self) -> Tuple[str, ...]:
""" Properties list. """
...
# #####################################################################################################################
# SFScriptForge CLASS (alias of ScriptForge Basic library) ###
# #####################################################################################################################
class SFScriptForge:
""" SF_ScriptForge all-purpose services. """
# #########################################################################
# SF_Array CLASS
# #########################################################################
class SF_Array(SFServices, metaclass = ...):
def ImportFromCSVFile(self,
filename: FILE,
delimiter: str = ',',
dateformat: Literal['YYYY-MM-DD', 'DD-MM-YYYY', 'MM-DD-YYYY',
'YYYY/MM/DD', 'DD/MM/YYYY', 'MM/DD/YYYY',
'YYYY.MM.DD', 'DD.MM.YYYY', 'MM.DD.YYYY',
'YYYY MM DD', 'DD MM YYYY', 'MM DD YYYY'] = ...
) -> MATRIX:
"""
Import the data contained in a comma-separated values (CSV) file. The comma may be replaced
by any character.
Difference with the Basic version: dates are returned in their iso format,
not as any of the datetime objects.
Args
``filename``: The name of the text file containing the data.
The name must be expressed according to the current FileNaming property of the FileSystem
service.
``dateformat``: A special mechanism handles dates when ``dateformat`` is not the empty string.
The dash (-) may be replaced by a dot (.), a slash (/) or a space. Other date formats
will be ignored.
Returns
A ``list`` of ``lists``.
"""
...
# #########################################################################
# SF_Basic CLASS
# #########################################################################
class SF_Basic(SFServices, metaclass = ...):
"""
This service proposes a collection of Basic methods to be executed in a Python context
simulating the exact syntax and behavior of the identical Basic builtin method.\n
Typical example:
``basic = CreateScriptService('basic')``
``basic.MsgBox('This has to be displayed in a message box')``
"""
MB_ABORTRETRYIGNORE: Literal[2]
MB_DEFBUTTON1: Literal[128]
MB_DEFBUTTON2: Literal[258]
MB_DEFBUTTON3: Literal[215]
MB_ICONEXCLAMATION: Literal[48]
MB_ICONINFORMATION: Literal[64]
MB_ICONQUESTION: Literal[32]
MB_ICONSTOP: Literal[16]
MB_OK: Literal[0]
MB_OKCANCEL: Literal[1]
MB_RETRYCANCEL: Literal[5]
MB_YESNO: Literal[4]
MB_YESNOCANCEL: Literal[3]
IDABORT: Literal[3]
IDCANCEL: Literal[2]
IDIGNORE: Literal[5]
IDNO: Literal[7]
IDOK: Literal[1]
IDRETRY: Literal[4]
IDYES: Literal[6]
@classmethod
def CDate(cls, datevalue: Union[int, float, str]) -> Optional[datetime.datetime]:
"""
Converts a numeric expression or a string to a ``datetime.datetime`` Python native object.
Args
``datevalue``: A numeric expression or a ``string`` representing a date.
Returns
The equivalent ``datetime.datetime``.
"""
...
@staticmethod
def CDateFromUnoDateTime(unodate: Union[UNODateTime, UNODate, UNOTime]) -> datetime.datetime:
"""
Converts a ``UNO date/time`` representation to a ``datetime.datetime`` Python native object.
Args
``unodate``: A ``UNO date`` object, ``com.sun.star.util.DateTime``, ``.Date`` or ``.Time``.
Returns
The equivalent ``datetime.datetime``.
"""
...
@staticmethod
def CDateToUnoDateTime(date: Union[float, time.struct_time, datetime.datetime, datetime.date, datetime.time]
) -> UNODateTime:
"""
Converts a date representation into the ``com.sun.star.util.DateTime`` date format.
Args
``date``: A ``datetime`` like object.
When ``date`` is a ``float`` it is considered a ``time.time`` value.
Returns
A ``com.sun.star.util.DateTime`` UNO object.
"""
...
@classmethod
def ConvertFromUrl(cls, url: str) -> str:
"""
Convert from url.
Args
``url``: A string representing a file in URL format.
Returns
The same file name in native operating system notation._
"""
...
@classmethod
def ConvertToUrl(cls, systempath: str) -> str:
"""
Convert to url.
Args
``systempath``: A string representing a file in native operating system notation.
Returns
The same file name in URL format.
"""
...
@classmethod
def CreateUnoService(cls, servicename: str) -> UNO:
"""
Instantiates a UNO service
Args
``servicename``: A string representing the service to create.
Returns
A UNO object
"""
...
@classmethod
def CreateUnoStruct(cls, unostructure: str) -> UNO:
"""
Returns an instance of a UNO structure of the specified type.
Args
``unostructure``: A UNO Struct typename such as ``com.sun.star.awt.Size``.
Returns
A UNO Object
"""
...
@classmethod
def DateAdd(cls,
interval: Literal['yyyy', 'q', 'm','y', 'w', 'ww', 'd', 'h', 'n', 's'],
number: int,
date: Union[float, time.struct_time, datetime.datetime, datetime.date, datetime.time]
) -> datetime.datetime:
"""
Adds a date or time interval to a given date/time a number of times and returns the resulting date.
Args
``interval``: A string expression specifying the date or time interval.
``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 ``date`` value.
Returns
A ``datetime.datetime`` value.
"""
...
@classmethod
def DateDiff(cls,
interval: Literal['yyyy', 'q', 'm','y', 'w', 'ww', 'd', 'h', 'n', 's'],
date1: Union[float, time.struct_time, datetime.datetime, datetime.date, datetime.time],
date2: Union[float, time.struct_time, datetime.datetime, datetime.date, datetime.time],
firstdayofweek: Literal[0, 1, 2, 3, 4, 5, 6, 7] = ...,
firstweekofyear: Literal[0, 1, 2, 3] = ...,
) -> int:
"""
Gets the number of date or time intervals between two given date/time values.
Args
``interval``: A string expression specifying the date interval.
``date1``: The first ``datetime.datetime`` values to be compared.
``firstdayofweek``: An optional parameter that specifies the starting day of a week.
``firstweekofyear``: An optional parameter that specifies the starting week of a year.
Returns
A number.
"""
...
@classmethod
def DatePart(cls,
interval: Literal['yyyy', 'q', 'm','y', 'w', 'ww', 'd', 'h', 'n', 's'],
date: Union[float, time.struct_time, datetime.datetime, datetime.date, datetime.time],
firstdayofweek: Literal[0, 1, 2, 3, 4, 5, 6, 7] = ...,
firstweekofyear: Literal[0, 1, 2, 3] = ...,
) -> int:
"""
Gets a specified part of a date.
Args
``interval``: A string expression specifying the date interval.
``date``: The date from which to extract a part.
``firstdayofweek``: the starting day of a week. Defaults to 1.
``firstweekofyear``: the starting week of a year. Defaults to 1.
Returns
The specified part of the date.
"""
...
@classmethod
def DateValue(cls, string: str) -> datetime.datetime:
"""
Computes a date value from a date string.
Args
``string``: A string expression that contains the date that you want to calculate.
The string passed to ``DateValue`` must be expressed in one of the date formats defined
by your locale setting or using the ISO date format "yyyy-mm-dd" (year, month and day
separated by hyphens).
Returns
The converted date.
"""
...
@classmethod
def Format(cls, expression: Union[datetime.datetime, float, int], format: str = ...) -> str:
"""
Converts a number to a string, and then formats it according to the format that you specify.
Args
``expression``: Numeric expression that you want to convert to a formatted string.
``format``: the format to apply. Defaults to "".
Returns
The formatted value.
"""
...
@classmethod
def GetDefaultContext(cls) -> XComponentContext:
"""
Gets the default context of the process service factory, if existent, else returns a None reference.
"""
...
@classmethod
def GetGuiType(cls) -> int:
"""
Gets a numerical value that specifies the graphical user interface.
Returns
The GetGuiType value, 1 for Windows, 4 for UNIX
"""
...
@classmethod
def GetPathSeparator(cls) -> str:
"""
Gets the operating system-dependent directory separator used to specify file paths.
Returns
The os path separator
"""
...
@classmethod
def GetSystemTicks(cls) -> int:
"""
Gets 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:
Returns
The actual number of system ticks.
"""
...
class GlobalScope(metaclass = ...):
"""
Use cases:
- ``GlobalScope.BasicLibraries``
- ``GlobalScope.DialogLibraries``
"""
@classmethod
def BasicLibraries(cls) -> XLibraryContainer:
"""
``GlobalScope.BasicLibraries`` gets the UNO object containing all shared Basic libraries
and modules. This method is the Python equivalent to ``GlobalScope.BasicLibraries``
in Basic scripts.
Returns
A ``XLibraryContainer`` UNO object.
"""
...
@classmethod
def DialogLibraries(cls) -> XLibraryContainer:
"""
``GlobalScope.DialogLibraries`` gets the UNO object containing all shared dialog libraries.
Returns
A ``DialogLibraryContainer`` UNO object.
"""
...
@classmethod
def InputBox(cls,
prompt: str,
title: str = ...,
default: str = ...,
xpostwips: int = ...,
ypostwips: int = ...,
) -> str:
"""
Displays an input box.
Args
``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.
Returns
The input string.
"""
...
@classmethod
def MsgBox(cls, prompt: str, buttons: int = ..., title: str = ...) -> int:
"""
Displays a dialogue 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.
Args
``prompt``: String expression displayed as a message in the dialog box.
``buttons``: 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.
Defaults to 0.
``title``: String expression displayed in the title bar of the dialog. Defaults to "".
Returns
The pressed button.
"""
...
@classmethod
def Now(cls) -> datetime.datetime:
"""
Gets the current system date and time as a ``datetime.datetime`` Python native object.
"""
...
@classmethod
def RGB(cls, red: int, green: int, blue: int) -> int:
"""
Gets an integer color value consisting of red, green, and blue components.
Args
``red``: An integer expression that represents the red component (0-255) of the composite color.
``green``: An integer expression that represents the green component (0-255) of the
composite color.
``blue``: An integer expression that represents the blue component (0-255) of the composite
color.
Returns
An integer color value consisting of red, green, and blue components.
"""
...
@classmethod
def Wait(cls, millisec: Union[int, float]) -> None:
"""
Interrupts the program execution for the amount of time that you specify in milliseconds.
The method is an alternative to ``time.sleep()`` that sometimes freezes the LibreOffice
user interface.
Args
``millisec``: The amount of time (in milliseconds) to wait before the program is continued.
"""
...
@classmethod
def Xray(cls, unoobject: UNO) -> None:
"""
Inspect UNO objects or variables.
Args
``unoobject``: A variable or UNO object.
"""
...
StarDesktop: XDesktop
""" Gets the desktop as a UNO object. """
ThisComponent: Optional[XComponent]
"""
If the current component refers to a LibreOffice document, this method
returns the UNO object representing the document.
When the current component is the Basic IDE, the ThisComponent object returns in Basic the
component owning the currently run user script. This behaviour cannot be reproduced in Python.
Returns
The current component or None when not a document.
"""
ThisDatabaseDocument: Optional[XOfficeDatabaseDocument]
"""
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.
Returns
The current Base (main) component or None when not a Base document or one of its subcomponents.
"""
# #########################################################################
# SF_Dictionary CLASS
# #########################################################################
class SF_Dictionary(SFServices, dict):
"""
The service adds to a Python dict instance the interfaces for conversion to and from
a list of UNO PropertyValues
Usage
``dico = dict(A = 1, B = 2, C = 3)``
``myDict = CreateScriptService('Dictionary', dico) # Initialize myDict with the content of dico``
``myDict['D'] = 4``
``print(myDict) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}``
``propval = myDict.ConvertToPropertyValues()``
or
``dico = dict(A = 1, B = 2, C = 3)``
``myDict = CreateScriptService('Dictionary') # Initialize myDict as an empty dict object``
``myDict.update(dico) # Load the values of dico into myDict``
``myDict['D'] = 4``
``print(myDict) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}``
``propval = myDict.ConvertToPropertyValues()``
"""
def ConvertToPropertyValues(self) -> Tuple[PropertyValue]:
"""
Store the content of the dictionary in an array of PropertyValues.
Each entry in the list is a ``com.sun.star.beans.PropertyValue``.
The key is stored in Name, the value is stored in ``Value``.
If one of the items has a type ``datetime``, it is converted to a ``com.sun.star.util.DateTime``
structure. If one of the items is an empty list, it is converted to ``None``.
Returns
A list of property values. The resulting list is empty when the dictionary is empty.
"""
...
def ImportFromPropertyValues(self, propertyvalues: Sequence[PropertyValue], overwrite: bool = ...) -> bool:
"""
Inserts the contents of an array of ``PropertyValue`` objects into the current dictionary.
``PropertyValue`` Names are used as keys in the dictionary, whereas Values contain
the corresponding values. Date-type values are converted to ``datetime.datetime`` instances.
Args
``propertyvalues``: tuple containing ``com.sun.star.beans.PropertyValue`` objects.
``overwrite``: When True, entries with same name may exist in the dictionary
and their values are overwritten. When ``False`` (default), repeated keys are not overwritten.
Defaults to ``False``.
Returns
True when successful.
"""
...
# #########################################################################
# SF_Exception CLASS
# #########################################################################
class SF_Exception(SFServices, metaclass = ...):
"""
The Exception service is a collection of methods for code debugging.
The ``Exception`` service console stores events, variable values and information about errors.
Use the console when the Python shell is not available, for example in ``Calc`` user defined functions (UDF)
or during events processing.
Use the ``DebugPrint()`` and ``DebugDisplay()`` methods to log any relevant information, events and data
of any type to the console.
Console entries can be dumped to a text file or visualized in a dialogue.
"""
ReportScriptErrors: bool
""" When set to ``False``, an error occur silently. Useful f.i. in Calc user-defined functions.
The set value is preserved until it is explicitly set again. """
ReturnCode: str
""" Returns the code returned by the last call to the ScriptForge API from a user script.
It is the zero-length string if everything ran without error. """
ReturnCodeDescription: str
""" Returns the localized description of the code returned by the last call to the ScriptForge API
from a user script. It is the zero-length string if everything ran without error. """
StopWhenError: bool
""" When set to ``False``, the process continues when ScriptForge detects a user script error.
Default = ``True``. The set value is preserved until it is explicitly set again. """
def Clear(self):
"""
Reset the current error status and return code.
"""
...
def Console(self, modal: bool = ...) -> None:
"""
Displays the console messages in a modal or non-modal dialog. In both modes, all the past messages
issued by a ``DebugPrint()`` method or resulting from an exception are displayed. In non-modal mode,
subsequent entries are added automatically.
If the console is already open, when non-modal, it is brought to the front.
A modal console can only be closed by the user. A non-modal console can either be closed by the user
or upon script termination.
Args
``modal``: determine if the console window is modal (``True``) or non-modal (``False``).
Default value is ``True``.
"""
...
def ConsoleClear(self, keep: int = ...) -> None:
"""
Clears the console keeping an optional number of recent messages. If the console is activated in non-modal mode,
it is refreshed.
Args
``keep``: the number of recent messages to be kept. Default value is 0.
"""
...
def ConsoleToFile(self, filename: FILE) -> bool:
"""
Exports the contents of the console to a text file. If the file already exists and the console
is not empty, it will be overwritten without warning. Returns True if successful.
Args
``filename``: the name of the text file the console should be dumped into.
The name is expressed according to the current ``FileNaming`` property of the ``SF_FileSystem``
service.
Returns
``True`` when successful.
"""
...
def DebugDisplay(self, *args)-> int:
"""
Concatenates all the arguments into a single human-readable string and displays it in a MsgBox
with an Information icon and an OK button. The displayed string is also added to the Console.
Args
``*args``: any number of arguments of any type.
Returns
The result of the execution of the ``MsgBox()`` method.
"""
...
def DebugPrint(self, *args):
"""
Assembles all the given arguments into a single human-readable string and adds it as a new entry
in the console.
Args
``*args``: any number of arguments of any type.
"""
...
@classmethod
def PythonShell(cls, variables: dict = ...,
background: int = ...,
foreground: int = ...
) -> None:
"""
Opens an APSO Python shell as a non-modal window.
The Python script keeps running after the shell is opened.
The output from ``print`` statements inside the script are shown in the shell.
Args
``variables``: a Python dictionary with variable names and values that will be
passed on to the APSO Python shell. By default, all local variables are passed using
Python's builtin ``locals()`` function.
``background``: the background color of the window as an integer value. Usually given
as a hexadecimal value, like 0xFFFFFF, or as the output of the ``basic.RGB()`` method.
``foreground``: the foreground color of the window as an integer value.
Note
Typical use
``exc.PythonShell({**globals(), **locals()}, background = 0x0, foreground = 0xFFFFFF)``
"""
...
# #########################################################################
# SF_FileSystem CLASS
# #########################################################################
class SF_FileSystem(SFServices, metaclass = ...):
"""
The "FileSystem" service includes common file and folder handling routines.
"""
FileNaming: str
"""
Sets or returns the current files and folders notation, either ``'ANY', 'URL'`` or ``'SYS'``:
``ANY``: (default) the methods of the ``FileSystem`` service accept both URL and current operating
system's notation for input arguments but always return URL strings.
``URL``: the methods of the ``FileSystem`` service expect URL notation for input arguments and
return URL strings.
``SYS``: the methods of the ``FileSystem`` service expect current operating system's notation
for both input arguments and return strings.
Once set, the ``FileNaming`` property remains unchanged either until the end of the ``LibreOffice``
session or until it is set again.
"""
ConfigFolder: FILE
""" Returns the configuration folder of ``LibreOffice``. """
ExtensionsFolder: FILE
""" Returns the folder where extensions are installed. """
HomeFolder: FILE
""" Returns the user home folder. """
InstallFolder: FILE
""" Returns the installation folder of ``LibreOffice``. """
TemplatesFolder: FILE
""" Returns the folder containing the system templates files. """
TemporaryFolder: FILE
""" Returns the temporary files folder defined in the ``LibreOffice`` path settings. """
UserTemplatesFolder: FILE
""" Returns the folder containing the user-defined template files. """
ForReading: Literal[1]
ForWriting: Literal[2]
ForAppending: Literal[8]
def BuildPath(self, foldername: FILE, name: str) -> str:
"""
Joins a folder path and the name of a file and returns the full file name with a
valid path separator. The path separator is added only if necessary.
Args
``foldername``: the path with which name will be combined.
The specified path does not need to be an existing folder.
``name``: the name of the file to be appended to foldername. This parameter uses
the notation of the current operating system.
Returns
The path concatenated with the file name after insertion of a path separator, if necessary.
"""
...
def CompareFiles(self, filename1: FILE, filename2: FILE, comparecontents: bool = ...) -> bool:
"""
Compare 2 files and return ``True`` if they seem identical.
Depending on the value of the ``comparecontents`` argument,
the comparison between both files can be either based only on
file attributes (such as the last modified date), or based on the file contents.
Args
``filename1``: the 1st file to compare.
``filename2``: the 2nd file to compare.
``comparecontents``: when ``True``, the contents of the files are compared.
Defaults to ``False``.
Returns
``True`` when the files seem identical
"""
...
def CopyFile(self, source: FILE, destination: FILE, overwrite: bool = ...) -> bool:
"""
Copies one or more files from one location to another.
Args
``source``: ``FileName`` or ``NamePattern`` which can include wildcard characters,
for one or more files to be copied.
``destination``: ``FileName`` where the single ``source`` file is to be copied
or ``FolderName`` where the multiple files from ``source`` are to be copied.
``overwrite``: if ``True`` (default), files may be overwritten.
``CopyFile`` will fail if Destination has the read-only attribute set,
regardless of the value of Overwrite.
Returns
``True`` if at least one file has been copied. ``False`` if an error occurred.
An error also occurs if a source using wildcard characters doesn't match any files.
The method stops on the first error it encounters.
No attempt is made to roll back or undo any changes made before an error occurs.
Notes
- If ``destination`` does not exist, it is created.
- Wildcard characters are not allowed in ``destination``.
"""
...
def CopyFolder(self, source: FILE, destination: FILE, overwrite: bool = ...) -> bool:
"""
Copies one or more folders from one location to another.
Args
``source``: ``FolderName`` or ``NamePattern`` which can include wildcard characters,
for one or more folders to be copied.
``destination``: ``FolderName`` where the single ``source`` folder is to be copied
or ``FolderName`` where the multiple folders from ``source`` are to be copied.
If ``FolderName`` does not exist, it is created.
``overwrite``: if ``True`` (default), folders and their content may be overwritten.
Defaults to ``True``. ``CopyFile`` will fail if ``destination`` has the read-only
attribute set, regardless of the value of ``overwrite``.
Returns
``True`` if at least one folder has been copied. ``False`` if an error occurred.
An error also occurs if a ``source`` using wildcard characters doesn't match any folders.
The method stops on the first error it encounters.
No attempt is made to roll back or undo any changes made before an error occurs.
Notes
- If ``destination`` does not exist, it is created.
- Wildcard characters are not allowed in ``destination``.
"""
...
def CreateFolder(self, foldername: FILE) -> bool:
"""
Creates the specified ``foldername``.
If the specified folder has a parent folder that does not exist, it is created.
Args
foldername: a string representing the folder to create. It must not exist.
Returns
``True`` if ``foldername`` is a valid folder name, does not exist and creation was successful.
``False`` otherwise, including when ``foldername`` is a file.
"""
...
def CreateTextFile(
self, filename: FILE, overwrite: bool = ..., encoding: str = ...
) -> TEXTSTREAM:
"""
Creates a specified file and returns a ``TextStream`` service instance that can be used
to write to the file.
The method returns ``None`` if an error occurred.
Args
``filename``: the name of the file to be created.
``overwrite``: determines if ``filename`` can be overwritten (default = ``True``).
``encoding``: the character set to be used. The default encoding is "UTF-8".
"""
...
def DeleteFile(self, filename: FILE) -> bool:
"""
Deletes one or more files.
The files to be deleted must not be readonly.
Args
``filename``: ``FileName`` or ``NamePattern`` which can include wildcard characters,
for one or more files to be deleted.
Returns
``True`` if at least one file has been deleted. ``False`` if an error occurred.
An error also occurs if ``fileName`` using wildcard characters doesn't match any files.
The method stops on the first error it encounters.
No attempt is made to roll back or undo any changes made before an error occurs.
"""
...
def DeleteFolder(self, foldername: FILE) -> bool:
"""
Deletes one or more folders.
The folders to be deleted must not be readonly.
Args
``foldername``: ``FolderName`` or ``NamePattern`` which can include wildcard characters,
for one or more Folders to be deleted.
Returns
``True`` if at least one folder has been deleted. ``False`` if an error occurred.
An error will also occur if the ``foldername`` parameter uses wildcard characters and
does not match any folders.
The method stops immediately after it encounters an error.
The method does not roll back nor does it undo changes made before the error occurred.
"""
...
def ExtensionFolder(self, extension: str) -> str:
"""
Returns a string containing the folder where the specified extension package is installed.
Args
``extension``: a string value with the ID of the extension.
If the extension is not installed, an exception is raised.
"""
...
def FileExists(self, filename: FILE) -> bool:
"""
Return ``True`` if the given file exists.
Args
``filename``: a string representing the file to be tested.
Returns
``True`` if ``filename`` is a valid File name and it exists.
``False`` otherwise, including when ``filename`` is a folder.
"""
...
def Files(self, foldername: FILE, filter: str = ..., includesubfolders: bool = ...) -> Tuple[str, ...]:
"""
Gets a tuple of the ``FileNames`` stored in the given folder.
If the argument ``foldername`` specifies a folder that does not exist, an exception is raised.
The resulting tuple may be filtered with wildcards.
Args
``foldername``: the folder to explore.
``filter``: contains wildcards ("?" and "*") to limit the list to the relevant files
(default = "").
``includesubfolders``: set this argument to ``True`` to include the contents of
subfolders (Default = ``False``).
Returns
A tuple of strings, each entry is the ``FileName`` of an existing file.
"""
...
def FolderExists(self, foldername: FILE) -> bool:
"""
Returns ``True`` if the given folder name exists.
Args
``foldername``: a string representing a folder.
Returns
``True`` if ``folderName`` is a valid folder name and it exists.
``False`` otherwise, including when ``foldername`` is a file.
"""
...
def GetBaseName(self, filename: FILE) -> str:
"""
Returns the ``BaseName`` (equal to the last component) of a file or folder name, without its extension.
The method does not check for the existence of the specified file or folder.
Args
``filename``: path and file name
Returns
The ``BaseName`` of the given file name. It may be the empty string.
"""
...
def GetExtension(self, filename: FILE) -> str:
"""
Returns the extension part of a ``File-`` or ``FolderName``, without the dot (.).
The method does not check for the existence of the specified file or folder.
Args
``filename``: path and file name
Returns
The extension without a leading dot. May be empty.
"""
...
def GetFileLen(self, filename: FILE) -> int:
"""
Returns the length of a file in bytes.
Args
``filename``: a string representing an existing file.
Returns
File size if ``filename`` exists.
"""
...
def GetFileModified(self, filename: FILE) -> datetime.datetime:
"""
Returns the last modified date for the given file.
Args
``filename``: a string representing an existing file.
Returns
The modification date and time.
"""
...
def GetName(self, filename: FILE) -> str:
"""
Returns the last component of a ``File-`` or ``FolderName``.
The method does not check for the existence of the specified file or folder.
Args
``filename``: path and file name
Returns
The last component of the full file name in native operating system format.
"""
...
def GetParentFolderName(self, filename: FILE) -> FILE:
"""
Returns a string containing the name of the parent folder of the last component in a specified
``File-`` or ``FolderName``.
The method does not check for the existence of the specified file or folder.
Args
``filename``: path and file name.
Returns
A folder name including its final path separator.
"""
...
def GetTempName(self, extension: str = ...) -> FILE:
"""
Returns a randomly generated temporary file name that is useful for performing
operations that require a temporary file : the method does not create any file.
Args
``extension``: the extension of the temporary file name (Default = "").
Returns
A ``FileName`` as a string.
By default, the returned file name does not have an extension (suffix).
Use the extension parameter to specify the extension of the file name to be generated.
The folder part of the returned string is the system's temporary folder.
"""
...
def HashFile(self,
filename: FILE,
algorithm: Literal['MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512'],
) -> str:
"""
Gets a hexadecimal string representing a checksum of the given file.
Args
``filename``: a string representing a file.
``algorithm``: the hashing algorithm to use.
Returns
The requested checksum as a string. Hexadecimal digits are lower-cased.
A zero-length string when an error occurred.
Note
The supported hashing algorithms are:
- MD5
- SHA1
- SHA224
- SHA256
- SHA384
- SHA512
"""
...
def MoveFile(self, source: FILE, destination: FILE) -> bool:
"""
Moves one or more files from one location to another.
Returns ``True`` if at least one file has been moved or ``False`` if an error occurred.
An error will also occur if the source parameter uses wildcard characters and does not match any files.
The method stops immediately after it encounters an error. The method does not
roll back nor does it undo changes made before the error occurred.
Args
``source``: ``FileName`` or ``NamePattern`` which can include wildcard characters,
for one or more files to be moved.
``destination``: if ``source`` is an existing file name then ``destination`` indicates
the new path and file name of the moved file. If the move operation involves multiple files,
then ``destination`` must be a folder name. If it does not exist, it is created.
If ``source`` and ``destination`` have the same parent folder, the method will rename
the ``source``.
Wildcard characters are not allowed in ``destination``.
Returns
``True`` if at least one file has been moved. ``False`` if an error occurred.
"""
...
def MoveFolder(self, source: FILE, destination: FILE) -> bool:
"""
Moves one or more folders from one location to another.
Returns ``True`` if at least one folder has been moved or ``False`` if an error occurred.
An error will also occur if the source parameter uses wildcard characters and does
not match any folders.
The method stops immediately after it encounters an error. The method does not roll
back nor does it undo changes made before the error occurred.
Args
``source``: ``FolderName`` or ``NamePattern`` which can include wildcard characters,
for one or more folders to be moved.
``destination``: if the move operation involves a single folder, then ``destination``
is the name and path of the moved folder. It must not exist.
If multiple folders are being moved, then ``destination`` designates where the folders
in ``source`` will be moved into. If ``destination`` does not exist, it is created.
Wildcard characters are not allowed in ``destination``.
Returns
``True`` if at least one folder has been moved. ``False`` if an error occurred.
"""
...
def Normalize(self, filename: FILE) -> FILE:
"""
Returns a string containing the normalized path name by collapsing redundant separators and up-level
references. For instance, the path names ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` are all
normalized to ``A/B``.
On Windows, forward slashes ``/`` are converted to backward slashes \\\.
Args
``filename``: a string representing a valid path name.
The file or directory represented by this argument may not exist.
Returns
The normalized file name.
"""
...
def OpenTextFile(self,
filename: FILE,
iomode: Literal[1, 2, 8] = ...,
create: bool = ...,
encoding: str = ...,
) -> TEXTSTREAM:
"""
Opens a specified file and returns a ``TextStream`` object that can be used to read from,
write to, or append to the file.
Args
``filename``: identifies the file to open.
``iomode``: indicates input/output mode. It can be one of three constants:
``filesystem.ForReading`` (default), ``filesystem.ForWriting``, or ``filesystem.ForAppending``.
``create``: boolean value that indicates whether a new file can be created if the specified
filename doesn't exist. The value is ``True`` if a new file and its parent folders
may be created. ``False`` if they aren't created. Defaults to ``False``.
``encoding``: the character set that should be used. Defaults to "UTF-8".
Returns
A ``TEXTSTREAM`` instance representing the opened file or ``None`` if an error occurred.
The method does not check if the file is really a text file. It doesn't check either
if the given encoding is implemented in LibreOffice nor if it is the right one.
"""
...
def PickFile(self,
defaultfile: FILE = ...,
mode: Literal['OPEN', 'SAVE'] = ...,
filter: str = ...,
) -> FILE:
"""
Opens a dialog box to open or save a file.
If the ``SAVE`` mode is set and the picked file exists, a warning message will be displayed.
Args
``defaultfile``: this argument is a string composed of a folder and file name.
The folder part indicates the folder that will be shown when the dialog opens
(default = the last selected folder). The file part designates the default file to open or save.
``mode``: a string value that can be either "OPEN" (for input files) or
"SAVE" (for output files). The default value is "OPEN".
``filter``: the extension of the files displayed when the dialog is opened
(default = no filter).
Returns
The selected FileName in ``filesystem.FileNaming`` format or "" if the dialog was cancelled.
"""
...
def PickFolder(self, defaultfolder: FILE = ..., title: str = ...) -> FILE:
"""
Display a dialog box to select a folder.
Args
``defaultfolder``: the folder from which to start. Default = the last selected folder.
``title``: an optional text to display in the dialog header.
Returns
The selected folder in ``filesystem.FileNaming`` notation.
A zero-length string if the dialog was cancelled.
"""
...
def SubFolders(self,
--> --------------------
--> maximum size reached
--> --------------------
[ 0.35Quellennavigators
Projekt
]
|
2026-03-28
|
|
|
|
|