# 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 twin scriptforge.pyi module.
Usage:
When Python and LibreOffice run in the same process (usual case): from scriptforge import CreateScriptService
When Python and LibreOffice are started in separate processes,
LibreOffice being started from console ... (example for Linux with port = 2024)
./soffice --accept='socket,host=localhost,port=2024;urp;'
then use next statements: from scriptforge import CreateScriptService, ScriptForge
ScriptForge(hostname = 'localhost', port = 2024)
When the user uses an IDE like PyCharm or VSCode, (s)he might benefit from the typing
hints provided by them thanks to the twin scriptforge.pyi module.
# ##################################################################################################################### # ScriptForge CLASS ### # #####################################################################################################################
class ScriptForge(object, metaclass = _Singleton): """
The ScriptForge class encapsulates the core of the ScriptForge run-time
- Bridge with the LibreOffice process
- Implementation of the inter-language 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").
All its properties and methods are for INTERNAL / DEBUGGING use only. """
componentcontext = None# com.sun.star.uno.XComponentContext
scriptprovider = None# com.sun.star.script.provider.XScriptProvider
SCRIPTFORGEINITDONE = False# When True, an instance of the class exists
servicesdispatcher = None# com.sun.star.script.provider.XScript to 'basicdispatcher' constant
serviceslist = {} # Dictionary of all available services
# ######################################################################### # Class constants # #########################################################################
library = 'ScriptForge'
Version = '25.8'# Version number of the LibreOffice release containing the actual file # # Basic dispatcher for Python scripts (@scope#library.module.function)
basicdispatcher = '@application#ScriptForge.SF_PythonHelper._PythonDispatcher' # Python helper functions module
pythonhelpermodule = 'ScriptForgeHelper.py'# Preset in production mode, # might be changed (by devs only) in test mode # # VarType() constants
V_EMPTY, V_NULL, V_INTEGER, V_LONG, V_SINGLE, V_DOUBLE = 0, 1, 2, 3, 4, 5
V_CURRENCY, V_DATE, V_STRING, V_OBJECT, V_BOOLEAN = 6, 7, 8, 9, 11
V_VARIANT, V_ARRAY, V_ERROR, V_UNO = 12, 8192, -1, 16 # Types of objects returned from Basic
objMODULE, objCLASS, objDICT, objUNO = 1, 2, 3, 4 # Special argument symbols
cstSymEmpty, cstSymNull, cstSymMissing = '+++EMPTY+++', '+++NULL+++', '+++MISSING+++' # Predefined references for services implemented as standard Basic modules
servicesmodules = dict([('ScriptForge.Array', 0),
('ScriptForge.Exception', 1),
('ScriptForge.FileSystem', 2),
('ScriptForge.Platform', 3),
('ScriptForge.Region', 4),
('ScriptForge.Services', 5),
('ScriptForge.Session', 6),
('ScriptForge.String', 7),
('ScriptForge.UI', 8)])
def __init__(self, hostname = '', port = 0, pipe = ''): """
Because singleton, constructor is executed only once while Python active
Both arguments are mandatory when Python and LibreOffice run in separate processes
Otherwise both arguments must be left out.
:param hostname: probably 'localhost'
:param port: port number
:param pipe: pipe name """
ScriptForge.hostname = hostname
ScriptForge.port = port
ScriptForge.pipe = pipe # Determine main pyuno entry points
ScriptForge.componentcontext = self.ConnectToLOProcess(hostname, port, pipe) # com.sun.star.uno.XComponentContext
ScriptForge.remoteprocess = (port > 0 and len(hostname) > 0) or len(pipe) > 0
ScriptForge.scriptprovider = self.ScriptProvider(ScriptForge.componentcontext) # ...script.provider.XScriptProvider # # Establish a list of the available services as a dictionary (servicename, serviceclass)
ScriptForge.serviceslist = dict((cls.servicename, cls) for cls in SFServices.__subclasses__())
ScriptForge.servicesdispatcher = None # # All properties and methods of the ScriptForge API are ProperCased # Compute their synonyms as lowercased and camelCased names
ScriptForge.SetAttributeSynonyms() #
ScriptForge.SCRIPTFORGEINITDONE = True
@classmethod def ConnectToLOProcess(cls, hostname = '', port = 0, pipe = ''): """
Called by the ScriptForge class constructor to establish the connection with
the requested LibreOffice instance
The default arguments are for the usual interactive mode
:param hostname: probably 'localhost'or''
:param port: port number or 0
:param pipe: pipe name or''
:return: the derived component context """ if (len(hostname) > 0 and port > 0 and len(pipe) == 0) \ or (len(hostname) == 0 and port == 0 and len(pipe) > 0): # Explicit connection via socket or pipe
ctx = uno.getComponentContext() # com.sun.star.uno.XComponentContext
resolver = ctx.ServiceManager.createInstanceWithContext( 'com.sun.star.bridge.UnoUrlResolver', ctx) # com.sun.star.comp.bridge.UnoUrlResolver try: if len(pipe) == 0:
conn = 'socket,host=%s,port=%d' % (hostname, port) else:
conn = 'pipe,name=%s' % pipe
url = 'uno:%s;urp;StarOffice.ComponentContext' % conn
ctx = resolver.resolve(url) except Exception: # thrown when LibreOffice specified instance isn't started raise SystemExit( "Connection to LibreOffice failed (%s)" % conn) return ctx elif len(hostname) == 0 and port == 0 and len(pipe) == 0: # Usual interactive mode return uno.getComponentContext() else: raise SystemExit('The creation of the ScriptForge() instance got invalid arguments: '
+ "(host = '" + hostname + "', port = " + str(port) + ", pipe = '" + pipe + "')")
@classmethod def InvokeSimpleScript(cls, script, *args): """
Low-level script execution via the script provider protocol:
Create a UNO object corresponding with the given Python or Basic script
The execution is done with the invoke() method applied on the created object
Implicit scope: Either "application" a shared library (BASIC) "share" a module within LibreOffice Macros (PYTHON)
:param script: Either
[@][scope#][library.]module.method - Must not be a class module or method
[@] means that the targeted method accepts ParamArray arguments (Basic only)
[scope#][directory/]module.py$method - Must be a method defined at module level
:return: the value returned by the invoked script without interpretation
An error is raised when the script isnot found. """
def ParseScript(_script): # Check ParamArray, scope, script to run, arguments
_paramarray = False if _script[0] == '@':
_script = _script[1:]
_paramarray = True
scope = '' if'#' in _script:
scope, _script = _script.split('#') if'.py$'in _script.lower(): # Python if len(scope) == 0:
scope = 'share'# Default for Python # Provide an alternate helper script depending on test context if _script.startswith(cls.pythonhelpermodule) and hasattr(cls, 'pythonhelpermodule2'):
_script = cls.pythonhelpermodule2 + _script[len(cls.pythonhelpermodule):] if'#' in _script:
scope, _script = _script.split('#')
uri = 'vnd.sun.star.script:{0}?language=Python&location={1}'.format(_script, scope) else: # Basic if len(scope) == 0:
scope = 'application'# Default for Basic
lib = '' if len(_script.split('.')) < 3:
lib = cls.library + '.'# Default library = ScriptForge
uri = 'vnd.sun.star.script:{0}{1}?language=Basic&location={2}'.format(lib, _script, scope) # Get the script object
_fullscript = ('@'if _paramarray else'') + scope + '#' + _script try:
_xscript = cls.scriptprovider.getScript(uri) # com.sun.star.script.provider.XScript except Exception: raise RuntimeError( 'The script \'{0}\' could not be located in your LibreOffice installation'.format(_script)) return _paramarray, _fullscript, _xscript
# The frequently called PythonDispatcher in the ScriptForge Basic library is cached to privilege performance if cls.servicesdispatcher isnotNoneand script == cls.basicdispatcher:
xscript = cls.servicesdispatcher
fullscript = script
paramarray = True # Parse the 'script' argument and build the URI specification described in # https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework#Scripting_Framework_URI_Specification elif len(script) > 0:
paramarray, fullscript, xscript = ParseScript(script) else: # Should not happen returnNone
# At 1st execution of the common Basic dispatcher, buffer xscript if fullscript == cls.basicdispatcher and cls.servicesdispatcher isNone:
cls.servicesdispatcher = xscript
# Execute the script with the given arguments # Packaging for script provider depends on presence of ParamArray arguments in the called Basic script if paramarray:
scriptreturn = xscript.invoke(args[0], (), ()) else:
scriptreturn = xscript.invoke(args, (), ())
# return scriptreturn[0] # Updatable arguments passed by reference are ignored
@classmethod def InvokeBasicService(cls, basicobject, flags, method, *args): """
High-level script execution via the ScriptForge inter-language protocol:
To be used for all service methods having their implementation in the Basic world
Substitute dictionary arguments by sets of UNO property values
Execute the given Basic method on a class instance
Interpret its result
This method has as counterpart the ScriptForge.SF_PythonHelper._PythonDispatcher() Basic method
:param basicobject: a SFServices subclass instance
The real object is cached in a Basic Global variable and identified by its reference
:param flags: see the vb* and flg* constants in the SFServices class
:param method: the name of the method or property to invoke, as a string
:param args: the arguments of the method. Symbolic cst* constants may be necessary
:return: The invoked Basic counterpart script (with InvokeSimpleScript()) will return a tuple
[0/Value] The returned value - scalar, object reference, UNO object or a tuple
[1/VarType] The Basic VarType() of the returned value
Null, Empty and Nothing have own vartypes but return all None to Python
Additionally, when [0] is a tuple:
[2/Dims] Number of dimensions of the original Basic array
Additionally, when [0] is a UNO or Basic object:
[2/Class] Basic module (1), Basic class instance (2), Dictionary (3), UNO object (4)
Additionally, when [0] is a Basic object:
[3/Type] The object's ObjectType
[4/Service] The object's ServiceName
[5/Name] The object's name
When an error occurs Python receives Noneas a scalar. This determines the occurrence of a failure
The method returns either
- the 0th element of the tuple when scalar, tuple or UNO object
- a new SFServices() object or one of its subclasses otherwise """ # Constants
script = cls.basicdispatcher
cstNoArgs = '+++NOARGS+++'
cstValue, cstVarType, cstDims, cstClass, cstType, cstService, cstName = 0, 1, 2, 2, 3, 4, 5
def ConvertDictArgs(): """
Convert dictionaries in arguments to sets of property values """
argslist = list(args) for i in range(len(args)):
arg = argslist[i] if isinstance(arg, dict):
argdict = arg ifnot isinstance(argdict, SFScriptForge.SF_Dictionary):
argdict = CreateScriptService('ScriptForge.Dictionary', arg)
argslist[i] = argdict.ConvertToPropertyValues() return tuple(argslist)
# # Intercept dictionary arguments if flags & SFServices.flgDictArg == SFServices.flgDictArg: # Bits comparison
args = ConvertDictArgs() # # Run the basic script # The targeted script has a ParamArray argument. Do not change next 4 lines except if you know what you do ! if len(args) == 0:
args = (basicobject,) + (flags,) + (method,) + (cstNoArgs,) else:
args = (basicobject,) + (flags,) + (method,) + args
returntuple = cls.InvokeSimpleScript(script, args) # # Interpret the result # Did an error occur in the Basic world ? ifnot isinstance(returntuple, (tuple, list)): raise RuntimeError("The execution of the method '" + method + "' failed. Execution stops.") # # Analyze the returned tuple # Distinguish: # A Basic object to be mapped onto a new Python class instance # A UNO object # A set of property values to be returned as a dict() # An array, tuple or tuple of tuples - manage dates inside # A scalar, Nothing, a date
returnvalue = returntuple[cstValue] if returntuple[cstVarType] == cls.V_OBJECT and len(returntuple) > cstClass: # Skip Nothing if returntuple[cstClass] == cls.objUNO: pass elif returntuple[cstClass] == cls.objDICT:
dico = CreateScriptService('ScriptForge.Dictionary') ifnot isinstance(returnvalue, uno.ByteSequence): # if array not empty
dico.ImportFromPropertyValues(returnvalue, overwrite = True) return dico else: # Create the new class instance of the right subclass of SFServices()
servname = returntuple[cstService] if servname notin cls.serviceslist: # When service not found raise RuntimeError("The service '" + servname + "' is not available in Python. Execution stops.")
subcls = cls.serviceslist[servname] if subcls isnotNone: return subcls(returnvalue, returntuple[cstType], returntuple[cstClass], returntuple[cstName]) elif returntuple[cstVarType] >= cls.V_ARRAY: # Intercept empty array if isinstance(returnvalue, uno.ByteSequence): return () if flags & SFServices.flgDateRet == SFServices.flgDateRet: # Bits comparison # Intercept all UNO dates in the 1D or 2D array if isinstance(returnvalue[0], tuple): # tuple of tuples
arr = [] for i in range(len(returnvalue)):
row = tuple(map(SFScriptForge.SF_Basic.CDateFromUnoDateTime, returnvalue[i]))
arr.append(row)
returnvalue = tuple(arr) else: # 1D tuple
returnvalue = tuple(map(SFScriptForge.SF_Basic.CDateFromUnoDateTime, returnvalue)) elif returntuple[cstVarType] == cls.V_DATE:
dat = SFScriptForge.SF_Basic.CDateFromUnoDateTime(returnvalue) return dat else: # All other scalar values pass return returnvalue
@classmethod def initializeRoot(cls, force = False): """
Initialize the global scriptforge data structure.
When force = False, only when not yet done.
When force = True, reinitialize it whatever its status. """
script = 'application#ScriptForge.SF_Utils._InitializeRoot' return cls.InvokeSimpleScript(script, force)
@classmethod def errorHandling(cls, standard = True): """
Determine how errors in the ScriptForge Basic code are handled. Either
- the standard mode, i.e. display a "crash" message to the user
- the debugging mode, i.e. the execution stops on the line causing the error """
script = 'application#ScriptForge.SF_Utils._ErrorHandling' return cls.InvokeSimpleScript(script, standard)
@classmethod def SetAttributeSynonyms(cls): """
A synonym of an attribute is either the lowercase or the camelCase form of its original ProperCase name. In every subclass of SFServices:
1) Fill the propertysynonyms dictionary with the synonyms of the properties listed in serviceproperties
Example:
serviceproperties = dict(ConfigFolder = False, InstallFolder = False)
propertysynonyms = dict(configfolder = 'ConfigFolder', installfolder = 'InstallFolder',
configFolder = 'ConfigFolder', installFolder = 'InstallFolder')
2) Define new method attributes synonyms of the original methods
Example: def CopyFile(...): # etc ...
copyFile, copyfile = CopyFile, CopyFile """
for cls in SFServices.__subclasses__(): # Synonyms of properties if hasattr(cls, 'serviceproperties'):
dico = cls.serviceproperties
dicosyn = dict(zip(map(str.lower, dico.keys()), dico.keys())) # lower case
cc = dict(zip(map(camelCase, dico.keys()), dico.keys())) # camel Case
dicosyn.update(cc)
setattr(cls, 'propertysynonyms', dicosyn) # Synonyms of methods. A method is a public callable attribute
methods = [method for method in dir(cls) ifnot method.startswith('_')] for method in methods:
func = getattr(cls, method) if callable(func): # Assign to each synonym a reference to the original method
lc = method.lower()
setattr(cls, lc, func)
cc = camelCase(method) if cc != lc:
setattr(cls, cc, func) return
@staticmethod def unpack_args(kwargs): """
Convert a dictionary passed as argument to a list alternating keys and values
Example:
dict(A = 'a', B = 2) => 'A', 'a', 'B', 2 """ return [v for p in zip(list(kwargs.keys()), list(kwargs.values())) for v in p]
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.
Every subclass must initialize 3 class properties:
servicename (e.g. 'ScriptForge.FileSystem', 'ScriptForge.Basic')
servicesynonyms (e.g. 'FileSystem', 'Basic')
serviceimplementation: either 'python'or'basic'
This is sufficient to register the service in the Python world
The communication with Basic is managed by 2 ScriptForge() methods:
InvokeSimpleScript(): low level invocation of a Basic script. This script must be located in a usual Basic module. The result is passed as-is
InvokeBasicService(): the result comes back encapsulated with additional info
The result is interpreted in the method
The invoked script can be a property or a method of a Basic classor usual module
It is up to every service method to determine which method to use
For Basic services only:
Each instance is identified by its
- object reference: the real Basic object embedded as a UNO wrapper object
- object type ('SF_String', 'DICTIONARY', ...)
- class module: 1 for usual modules, 2 forclass modules
- name (form, control, ... name) - may be blank
The role of the SFServices() superclass is mainly to propose a generic properties management
Properties are got and set following next strategy:
1. Property names are controlled strictly ('Value'or'value', not'VALUE')
2. Getting a property value for the first time is always done via a Basic call
3. Next occurrences are fetched from the Python dictionary of the instance if the property is read-only, otherwise via a Basic call
Each subclass must define its interface with the user scripts:
1. The properties
Property names are proper-cased
Conventionally, camel-cased and lower-cased synonyms are supported where relevant
Properties are grouped in a dictionary named 'serviceproperties' with keys = (proper-cased) property names and value = int
0 = read-only, fetch value locally
1 = read-only, fetch value from UNO/Basic because value might have been changed by user
2 = editable, fetch value locally
3 = editable, fetch value from UNO/Basic because value might have been changed by user
Properties that may be fetched locally are buffered in Python after their 1st get request to Basic or after their update. If there is a need to handle a specific property in a specific manner:
@property def myProperty(self): return self.GetProperty('myProperty')
2 The methods
a usual def: statement def myMethod(self, arg1, arg2 = ''): return self.Execute(self.vbMethod, 'myMethod', arg1, arg2)
Method names are proper-cased, arguments are lower-cased
Conventionally, camel-cased and lower-cased homonyms are supported in method names where relevant
All arguments must be present and initialized before the call to Basic, if any """ # Python-Basic protocol constants and flags
vbGet, vbLet, vbMethod, vbSet = 2, 4, 1, 8 # CallByName constants
flgPost = 16 # The method or the property implies a hardcoded post-processing
flgDictArg = 32 # Invoked service method may contain a dict argument
flgDateArg = 64 # Invoked service method may contain a date argument
flgDateRet = 128 # Invoked service method can return a date
flgArrayArg = 512 # 1st argument can be a 2D array
flgArrayRet = 1024 # Invoked service method can return a 2D array (standard modules) or any array (class modules)
flgUno = 256 # Invoked service method/property can return a UNO object
flgObject = 2048 # 1st argument may be a Basic object
flgHardCode = 4096 # Force hardcoded call to method, avoid CallByName() # Basic class type
moduleClass, moduleStandard = 2, 1 # # Empty dictionary for lower/camelcased homonyms of properties
propertysynonyms = {} # To operate dynamic property getting/setting it is necessary to # enumerate all types of properties and adapt __getattr__() and __setattr__() according to their type
internal_attributes = ('objectreference', 'objecttype', 'name', 'servicename', 'serviceimplementation', 'classmodule', 'EXEC', 'SIMPLEEXEC') # Shortcuts to script provider interfaces
SIMPLEEXEC = ScriptForge.InvokeSimpleScript
EXEC = ScriptForge.InvokeBasicService
def __init__(self, reference = -1, objtype = None, classmodule = 0, name = ''): """
Trivial initialization of internal properties If the subclass has its own __init()__ method, a call to this one should be its first statement. """
self.objectreference = reference # the index in the Python storage where the Basic object is stored
self.objecttype = objtype # ('SF_String', 'TIMER', ...)
self.classmodule = classmodule # Module (1), Class instance (2)
self.name = name # '' when no name
def __getattr__(self, name): """
Executed for EVERY property reference if name not yet in the instance dict
At the 1st get, the property value is always got from Basic
Due to the use of lower/camelcase synonyms, it is called for each variant of the same property
The method manages itself the buffering in __dict__ based on the official ProperCase property name """ if name in self.propertysynonyms: # Reset real name if argument provided in lower or camel case
name = self.propertysynonyms[name] if self.serviceimplementation == 'basic': if name in ('serviceproperties', 'internal_attributes', 'propertysynonyms'): pass elif name in self.serviceproperties:
prop = self.GetProperty(name) # Get Property from Basic if self.serviceproperties[name] in (0, 2): # Store the property value for later re-use
object.__setattr__(self, name, prop) return prop # Execute the usual attributes getter return super(SFServices, self).__getattribute__(name)
def __setattr__(self, name, value): """
Executed for EVERY property assignment, including in __init__() !!
Setting a property required for all serviceproperties() to be executed in Basic
The new value is stored for re-use in the local instance when relevant """ if self.serviceimplementation == 'basic': if name in self.internal_attributes: pass elif name in self.serviceproperties or name in self.propertysynonyms: if name in self.propertysynonyms: # Reset real name if argument provided in lower or camel case
name = self.propertysynonyms[name]
proplevel = self.serviceproperties[name] if proplevel in (2, 3): # Editable
self.SetProperty(name, value) if proplevel == 3: # Do not store in the local instance return else: raise AttributeError( "object of type '" + self.objecttype + "' has no editable property '" + name + "'") else: raise AttributeError("object of type '" + self.objecttype + "' has no property '" + name + "'")
object.__setattr__(self, name, value) # Store the new value in the local instance return
def GetProperty(self, propertyname, arg = None): """
Get the given property from the Basic world """ if self.serviceimplementation == 'basic': # Conventionally properties starting with X (and only them) may return a UNO object
calltype = self.vbGet + (self.flgUno if propertyname[0] == 'X'else 0) if arg isNone: return self.EXEC(self.objectreference, calltype, propertyname) else: # There are a few cases (Calc ...) where GetProperty accepts an argument return self.EXEC(self.objectreference, calltype, propertyname, arg) returnNone
def SetProperty(self, propertyname, value): """
Set the given property to a new value in the Basic world """ if self.serviceimplementation == 'basic':
flag = self.vbLet if isinstance(value, datetime.datetime):
value = SFScriptForge.SF_Basic.CDateToUnoDateTime(value)
flag += self.flgDateArg elif isinstance(value, dict):
flag += self.flgDictArg if repr(type(value)) == "":
flag += self.flgUno return self.EXEC(self.objectreference, flag, propertyname, value)
# ##################################################################################################################### # SFScriptForge CLASS (alias of ScriptForge Basic library) ### # ##################################################################################################################### class SFScriptForge:
# ######################################################################### # SF_Array CLASS # ######################################################################### class SF_Array(SFServices, metaclass = _Singleton): """
Provides a collection of methods for manipulating and transforming arrays of one dimension (vectors) and arrays of two dimensions (matrices). This includes set operations, sorting,
importing to and exporting from text files.
The Python version of the service provides a single method: ImportFromCSVFile """ # Mandatory class properties for service registration
serviceimplementation = 'basic'
servicename = 'ScriptForge.Array'
servicesynonyms = ('array', 'scriptforge.array')
serviceproperties = dict()
def ImportFromCSVFile(self, filename, delimiter = ',', dateformat = ''): """
Difference with the Basic version: dates are returned in their iso format, notas any of the datetime objects. """ return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'ImportFromCSVFile',
filename, delimiter, dateformat)
# ######################################################################### # SF_Basic CLASS # ######################################################################### class SF_Basic(SFServices, metaclass = _Singleton): """
This service proposes a collection of Basic methods to be executed in a Python context
simulating the exact syntax and behaviour of the identical Basic builtin method.
Typical example:
SF_Basic.MsgBox('This has to be displayed in a message box')
The signatures of Basic builtin functions are derived from
core/basic/source/runtime/stdobj.cxx
@staticmethod def CDateFromUnoDateTime(unodate): """
Converts a UNO date/time representation to a datetime.datetime Python native object
:param unodate: com.sun.star.util.DateTime, com.sun.star.util.Date or com.sun.star.util.Time
:return: the equivalent datetime.datetime """
date = datetime.datetime(1899, 12, 30, 0, 0, 0, 0) # Idem as Basic builtin TimeSerial() function
datetype = repr(type(unodate)) if'com.sun.star.util.DateTime'in datetype: if 1900 <= unodate.Year <= datetime.MAXYEAR:
date = datetime.datetime(unodate.Year, unodate.Month, unodate.Day, unodate.Hours,
unodate.Minutes, unodate.Seconds, int(unodate.NanoSeconds / 1000)) elif'com.sun.star.util.Date'in datetype: if 1900 <= unodate.Year <= datetime.MAXYEAR:
date = datetime.datetime(unodate.Year, unodate.Month, unodate.Day) elif'com.sun.star.util.Time'in datetype:
date = datetime.datetime(unodate.Hours, unodate.Minutes, unodate.Seconds,
int(unodate.NanoSeconds / 1000)) else: return unodate # Not recognized as a UNO date structure return date
@staticmethod def CDateToUnoDateTime(date): """
Converts a date representation into the ccom.sun.star.util.DateTime date format
Acceptable boundaries: year >= 1900 and <= 32767
:param date: datetime.datetime, datetime.date, datetime.time, float (time.time) or time.struct_time
:return: a com.sun.star.util.DateTime """
unodate = uno.createUnoStruct('com.sun.star.util.DateTime')
unodate.Year, unodate.Month, unodate.Day, unodate.Hours, unodate.Minutes, unodate.Seconds, \
unodate.NanoSeconds, unodate.IsUTC = \
1899, 12, 30, 0, 0, 0, 0, False# Identical to Basic TimeSerial() function
if isinstance(date, float):
date = time.localtime(date) if isinstance(date, time.struct_time): if 1900 <= date[0] <= 32767:
unodate.Year, unodate.Month, unodate.Day, unodate.Hours, unodate.Minutes, unodate.Seconds = \
date[0:6] else: # Copy only the time related part
unodate.Hours, unodate.Minutes, unodate.Seconds = date[3:3] elif isinstance(date, (datetime.datetime, datetime.date, datetime.time)): if isinstance(date, (datetime.datetime, datetime.date)): if 1900 <= date.year <= 32767:
unodate.Year, unodate.Month, unodate.Day = date.year, date.month, date.day if isinstance(date, (datetime.datetime, datetime.time)):
unodate.Hours, unodate.Minutes, unodate.Seconds, unodate.NanoSeconds = \
date.hour, date.minute, date.second, date.microsecond * 1000 else: return date # Not recognized as a date return unodate
class GlobalScope(object, metaclass = _Singleton):
@classmethod # Mandatory because the GlobalScope class is normally not instantiated def BasicLibraries(cls): return ScriptForge.InvokeSimpleScript(SFScriptForge.SF_Basic.module + '.PyGlobalScope', 'Basic')
@property def ThisComponent(self): """
When the current component is the Basic IDE, the ThisComponent object returns in Basic the component owning the currently run user script.
Above behaviour cannot be reproduced in Python.
:return: the current component orNone when not a document """
comp = self.StarDesktop.getCurrentComponent() if comp isNone: returnNone
impl = comp.ImplementationName if impl in ('com.sun.star.comp.basic.BasicIDE', 'com.sun.star.comp.sfx2.BackingComp'): returnNone# None when Basic IDE or welcome screen return comp
@property def ThisDatabaseDocument(self): """
When the current component is the Basic IDE, the ThisDatabaseDocument object returns in Basic the database owning the currently run user script.
Above behaviour cannot be reproduced in Python.
:return: the current Base (main) component orNone when not a Base document or one of its subcomponents """
comp = self.ThisComponent # Get the current component if comp isNone: returnNone #
sess = CreateScriptService('Session')
impl, ident = '', '' if sess.HasUnoProperty(comp, 'ImplementationName'):
impl = comp.ImplementationName if sess.HasUnoProperty(comp, 'Identifier'):
ident = comp.Identifier #
targetimpl = 'com.sun.star.comp.dba.ODatabaseDocument' if impl == targetimpl: # The current component is the main Base window return comp # Identify resp. form, table/query, table/query in edit mode, report, relations diagram if impl == 'SwXTextDocument'and ident == 'com.sun.star.sdb.FormDesign' \ or impl == 'org.openoffice.comp.dbu.ODatasourceBrowser' \ or impl in ('org.openoffice.comp.dbu.OTableDesign', 'org.openoffice.comp.dbu.OQuertDesign') \ or impl == 'SwXTextDocument'and ident == 'com.sun.star.sdb.TextReportDesign' \ or impl == 'org.openoffice.comp.dbu.ORelationDesign':
db = comp.ScriptContainer if sess.HasUnoProperty(db, 'ImplementationName'): if db.ImplementationName == targetimpl: return db returnNone
# ######################################################################### # SF_Dictionary CLASS # ######################################################################### class SF_Dictionary(SFServices, dict): """
The service adds to a Python dict instance the interfaces for conversion to andfrom
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() """ # Mandatory class properties for service registration
serviceimplementation = 'python'
servicename = 'ScriptForge.Dictionary'
servicesynonyms = ('dictionary', 'scriptforge.dictionary')
def ConvertToPropertyValues(self): """
Store the content of the dictionary in an array of PropertyValues.
Each entry in the array is a com.sun.star.beans.PropertyValue.
he 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.
The resulting array is empty when the dictionary is empty. """
result = [] for key in iter(self):
value = self[key]
item = value if isinstance(value, dict): # check that first level is not itself a (sub)dict
item = None elif isinstance(value, (tuple, list)): # check every member of the list is not a (sub)dict if len(value) == 0: # Property values do not like empty lists
value = None else: for i in range(len(value)): if isinstance(value[i], dict):
value[i] = None
item = value elif isinstance(value, (datetime.datetime, datetime.date, datetime.time)):
item = SFScriptForge.SF_Basic.CDateToUnoDateTime(value)
pv = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
pv.Name = key
pv.Value = item
result.append(pv) return result
def ImportFromPropertyValues(self, propertyvalues, overwrite = False): """
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.
:param propertyvalues: a list.tuple containing com.sun.star.beans.PropertyValue objects
:param 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.
:return: True when successful """
result = [] for pv in iter(propertyvalues):
key = pv.Name if overwrite isTrueor key notin self:
item = pv.Value if'com.sun.star.util.DateTime'in repr(type(item)):
item = datetime.datetime(item.Year, item.Month, item.Day,
item.Hours, item.Minutes, item.Seconds, int(item.NanoSeconds / 1000)) elif'com.sun.star.util.Date'in repr(type(item)):
item = datetime.datetime(item.Year, item.Month, item.Day) elif'com.sun.star.util.Time'in repr(type(item)):
item = datetime.datetime(item.Hours, item.Minutes, item.Seconds, int(item.NanoSeconds / 1000))
result.append((key, item))
self.update(result) returnTrue
# ######################################################################### # SF_Exception CLASS # ######################################################################### class SF_Exception(SFServices, metaclass = _Singleton): """
The Exception service is a collection of methods for code debugging and error handling.
The Exception service console stores events, variable values and information about errors.
Use the console when the Python shell isnot available, for example in Calc user defined functions (UDF) or during events processing.
Use DebugPrint() method to aggregate additional user data of any type.
Console entries can be dumped to a text file or visualized in a dialogue. """ # Mandatory class properties for service registration
serviceimplementation = 'basic'
servicename = 'ScriptForge.Exception'
servicesynonyms = ('exception', 'scriptforge.exception')
serviceproperties = dict(ReportScriptErrors = 3, ReturnCode = 1, ReturnCodeDescription = 1, StopWhenError = 3)
def Console(self, modal = True): # From Python, the current XComponentContext must be added as last argument return self.ExecMethod(self.vbMethod, 'Console', modal, ScriptForge.componentcontext)
def DebugDisplay(self, *args): # Arguments are concatenated in a single string similar to what the Python print() function would produce
self.DebugPrint(*args)
param = '\n'.join(list(map(lambda a: a.strip("'") if isinstance(a, str) else repr(a), args)))
bas = CreateScriptService('ScriptForge.Basic') return bas.MsgBox(param, bas.MB_OK + bas.MB_ICONINFORMATION, 'DebugDisplay')
def DebugPrint(self, *args): # Arguments are concatenated in a single string similar to what the Python print() function would produce # Avoid using repr() on strings to not have backslashes * 4
param = '\t'.join(list(map(lambda a: a.strip("'") if isinstance(a, str) else repr(a),
args))).expandtabs(tabsize = 4) return self.ExecMethod(self.vbMethod, 'DebugPrint', param)
@classmethod def PythonShell(cls, variables = None, background = 0xFDF6E3, foreground = 0x657B83): """
Open an APSO python shell window - Thanks to its authors Hanya/Tsutomu Uchino/Hubert Lambert
:param variables: Typical use
PythonShell.({**globals(), **locals()})
to push the globaland local dictionaries to the shell window
:param background: background color as an int
:param foreground: foreground color as an int """ if variables isNone:
variables = locals() # Is APSO installed ?
ctx = ScriptForge.componentcontext
ext = ctx.getByName('/singletons/com.sun.star.deployment.PackageInformationProvider')
apso = 'apso.python.script.organizer' if len(ext.getPackageLocation(apso)) > 0: # APSO is available. However, PythonShell() is ignored in bridge mode # because APSO library is not in pythonpath if ScriptForge.remoteprocess: returnNone # Directly derived from apso.oxt|python|scripts|tools.py$console # we need to load apso before import statement
ctx.ServiceManager.createInstance('apso.python.script.organizer.impl') # now we can use apso_utils library from apso_utils import console
kwargs = {'loc': variables, 'BACKGROUND': background, 'FOREGROUND': foreground, 'prettyprint': False}
kwargs['loc'].setdefault('XSCRIPTCONTEXT', uno)
console(**kwargs) # An interprocess call is necessary to allow a redirection of STDOUT and STDERR by APSO # Choice is a minimalist call to a Basic routine: no arguments, a few lines of code
SFScriptForge.SF_Basic.GetGuiType() else: # The APSO extension could not be located in your LibreOffice installation
cls._RaiseFatal('SF_Exception.PythonShell', 'variables=None', 'PYTHONSHELLERROR')
@classmethod def RaiseFatal(cls, errorcode, *args): """
Generate a run-time error caused by an anomaly in a user script detected by ScriptForge
The message is logged in the console. The execution is STOPPED For INTERNAL USE only """ # Direct call because RaiseFatal forces an execution stop in Basic if len(args) == 0:
args = (None,) return cls.SIMPLEEXEC('@SF_Exception.RaiseFatal', (errorcode, *args)) # With ParamArray
@classmethod def _RaiseFatal(cls, sub, subargs, errorcode, *args): """
Wrapper of RaiseFatal(). Includes method and syntax of the failed Python routine
to simulate the exact behaviour of the Basic RaiseFatal() method For INTERNAL USE only """
ScriptForge.InvokeSimpleScript('ScriptForge.SF_Utils._EnterFunction', sub, subargs)
cls.RaiseFatal(errorcode, *args) raise RuntimeError("The execution of the method '" + sub.split('.')[-1] + "' failed. Execution stops.")
# ######################################################################### # SF_FileSystem CLASS # ######################################################################### class SF_FileSystem(SFServices, metaclass = _Singleton): """
The "FileSystem" service includes common file and folder handling routines. """ # Mandatory class properties for service registration
serviceimplementation = 'basic'
servicename = 'ScriptForge.FileSystem'
servicesynonyms = ('filesystem', 'scriptforge.filesystem')
serviceproperties = dict(ConfigFolder = 1, ExtensionsFolder = 1, FileNaming = 3, HomeFolder = 1,
InstallFolder = 1, TemplatesFolder = 1, TemporaryFolder = 1,
UserTemplatesFolder = 1) # 1 because FileNaming determines every time the folder format # Open TextStream constants
ForReading, ForWriting, ForAppending = 1, 2, 8
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.