LibreOffice Module wizards (master) 1
scriptforge.py
Go to the documentation of this file.
1# -*- coding: utf-8 -*-
2
3# Copyright 2020-2022 Jean-Pierre LEDURE, Rafael LIMA, Alain ROMEDENNE
4
5# =====================================================================================================================
6# === The ScriptForge library and its associated libraries are part of the LibreOffice project. ===
7# === Full documentation is available on https://help.libreoffice.org/ ===
8# =====================================================================================================================
9
10# ScriptForge is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14# ScriptForge is free software; you can redistribute it and/or modify it under the terms of either (at your option):
15
16# 1) The Mozilla Public License, v. 2.0. If a copy of the MPL was not
17# distributed with this file, you can obtain one at http://mozilla.org/MPL/2.0/ .
18
19# 2) The GNU Lesser General Public License as published by
20# the Free Software Foundation, either version 3 of the License, or
21# (at your option) any later version. If a copy of the LGPL was not
22# distributed with this file, see http://www.gnu.org/licenses/ .
23
24"""
25 ScriptForge libraries are an extensible and robust collection of macro scripting resources for LibreOffice
26 to be invoked from user Basic or Python macros. Users familiar with other BASIC macro variants often face hard
27 times to dig into the extensive LibreOffice Application Programming Interface even for the simplest operations.
28 By collecting most-demanded document operations in a set of easy to use, easy to read routines, users can now
29 program document macros with much less hassle and get quicker results.
30
31 ScriptForge abundant methods are organized in reusable modules that cleanly isolate Basic/Python programming
32 language constructs from ODF document content accesses and user interface(UI) features.
33
34 The scriptforge.py module
35 - implements a protocol between Python (user) scripts and the ScriptForge Basic library
36 - contains the interfaces (classes and attributes) to be used in Python user scripts
37 to run the services implemented in the standard libraries shipped with LibreOffice
38
39 Usage:
40
41 When Python and LibreOffice run in the same process (usual case): either
42 from scriptforge import * # or, better ...
43 from scriptforge import CreateScriptService
44
45 When Python and LibreOffice are started in separate processes,
46 LibreOffice being started from console ... (example for Linux with port = 2021)
47 ./soffice --accept='socket,host=localhost,port=2021;urp;'
48 then use next statement:
49 from scriptforge import * # or, better ...
50 from scriptforge import CreateScriptService, ScriptForge
51 ScriptForge(hostname = 'localhost', port = 2021)
52
53 Specific documentation about the use of ScriptForge from Python scripts:
54 https://help.libreoffice.org/latest/en-US/text/sbasic/shared/03/sf_intro.html?DbPAR=BASIC
55 """
56
57import uno
58
59import datetime
60import time
61import os
62
63
64class _Singleton(type):
65 """
66 A Singleton metaclass design pattern
67 Credits: « Python in a Nutshell » by Alex Martelli, O'Reilly
68 """
69 instances = {}
70
71 def __call__(cls, *args, **kwargs):
72 if cls not in cls.instances:
73 cls.instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
74 return cls.instances[cls]
75
76
77# #####################################################################################################################
78# ScriptForge CLASS ###
79# #####################################################################################################################
80
81class ScriptForge(object, metaclass = _Singleton):
82 """
83 The ScriptForge (singleton) class encapsulates the core of the ScriptForge run-time
84 - Bridge with the LibreOffice process
85 - Implementation of the inter-language protocol with the Basic libraries
86 - Identification of the available services interfaces
87 - Dispatching of services
88 - Coexistence with UNO
89
90 It embeds the Service class that manages the protocol with Basic
91 """
92
93 # #########################################################################
94 # Class attributes
95 # #########################################################################
96 hostname = ''
97 port = 0
98 componentcontext = None
99 scriptprovider = None
100 SCRIPTFORGEINITDONE = False
101
102 # #########################################################################
103 # Class constants
104 # #########################################################################
105 library = 'ScriptForge'
106 Version = '7.6' # Actual version number
107 #
108 # Basic dispatcher for Python scripts
109 basicdispatcher = '@application#ScriptForge.SF_PythonHelper._PythonDispatcher'
110 # Python helper functions module
111 pythonhelpermodule = 'ScriptForgeHelper.py'
112 #
113 # VarType() constants
114 V_EMPTY, V_NULL, V_INTEGER, V_LONG, V_SINGLE, V_DOUBLE = 0, 1, 2, 3, 4, 5
115 V_CURRENCY, V_DATE, V_STRING, V_OBJECT, V_BOOLEAN = 6, 7, 8, 9, 11
116 V_VARIANT, V_ARRAY, V_ERROR, V_UNO = 12, 8192, -1, 16
117 # Object types
118 objMODULE, objCLASS, objUNO = 1, 2, 3
119 # Special argument symbols
120 cstSymEmpty, cstSymNull, cstSymMissing = '+++EMPTY+++', '+++NULL+++', '+++MISSING+++'
121 # Predefined references for services implemented as standard Basic modules
122 servicesmodules = dict([('ScriptForge.Array', 0),
123 ('ScriptForge.Exception', 1),
124 ('ScriptForge.FileSystem', 2),
125 ('ScriptForge.Platform', 3),
126 ('ScriptForge.Region', 4),
127 ('ScriptForge.Services', 5),
128 ('ScriptForge.Session', 6),
129 ('ScriptForge.String', 7),
130 ('ScriptForge.UI', 8)])
131
132 def __init__(self, hostname = '', port = 0):
133 """
134 Because singleton, constructor is executed only once while Python active
135 Arguments are mandatory when Python and LibreOffice run in separate processes
136 :param hostname: probably 'localhost'
137 :param port: port number
138 """
139 ScriptForge.hostname = hostname
140 ScriptForge.port = port
141 # Determine main pyuno entry points
142 ScriptForge.componentcontext = self.ConnectToLOProcess(hostname, port) # com.sun.star.uno.XComponentContext
143 ScriptForge.scriptprovider = self.ScriptProvider(self.componentcontext) # ...script.provider.XScriptProvider
144 #
145 # Establish a list of the available services as a dictionary (servicename, serviceclass)
146 ScriptForge.serviceslist = dict((cls.servicename, cls) for cls in SFServices.__subclasses__())
147 ScriptForge.servicesdispatcher = None
148 #
149 # All properties and methods of the ScriptForge API are ProperCased
150 # Compute their synonyms as lowercased and camelCased names
151 ScriptForge.SetAttributeSynonyms()
152 #
153 ScriptForge.SCRIPTFORGEINITDONE = True
154
155 @classmethod
156 def ConnectToLOProcess(cls, hostname = '', port = 0):
157 """
158 Called by the ScriptForge class constructor to establish the connection with
159 the requested LibreOffice instance
160 The default arguments are for the usual interactive mode
161
162 :param hostname: probably 'localhost' or ''
163 :param port: port number or 0
164 :return: the derived component context
165 """
166 if len(hostname) > 0 and port > 0: # Explicit connection request via socket
167 ctx = uno.getComponentContext() # com.sun.star.uno.XComponentContext
168 resolver = ctx.ServiceManager.createInstanceWithContext(
169 'com.sun.star.bridge.UnoUrlResolver', ctx) # com.sun.star.comp.bridge.UnoUrlResolver
170 try:
171 conn = 'socket,host=%s,port=%d' % (hostname, port)
172 url = 'uno:%s;urp;StarOffice.ComponentContext' % conn
173 ctx = resolver.resolve(url)
174 except Exception: # thrown when LibreOffice specified instance isn't started
175 raise SystemExit(
176 'Connection to LibreOffice failed (host = ' + hostname + ', port = ' + str(port) + ')')
177 return ctx
178 elif len(hostname) == 0 and port == 0: # Usual interactive mode
180 else:
181 raise SystemExit('The creation of the ScriptForge() instance got invalid arguments: '
182 + '(host = ' + hostname + ', port = ' + str(port) + ')')
183
184 @classmethod
185 def ScriptProvider(cls, context = None):
186 """
187 Returns the general script provider
188 """
189 servicemanager = context.ServiceManager # com.sun.star.lang.XMultiComponentFactory
190 masterscript = servicemanager.createInstanceWithContext(
191 'com.sun.star.script.provider.MasterScriptProviderFactory', context)
192 return masterscript.createScriptProvider("")
193
194 @classmethod
195 def InvokeSimpleScript(cls, script, *args):
196 """
197 Create a UNO object corresponding with the given Python or Basic script
198 The execution is done with the invoke() method applied on the created object
199 Implicit scope: Either
200 "application" a shared library (BASIC)
201 "share" a library of LibreOffice Macros (PYTHON)
202 :param script: Either
203 [@][scope#][library.]module.method - Must not be a class module or method
204 [@] means that the targeted method accepts ParamArray arguments (Basic only)
205 [scope#][directory/]module.py$method - Must be a method defined at module level
206 :return: the value returned by the invoked script, or an error if the script was not found
207 """
208
209 # The frequently called PythonDispatcher in the ScriptForge Basic library is cached to privilege performance
210 if cls.servicesdispatcher is not None and script == ScriptForge.basicdispatcher:
211 xscript = cls.servicesdispatcher
212 fullscript = script
213 paramarray = True
214 # Build the URI specification described in
215 # https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework#Scripting_Framework_URI_Specification
216 elif len(script) > 0:
217 # Check ParamArray arguments
218 paramarray = False
219 if script[0] == '@':
220 script = script[1:]
221 paramarray = True
222 scope = ''
223 if '#' in script:
224 scope, script = script.split('#')
225 if '.py$' in script.lower(): # Python
226 if len(scope) == 0:
227 scope = 'share' # Default for Python
228 # Provide an alternate helper script depending on test context
229 if script.startswith(cls.pythonhelpermodule) and hasattr(cls, 'pythonhelpermodule2'):
230 script = cls.pythonhelpermodule2 + script[len(cls.pythonhelpermodule):]
231 if '#' in script:
232 scope, script = script.split('#')
233 uri = 'vnd.sun.star.script:{0}?language=Python&location={1}'.format(script, scope)
234 else: # Basic
235 if len(scope) == 0:
236 scope = 'application' # Default for Basic
237 lib = ''
238 if len(script.split('.')) < 3:
239 lib = cls.library + '.' # Default library = ScriptForge
240 uri = 'vnd.sun.star.script:{0}{1}?language=Basic&location={2}'.format(lib, script, scope)
241 # Get the script object
242 fullscript = ('@' if paramarray else '') + scope + ':' + script
243 try:
244 xscript = cls.scriptprovider.getScript(uri)
245 except Exception:
246 raise RuntimeError(
247 'The script \'{0}\' could not be located in your LibreOffice installation'.format(script))
248 else: # Should not happen
249 return None
250
251 # At 1st execution of the common Basic dispatcher, buffer xscript
252 if fullscript == ScriptForge.basicdispatcher and cls.servicesdispatcher is None:
253 cls.servicesdispatcher = xscript
254
255 # Execute the script with the given arguments
256 # Packaging for script provider depends on presence of ParamArray arguments in the called Basic script
257 if paramarray:
258 scriptreturn = xscript.invoke(args[0], (), ())
259 else:
260 scriptreturn = xscript.invoke(args, (), ())
261
262 #
263 return scriptreturn[0] # Updatable arguments passed by reference are ignored
264
265 @classmethod
266 def InvokeBasicService(cls, basicobject, flags, method, *args):
267 """
268 Execute a given Basic script and interpret its result
269 This method has as counterpart the ScriptForge.SF_PythonHelper._PythonDispatcher() Basic method
270 :param basicobject: a Service subclass
271 :param flags: see the vb* and flg* constants in the SFServices class
272 :param method: the name of the method or property to invoke, as a string
273 :param args: the arguments of the method. Symbolic cst* constants may be necessary
274 :return: The invoked Basic counterpart script (with InvokeSimpleScript()) will return a tuple
275 [0] The returned value - scalar, object reference or a tuple
276 [1] The Basic VarType() of the returned value
277 Null, Empty and Nothing have different vartypes but return all None to Python
278 Additionally, when [0] is a tuple:
279 [2] Number of dimensions in Basic
280 Additionally, when [0] is a UNO or Basic object:
281 [2] Module (1), Class instance (2) or UNO (3)
282 [3] The object's ObjectType
283 [4] The object's ServiceName
284 [5] The object's name
285 When an error occurs Python receives None as a scalar. This determines the occurrence of a failure
286 The method returns either
287 - the 0th element of the tuple when scalar, tuple or UNO object
288 - a new Service() object or one of its subclasses otherwise
289 """
290 # Constants
291 script = ScriptForge.basicdispatcher
292 cstNoArgs = '+++NOARGS+++'
293 cstValue, cstVarType, cstDims, cstClass, cstType, cstService, cstName = 0, 1, 2, 2, 3, 4, 5
294
295 #
296 # Run the basic script
297 # The targeted script has a ParamArray argument. Do not change next 4 lines except if you know what you do !
298 if len(args) == 0:
299 args = (basicobject,) + (flags,) + (method,) + (cstNoArgs,)
300 else:
301 args = (basicobject,) + (flags,) + (method,) + args
302 returntuple = cls.InvokeSimpleScript(script, args)
303 #
304 # Interpret the result
305 # Did an error occur in the Basic world ?
306 if not isinstance(returntuple, (tuple, list)):
307 raise RuntimeError("The execution of the method '" + method + "' failed. Execution stops.")
308 #
309 # Analyze the returned tuple
310 if returntuple[cstVarType] == ScriptForge.V_OBJECT and len(returntuple) > cstClass: # Avoid Nothing
311 if returntuple[cstClass] == ScriptForge.objUNO:
312 pass
313 else:
314 # Create the new class instance of the right subclass of SFServices()
315 servname = returntuple[cstService]
316 if servname not in cls.serviceslist:
317 # When service not found
318 raise RuntimeError("The service '" + servname + "' is not available in Python. Execution stops.")
319 subcls = cls.serviceslist[servname]
320 if subcls is not None:
321 return subcls(returntuple[cstValue], returntuple[cstType], returntuple[cstClass],
322 returntuple[cstName])
323 elif returntuple[cstVarType] >= ScriptForge.V_ARRAY:
324 # Intercept empty array
325 if isinstance(returntuple[cstValue], uno.ByteSequence):
326 return ()
327 elif returntuple[cstVarType] == ScriptForge.V_DATE:
328 dat = SFScriptForge.SF_Basic.CDateFromUnoDateTime(returntuple[cstValue])
329 return dat
330 else: # All other scalar values
331 pass
332 return returntuple[cstValue]
333
334 @staticmethod
336 """
337 A synonym of an attribute is either the lowercase or the camelCase form of its original ProperCase name.
338 In every subclass of SFServices:
339 1) Fill the propertysynonyms dictionary with the synonyms of the properties listed in serviceproperties
340 Example:
341 serviceproperties = dict(ConfigFolder = False, InstallFolder = False)
342 propertysynonyms = dict(configfolder = 'ConfigFolder', installfolder = 'InstallFolder',
343 configFolder = 'ConfigFolder', installFolder = 'InstallFolder')
344 2) Define new method attributes synonyms of the original methods
345 Example:
346 def CopyFile(...):
347 # etc ...
348 copyFile, copyfile = CopyFile, CopyFile
349 """
350
351 def camelCase(key):
352 return key[0].lower() + key[1:]
353
354 for cls in SFServices.__subclasses__():
355 # Synonyms of properties
356 if hasattr(cls, 'serviceproperties'):
357 dico = cls.serviceproperties
358 dicosyn = dict(zip(map(str.lower, dico.keys()), dico.keys())) # lower case
359 cc = dict(zip(map(camelCase, dico.keys()), dico.keys())) # camel Case
360 dicosyn.update(cc)
361 setattr(cls, 'propertysynonyms', dicosyn)
362 # Synonyms of methods. A method is a public callable attribute
363 methods = [method for method in dir(cls) if not method.startswith('_')]
364 for method in methods:
365 func = getattr(cls, method)
366 if callable(func):
367 # Assign to each synonym a reference to the original method
368 lc = method.lower()
369 setattr(cls, lc, func)
370 cc = camelCase(method)
371 if cc != lc:
372 setattr(cls, cc, func)
373 return
374
375 @staticmethod
376 def unpack_args(kwargs):
377 """
378 Convert a dictionary passed as argument to a list alternating keys and values
379 Example:
380 dict(A = 'a', B = 2) => 'A', 'a', 'B', 2
381 """
382 return [v for p in zip(list(kwargs.keys()), list(kwargs.values())) for v in p]
383
384
385# #####################################################################################################################
386# SFServices CLASS (ScriptForge services superclass) ###
387# #####################################################################################################################
388
389class SFServices(object):
390 """
391 Generic implementation of a parent Service class
392 Every service must subclass this class to be recognized as a valid service
393 A service instance is created by the CreateScriptService method
394 It can have a mirror in the Basic world or be totally defined in Python
395
396 Every subclass must initialize 3 class properties:
397 servicename (e.g. 'ScriptForge.FileSystem', 'ScriptForge.Basic')
398 servicesynonyms (e.g. 'FileSystem', 'Basic')
399 serviceimplementation: either 'python' or 'basic'
400 This is sufficient to register the service in the Python world
401
402 The communication with Basic is managed by 2 ScriptForge() methods:
403 InvokeSimpleScript(): low level invocation of a Basic script. This script must be located
404 in a usual Basic module. The result is passed as-is
405 InvokeBasicService(): the result comes back encapsulated with additional info
406 The result is interpreted in the method
407 The invoked script can be a property or a method of a Basic class or usual module
408 It is up to every service method to determine which method to use
409
410 For Basic services only:
411 Each instance is identified by its
412 - object reference: the real Basic object embedded as a UNO wrapper object
413 - object type ('SF_String', 'DICTIONARY', ...)
414 - class module: 1 for usual modules, 2 for class modules
415 - name (form, control, ... name) - may be blank
416
417 The role of the SFServices() superclass is mainly to propose a generic properties management
418 Properties are got and set following next strategy:
419 1. Property names are controlled strictly ('Value' or 'value', not 'VALUE')
420 2. Getting a property value for the first time is always done via a Basic call
421 3. Next occurrences are fetched from the Python dictionary of the instance if the property
422 is read-only, otherwise via a Basic call
423 4. Read-only properties may be modified or deleted exceptionally by the class
424 when self.internal == True. The latter must immediately be reset after use
425
426 Each subclass must define its interface with the user scripts:
427 1. The properties
428 Property names are proper-cased
429 Conventionally, camel-cased and lower-cased synonyms are supported where relevant
430 a dictionary named 'serviceproperties' with keys = (proper-cased) property names and value = boolean
431 True = editable, False = read-only
432 a list named 'localProperties' reserved to properties for internal use
433 e.g. oDlg.Controls() is a method that uses '_Controls' to hold the list of available controls
434 When
435 forceGetProperty = False # Standard behaviour
436 read-only serviceproperties are buffered in Python after their 1st get request to Basic
437 Otherwise set it to True to force a recomputation at each property getter invocation
438 If there is a need to handle a specific property in a specific manner:
439 @property
440 def myProperty(self):
441 return self.GetProperty('myProperty')
442 2 The methods
443 a usual def: statement
444 def myMethod(self, arg1, arg2 = ''):
445 return self.Execute(self.vbMethod, 'myMethod', arg1, arg2)
446 Method names are proper-cased, arguments are lower-cased
447 Conventionally, camel-cased and lower-cased homonyms are supported where relevant
448 All arguments must be present and initialized before the call to Basic, if any
449 """
450 # Python-Basic protocol constants and flags
451 vbGet, vbLet, vbMethod, vbSet = 2, 4, 1, 8 # CallByName constants
452 flgPost = 32 # The method or the property implies a hardcoded post-processing
453 flgDateArg = 64 # Invoked service method may contain a date argument
454 flgDateRet = 128 # Invoked service method can return a date
455 flgArrayArg = 512 # 1st argument can be a 2D array
456 flgArrayRet = 1024 # Invoked service method can return a 2D array (standard modules) or any array (class modules)
457 flgUno = 256 # Invoked service method/property can return a UNO object
458 flgObject = 2048 # 1st argument may be a Basic object
459 flgHardCode = 4096 # Force hardcoded call to method, avoid CallByName()
460 # Basic class type
461 moduleClass, moduleStandard = 2, 1
462 #
463 # Define the default behaviour for read-only properties: buffer their values in Python
464 forceGetProperty = False
465 # Empty dictionary for lower/camelcased homonyms or properties
466 propertysynonyms = {}
467 # To operate dynamic property getting/setting it is necessary to
468 # enumerate all types of properties and adapt __getattr__() and __setattr__() according to their type
469 internal_attributes = ('objectreference', 'objecttype', 'name', 'internal', 'servicename',
470 'serviceimplementation', 'classmodule', 'EXEC', 'SIMPLEEXEC')
471 # Shortcuts to script provider interfaces
472 SIMPLEEXEC = ScriptForge.InvokeSimpleScript
473 EXEC = ScriptForge.InvokeBasicService
474
475 def __init__(self, reference = -1, objtype = None, classmodule = 0, name = ''):
476 """
477 Trivial initialization of internal properties
478 If the subclass has its own __init()__ method, a call to this one should be its first statement.
479 Afterwards localProperties should be filled with the list of its own properties
480 """
481 self.objectreference = reference # the index in the Python storage where the Basic object is stored
482 self.objecttype = objtype # ('SF_String', 'DICTIONARY', ...)
483 self.classmodule = classmodule # Module (1), Class instance (2)
484 self.name = name # '' when no name
485 self.internal = False # True to exceptionally allow assigning a new value to a read-only property
486 self.localProperties = [] # the properties reserved for internal use (often empty)
487
488 def __getattr__(self, name):
489 """
490 Executed for EVERY property reference if name not yet in the instance dict
491 At the 1st get, the property value is always got from Basic
492 Due to the use of lower/camelcase synonyms, it is called for each variant of the same property
493 The method manages itself the buffering in __dict__ based on the official ProperCase property name
494 """
495 if name in self.propertysynonyms: # Reset real name if argument provided in lower or camel case
496 name = self.propertysynonyms[name]
497 if self.serviceimplementation == 'basic':
498 if name in ('serviceproperties', 'localProperties', 'internal_attributes', 'propertysynonyms',
499 'forceGetProperty'):
500 pass
501 elif name in self.serviceproperties:
502 if self.forceGetProperty is False and self.serviceproperties[name] is False: # False = read-only
503 if name in self.__dict__:
504 return self.__dict__[name]
505 else:
506 # Get Property from Basic and store it
507 prop = self.GetProperty(name)
508 self.__dict__[name] = prop
509 return prop
510 else: # Get Property from Basic and do not store it
511 return self.GetProperty(name)
512 # Execute the usual attributes getter
513 return super(SFServices, self).__getattribute__(name)
514
515 def __setattr__(self, name, value):
516 """
517 Executed for EVERY property assignment, including in __init__() !!
518 Setting a property requires for serviceproperties() to be executed in Basic
519 Management of __dict__ is automatically done in the final usual object.__setattr__ method
520 """
521 if self.serviceimplementation == 'basic':
522 if name in ('serviceproperties', 'localProperties', 'internal_attributes', 'propertysynonyms',
523 'forceGetProperty'):
524 pass
525 elif name[0:2] == '__' or name in self.internal_attributes or name in self.localProperties:
526 pass
527 elif name in self.serviceproperties or name in self.propertysynonyms:
528 if name in self.propertysynonyms: # Reset real name if argument provided in lower or camel case
529 name = self.propertysynonyms[name]
530 if self.internal: # internal = True forces property local setting even if property is read-only
531 pass
532 elif self.serviceproperties[name] is True: # True == Editable
533 self.SetProperty(name, value)
534 return
535 else:
536 raise AttributeError(
537 "type object '" + self.objecttype + "' has no editable property '" + name + "'")
538 else:
539 raise AttributeError("type object '" + self.objecttype + "' has no property '" + name + "'")
540 object.__setattr__(self, name, value)
541 return
542
543 def __repr__(self):
544 return self.serviceimplementation + '/' + self.servicename + '/' + str(self.objectreference) + '/' + \
545 super(SFServices, self).__repr__()
546
547 def Dispose(self):
548 if self.serviceimplementation == 'basic':
549 if self.objectreference >= len(ScriptForge.servicesmodules): # Do not dispose predefined module objects
550 self.ExecMethod(self.vbMethod, 'Dispose')
551 self.objectreference = -1
552
553 def ExecMethod(self, flags = 0, methodname = '', *args):
554 if flags == 0:
555 flags = self.vbMethod
556 if len(methodname) > 0:
557 return self.EXEC(self.objectreference, flags, methodname, *args)
558
559 def GetProperty(self, propertyname, arg = None):
560 """
561 Get the given property from the Basic world
562 """
563 if self.serviceimplementation == 'basic':
564 # Conventionally properties starting with X (and only them) may return a UNO object
565 calltype = self.vbGet + (self.flgUno if propertyname[0] == 'X' else 0)
566 if arg is None:
567 return self.EXEC(self.objectreference, calltype, propertyname)
568 else: # There are a few cases (Calc ...) where GetProperty accepts an argument
569 return self.EXEC(self.objectreference, calltype, propertyname, arg)
570 return None
571
572 def Properties(self):
573 return list(self.serviceproperties)
574
575 def basicmethods(self):
576 if self.serviceimplementation == 'basic':
577 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'Methods')
578 else:
579 return []
580
582 if self.serviceimplementation == 'basic':
583 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'Properties')
584 else:
585 return []
586
587 def SetProperty(self, propertyname, value):
588 """
589 Set the given property to a new value in the Basic world
590 """
591 if self.serviceimplementation == 'basic':
592 flag = self.vbLet
593 if isinstance(value, datetime.datetime):
594 value = SFScriptForge.SF_Basic.CDateToUnoDateTime(value)
595 flag += self.flgDateArg
596 if repr(type(value)) == "<class 'pyuno'>":
597 flag += self.flgUno
598 return self.EXEC(self.objectreference, flag, propertyname, value)
599
600
601# #####################################################################################################################
602# SFScriptForge CLASS (alias of ScriptForge Basic library) ###
603# #####################################################################################################################
605 pass
606
607 # #########################################################################
608 # SF_Array CLASS
609 # #########################################################################
610 class SF_Array(SFServices, metaclass = _Singleton):
611 """
612 Provides a collection of methods for manipulating and transforming arrays of one dimension (vectors)
613 and arrays of two dimensions (matrices). This includes set operations, sorting,
614 importing to and exporting from text files.
615 The Python version of the service provides a single method: ImportFromCSVFile
616 """
617 # Mandatory class properties for service registration
618 serviceimplementation = 'basic'
619 servicename = 'ScriptForge.Array'
620 servicesynonyms = ('array', 'scriptforge.array')
621 serviceproperties = dict()
622
623 def ImportFromCSVFile(self, filename, delimiter = ',', dateformat = ''):
624 """
625 Difference with the Basic version: dates are returned in their iso format,
626 not as any of the datetime objects.
627 """
628 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'ImportFromCSVFile',
629 filename, delimiter, dateformat)
630
631 # #########################################################################
632 # SF_Basic CLASS
633 # #########################################################################
634 class SF_Basic(SFServices, metaclass = _Singleton):
635 """
636 This service proposes a collection of Basic methods to be executed in a Python context
637 simulating the exact syntax and behaviour of the identical Basic builtin method.
638 Typical example:
639 SF_Basic.MsgBox('This has to be displayed in a message box')
640
641 The signatures of Basic builtin functions are derived from
642 core/basic/source/runtime/stdobj.cxx
643
644 Detailed user documentation:
645 https://help.libreoffice.org/latest/en-US/text/sbasic/shared/03/sf_basic.html?DbPAR=BASIC
646 """
647 # Mandatory class properties for service registration
648 serviceimplementation = 'python'
649 servicename = 'ScriptForge.Basic'
650 servicesynonyms = ('basic', 'scriptforge.basic')
651 # Basic helper functions invocation
652 module = 'SF_PythonHelper'
653 # Message box constants
654 MB_ABORTRETRYIGNORE, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3 = 2, 128, 256, 512
655 MB_ICONEXCLAMATION, MB_ICONINFORMATION, MB_ICONQUESTION, MB_ICONSTOP = 48, 64, 32, 16
656 MB_OK, MB_OKCANCEL, MB_RETRYCANCEL, MB_YESNO, MB_YESNOCANCEL = 0, 1, 5, 4, 3
657 IDABORT, IDCANCEL, IDIGNORE, IDNO, IDOK, IDRETRY, IDYES = 3, 2, 5, 7, 1, 4, 6
658
659 @classmethod
660 def CDate(cls, datevalue):
661 cdate = cls.SIMPLEEXEC(cls.module + '.PyCDate', datevalue)
662 return cls.CDateFromUnoDateTime(cdate)
663
664 @staticmethod
666 """
667 Converts a UNO date/time representation to a datetime.datetime Python native object
668 :param unodate: com.sun.star.util.DateTime, com.sun.star.util.Date or com.sun.star.util.Time
669 :return: the equivalent datetime.datetime
670 """
671 date = datetime.datetime(1899, 12, 30, 0, 0, 0, 0) # Idem as Basic builtin TimeSerial() function
672 datetype = repr(type(unodate))
673 if 'com.sun.star.util.DateTime' in datetype:
674 if 1900 <= unodate.Year <= datetime.MAXYEAR:
675 date = datetime.datetime(unodate.Year, unodate.Month, unodate.Day, unodate.Hours,
676 unodate.Minutes, unodate.Seconds, int(unodate.NanoSeconds / 1000))
677 elif 'com.sun.star.util.Date' in datetype:
678 if 1900 <= unodate.Year <= datetime.MAXYEAR:
679 date = datetime.datetime(unodate.Year, unodate.Month, unodate.Day)
680 elif 'com.sun.star.util.Time' in datetype:
681 date = datetime.datetime(unodate.Hours, unodate.Minutes, unodate.Seconds,
682 int(unodate.NanoSeconds / 1000))
683 else:
684 return unodate # Not recognized as a UNO date structure
685 return date
686
687 @staticmethod
689 """
690 Converts a date representation into the ccom.sun.star.util.DateTime date format
691 Acceptable boundaries: year >= 1900 and <= 32767
692 :param date: datetime.datetime, datetime.date, datetime.time, float (time.time) or time.struct_time
693 :return: a com.sun.star.util.DateTime
694 """
695 unodate = uno.createUnoStruct('com.sun.star.util.DateTime')
696 unodate.Year, unodate.Month, unodate.Day, unodate.Hours, unodate.Minutes, unodate.Seconds, \
697 unodate.NanoSeconds, unodate.IsUTC = \
698 1899, 12, 30, 0, 0, 0, 0, False # Identical to Basic TimeSerial() function
699
700 if isinstance(date, float):
701 date = time.localtime(date)
702 if isinstance(date, time.struct_time):
703 if 1900 <= date[0] <= 32767:
704 unodate.Year, unodate.Month, unodate.Day, unodate.Hours, unodate.Minutes, unodate.Seconds = \
705 date[0:6]
706 else: # Copy only the time related part
707 unodate.Hours, unodate.Minutes, unodate.Seconds = date[3:3]
708 elif isinstance(date, (datetime.datetime, datetime.date, datetime.time)):
709 if isinstance(date, (datetime.datetime, datetime.date)):
710 if 1900 <= date.year <= 32767:
711 unodate.Year, unodate.Month, unodate.Day = date.year, date.month, date.day
712 if isinstance(date, (datetime.datetime, datetime.time)):
713 unodate.Hours, unodate.Minutes, unodate.Seconds, unodate.NanoSeconds = \
714 date.hour, date.minute, date.second, date.microsecond * 1000
715 else:
716 return date # Not recognized as a date
717 return unodate
718
719 @classmethod
720 def ConvertFromUrl(cls, url):
721 return cls.SIMPLEEXEC(cls.module + '.PyConvertFromUrl', url)
722
723 @classmethod
724 def ConvertToUrl(cls, systempath):
725 return cls.SIMPLEEXEC(cls.module + '.PyConvertToUrl', systempath)
726
727 @classmethod
728 def CreateUnoService(cls, servicename):
729 return cls.SIMPLEEXEC(cls.module + '.PyCreateUnoService', servicename)
730
731 @classmethod
732 def CreateUnoStruct(cls, unostructure):
733 return uno.createUnoStruct(unostructure)
734
735 @classmethod
736 def DateAdd(cls, interval, number, date):
737 if isinstance(date, datetime.datetime):
738 date = cls.CDateToUnoDateTime(date)
739 dateadd = cls.SIMPLEEXEC(cls.module + '.PyDateAdd', interval, number, date)
740 return cls.CDateFromUnoDateTime(dateadd)
741
742 @classmethod
743 def DateDiff(cls, interval, date1, date2, firstdayofweek = 1, firstweekofyear = 1):
744 if isinstance(date1, datetime.datetime):
745 date1 = cls.CDateToUnoDateTime(date1)
746 if isinstance(date2, datetime.datetime):
747 date2 = cls.CDateToUnoDateTime(date2)
748 return cls.SIMPLEEXEC(cls.module + '.PyDateDiff', interval, date1, date2, firstdayofweek, firstweekofyear)
749
750 @classmethod
751 def DatePart(cls, interval, date, firstdayofweek = 1, firstweekofyear = 1):
752 if isinstance(date, datetime.datetime):
753 date = cls.CDateToUnoDateTime(date)
754 return cls.SIMPLEEXEC(cls.module + '.PyDatePart', interval, date, firstdayofweek, firstweekofyear)
755
756 @classmethod
757 def DateValue(cls, string):
758 if isinstance(string, datetime.datetime):
759 string = string.isoformat()
760 datevalue = cls.SIMPLEEXEC(cls.module + '.PyDateValue', string)
761 return cls.CDateFromUnoDateTime(datevalue)
762
763 @classmethod
764 def Format(cls, expression, format = ''):
765 if isinstance(expression, datetime.datetime):
766 expression = cls.CDateToUnoDateTime(expression)
767 return cls.SIMPLEEXEC(cls.module + '.PyFormat', expression, format)
768
769 @classmethod
771 return ScriptForge.componentcontext
772
773 @classmethod
774 def GetGuiType(cls):
775 return cls.SIMPLEEXEC(cls.module + '.PyGetGuiType')
776
777 @classmethod
779 return os.sep
780
781 @classmethod
783 return cls.SIMPLEEXEC(cls.module + '.PyGetSystemTicks')
784
785 class GlobalScope(object, metaclass = _Singleton):
786 @classmethod # Mandatory because the GlobalScope class is normally not instantiated
788 return ScriptForge.InvokeSimpleScript(SFScriptForge.SF_Basic.module + '.PyGlobalScope', 'Basic')
789
790 @classmethod
792 return ScriptForge.InvokeSimpleScript(SFScriptForge.SF_Basic.module + '.PyGlobalScope', 'Dialog')
793
794 @classmethod
795 def InputBox(cls, prompt, title = '', default = '', xpostwips = -1, ypostwips = -1):
796 if xpostwips < 0 or ypostwips < 0:
797 return cls.SIMPLEEXEC(cls.module + '.PyInputBox', prompt, title, default)
798 return cls.SIMPLEEXEC(cls.module + '.PyInputBox', prompt, title, default, xpostwips, ypostwips)
799
800 @classmethod
801 def MsgBox(cls, prompt, buttons = 0, title = ''):
802 return cls.SIMPLEEXEC(cls.module + '.PyMsgBox', prompt, buttons, title)
803
804 @classmethod
805 def Now(cls):
806 return datetime.datetime.now()
807
808 @classmethod
809 def RGB(cls, red, green, blue):
810 return int('%02x%02x%02x' % (red, green, blue), 16)
811
812 @property
813 def StarDesktop(self):
814 ctx = ScriptForge.componentcontext
815 if ctx is None:
816 return None
817 smgr = ctx.getServiceManager() # com.sun.star.lang.XMultiComponentFactory
818 DESK = 'com.sun.star.frame.Desktop'
819 desktop = smgr.createInstanceWithContext(DESK, ctx)
820 return desktop
821
822 starDesktop, stardesktop = StarDesktop, StarDesktop
823
824 @property
825 def ThisComponent(self):
826 """
827 When the current component is the Basic IDE, the ThisComponent object returns
828 in Basic the component owning the currently run user script.
829 Above behaviour cannot be reproduced in Python.
830 :return: the current component or None when not a document
831 """
832 comp = self.StarDesktop.getCurrentComponent()
833 if comp is None:
834 return None
835 impl = comp.ImplementationName
836 if impl in ('com.sun.star.comp.basic.BasicIDE', 'com.sun.star.comp.sfx2.BackingComp'):
837 return None # None when Basic IDE or welcome screen
838 return comp
839
840 thisComponent, thiscomponent = ThisComponent, ThisComponent
841
842 @property
844 """
845 When the current component is the Basic IDE, the ThisDatabaseDocument object returns
846 in Basic the database owning the currently run user script.
847 Above behaviour cannot be reproduced in Python.
848 :return: the current Base (main) component or None when not a Base document or one of its subcomponents
849 """
850 comp = self.ThisComponent # Get the current component
851 if comp is None:
852 return None
853 #
854 sess = CreateScriptService('Session')
855 impl, ident = '', ''
856 if sess.HasUnoProperty(comp, 'ImplementationName'):
857 impl = comp.ImplementationName
858 if sess.HasUnoProperty(comp, 'Identifier'):
859 ident = comp.Identifier
860 #
861 targetimpl = 'com.sun.star.comp.dba.ODatabaseDocument'
862 if impl == targetimpl: # The current component is the main Base window
863 return comp
864 # Identify resp. form, table/query, table/query in edit mode, report, relations diagram
865 if impl == 'SwXTextDocument' and ident == 'com.sun.star.sdb.FormDesign' \
866 or impl == 'org.openoffice.comp.dbu.ODatasourceBrowser' \
867 or impl in ('org.openoffice.comp.dbu.OTableDesign', 'org.openoffice.comp.dbu.OQuertDesign') \
868 or impl == 'SwXTextDocument' and ident == 'com.sun.star.sdb.TextReportDesign' \
869 or impl == 'org.openoffice.comp.dbu.ORelationDesign':
870 db = comp.ScriptContainer
871 if sess.HasUnoProperty(db, 'ImplementationName'):
872 if db.ImplementationName == targetimpl:
873 return db
874 return None
875
876 thisDatabaseDocument, thisdatabasedocument = ThisDatabaseDocument, ThisDatabaseDocument
877
878 @classmethod
879 def Xray(cls, unoobject = None):
880 return cls.SIMPLEEXEC('XrayTool._main.xray', unoobject)
881
882 # #########################################################################
883 # SF_Dictionary CLASS
884 # #########################################################################
886 """
887 The service adds to a Python dict instance the interfaces for conversion to and from
888 a list of UNO PropertyValues
889
890 Usage:
891 dico = dict(A = 1, B = 2, C = 3)
892 myDict = CreateScriptService('Dictionary', dico) # Initialize myDict with the content of dico
893 myDict['D'] = 4
894 print(myDict) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
895 propval = myDict.ConvertToPropertyValues()
896 or
897 dico = dict(A = 1, B = 2, C = 3)
898 myDict = CreateScriptService('Dictionary') # Initialize myDict as an empty dict object
899 myDict.update(dico) # Load the values of dico into myDict
900 myDict['D'] = 4
901 print(myDict) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
902 propval = myDict.ConvertToPropertyValues()
903 """
904 # Mandatory class properties for service registration
905 serviceimplementation = 'python'
906 servicename = 'ScriptForge.Dictionary'
907 servicesynonyms = ('dictionary', 'scriptforge.dictionary')
908
909 def __init__(self, dic = None):
910 SFServices.__init__(self)
911 dict.__init__(self)
912 if dic is not None:
913 self.update(dic)
914
916 """
917 Store the content of the dictionary in an array of PropertyValues.
918 Each entry in the array is a com.sun.star.beans.PropertyValue.
919 he key is stored in Name, the value is stored in Value.
920
921 If one of the items has a type datetime, it is converted to a com.sun.star.util.DateTime structure.
922 If one of the items is an empty list, it is converted to None.
923
924 The resulting array is empty when the dictionary is empty.
925 """
926 result = []
927 for key in iter(self):
928 value = self[key]
929 item = value
930 if isinstance(value, dict): # check that first level is not itself a (sub)dict
931 item = None
932 elif isinstance(value, (tuple, list)): # check every member of the list is not a (sub)dict
933 if len(value) == 0: # Property values do not like empty lists
934 value = None
935 else:
936 for i in range(len(value)):
937 if isinstance(value[i], dict):
938 value[i] = None
939 item = value
940 elif isinstance(value, (datetime.datetime, datetime.date, datetime.time)):
941 item = SFScriptForge.SF_Basic.CDateToUnoDateTime(value)
942 pv = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
943 pv.Name = key
944 pv.Value = item
945 result.append(pv)
946 return result
947
948 def ImportFromPropertyValues(self, propertyvalues, overwrite = False):
949 """
950 Inserts the contents of an array of PropertyValue objects into the current dictionary.
951 PropertyValue Names are used as keys in the dictionary, whereas Values contain the corresponding values.
952 Date-type values are converted to datetime.datetime instances.
953 :param propertyvalues: a list.tuple containing com.sun.star.beans.PropertyValue objects
954 :param overwrite: When True, entries with same name may exist in the dictionary and their values
955 are overwritten. When False (default), repeated keys are not overwritten.
956 :return: True when successful
957 """
958 result = []
959 for pv in iter(propertyvalues):
960 key = pv.Name
961 if overwrite is True or key not in self:
962 item = pv.Value
963 if 'com.sun.star.util.DateTime' in repr(type(item)):
964 item = datetime.datetime(item.Year, item.Month, item.Day,
965 item.Hours, item.Minutes, item.Seconds, int(item.NanoSeconds / 1000))
966 elif 'com.sun.star.util.Date' in repr(type(item)):
967 item = datetime.datetime(item.Year, item.Month, item.Day)
968 elif 'com.sun.star.util.Time' in repr(type(item)):
969 item = datetime.datetime(item.Hours, item.Minutes, item.Seconds, int(item.NanoSeconds / 1000))
970 result.append((key, item))
971 self.update(result)
972 return True
973
974 # #########################################################################
975 # SF_Exception CLASS
976 # #########################################################################
977 class SF_Exception(SFServices, metaclass = _Singleton):
978 """
979 The Exception service is a collection of methods for code debugging and error handling.
980
981 The Exception service console stores events, variable values and information about errors.
982 Use the console when the Python shell is not available, for example in Calc user defined functions (UDF)
983 or during events processing.
984 Use DebugPrint() method to aggregate additional user data of any type.
985
986 Console entries can be dumped to a text file or visualized in a dialogue.
987 """
988 # Mandatory class properties for service registration
989 serviceimplementation = 'basic'
990 servicename = 'ScriptForge.Exception'
991 servicesynonyms = ('exception', 'scriptforge.exception')
992 serviceproperties = dict()
993
994 def Console(self, modal = True):
995 # From Python, the current XComponentContext must be added as last argument
996 return self.ExecMethod(self.vbMethod, 'Console', modal, ScriptForge.componentcontext)
997
998 def ConsoleClear(self, keep = 0):
999 return self.ExecMethod(self.vbMethod, 'ConsoleClear', keep)
1000
1001 def ConsoleToFile(self, filename):
1002 return self.ExecMethod(self.vbMethod, 'ConsoleToFile', filename)
1003
1004 def DebugDisplay(self, *args):
1005 # Arguments are concatenated in a single string similar to what the Python print() function would produce
1006 self.DebugPrint(*args)
1007 param = '\n'.join(list(map(lambda a: a.strip("'") if isinstance(a, str) else repr(a), args)))
1008 bas = CreateScriptService('ScriptForge.Basic')
1009 return bas.MsgBox(param, bas.MB_OK + bas.MB_ICONINFORMATION, 'DebugDisplay')
1010
1011 def DebugPrint(self, *args):
1012 # Arguments are concatenated in a single string similar to what the Python print() function would produce
1013 # Avoid using repr() on strings to not have backslashes * 4
1014 param = '\t'.join(list(map(lambda a: a.strip("'") if isinstance(a, str) else repr(a),
1015 args))).expandtabs(tabsize = 4)
1016 return self.ExecMethod(self.vbMethod, 'DebugPrint', param)
1017
1018 @classmethod
1019 def PythonShell(cls, variables = None):
1020 """
1021 Open an APSO python shell window - Thanks to its authors Hanya/Tsutomu Uchino/Hubert Lambert
1022 :param variables: Typical use
1023 PythonShell.({**globals(), **locals()})
1024 to push the global and local dictionaries to the shell window
1025 """
1026 if variables is None:
1027 variables = locals()
1028 # Is APSO installed ?
1029 ctx = ScriptForge.componentcontext
1030 ext = ctx.getByName('/singletons/com.sun.star.deployment.PackageInformationProvider')
1031 apso = 'apso.python.script.organizer'
1032 if len(ext.getPackageLocation(apso)) > 0:
1033 # APSO is available. However, PythonShell() is ignored in bridge mode
1034 # because APSO library not in pythonpath
1035 if ScriptForge.port > 0:
1036 return None
1037 # Directly derived from apso.oxt|python|scripts|tools.py$console
1038 # we need to load apso before import statement
1039 ctx.ServiceManager.createInstance('apso.python.script.organizer.impl')
1040 # now we can use apso_utils library
1041 from apso_utils import console
1042 kwargs = {'loc': variables}
1043 kwargs['loc'].setdefault('XSCRIPTCONTEXT', uno)
1044 console(**kwargs)
1045 # An interprocess call is necessary to allow a redirection of STDOUT and STDERR by APSO
1046 # Choice is a minimalist call to a Basic routine: no arguments, a few lines of code
1047 SFScriptForge.SF_Basic.GetGuiType()
1048 else:
1049 # The APSO extension could not be located in your LibreOffice installation
1050 cls._RaiseFatal('SF_Exception.PythonShell', 'variables=None', 'PYTHONSHELLERROR')
1051
1052 @classmethod
1053 def RaiseFatal(cls, errorcode, *args):
1054 """
1055 Generate a run-time error caused by an anomaly in a user script detected by ScriptForge
1056 The message is logged in the console. The execution is STOPPED
1057 For INTERNAL USE only
1058 """
1059 # Direct call because RaiseFatal forces an execution stop in Basic
1060 if len(args) == 0:
1061 args = (None,)
1062 return cls.SIMPLEEXEC('@SF_Exception.RaiseFatal', (errorcode, *args)) # With ParamArray
1063
1064 @classmethod
1065 def _RaiseFatal(cls, sub, subargs, errorcode, *args):
1066 """
1067 Wrapper of RaiseFatal(). Includes method and syntax of the failed Python routine
1068 to simulate the exact behaviour of the Basic RaiseFatal() method
1069 For INTERNAL USE only
1070 """
1071 ScriptForge.InvokeSimpleScript('ScriptForge.SF_Utils._EnterFunction', sub, subargs)
1072 cls.RaiseFatal(errorcode, *args)
1073 raise RuntimeError("The execution of the method '" + sub.split('.')[-1] + "' failed. Execution stops.")
1074
1075 # #########################################################################
1076 # SF_FileSystem CLASS
1077 # #########################################################################
1078 class SF_FileSystem(SFServices, metaclass = _Singleton):
1079 """
1080 The "FileSystem" service includes common file and folder handling routines.
1081 """
1082 # Mandatory class properties for service registration
1083 serviceimplementation = 'basic'
1084 servicename = 'ScriptForge.FileSystem'
1085 servicesynonyms = ('filesystem', 'scriptforge.filesystem')
1086 serviceproperties = dict(FileNaming = True, ConfigFolder = False, ExtensionsFolder = False, HomeFolder = False,
1087 InstallFolder = False, TemplatesFolder = False, TemporaryFolder = False,
1088 UserTemplatesFolder = False)
1089 # Force for each property to get its value from Basic - due to FileNaming updatability
1090 forceGetProperty = True
1091 # Open TextStream constants
1092 ForReading, ForWriting, ForAppending = 1, 2, 8
1093
1094 def BuildPath(self, foldername, name):
1095 return self.ExecMethod(self.vbMethod, 'BuildPath', foldername, name)
1096
1097 def CompareFiles(self, filename1, filename2, comparecontents = False):
1098 py = ScriptForge.pythonhelpermodule + '$' + '_SF_FileSystem__CompareFiles'
1099 if self.FileExists(filename1) and self.FileExists(filename2):
1100 file1 = self._ConvertFromUrl(filename1)
1101 file2 = self._ConvertFromUrl(filename2)
1102 return self.SIMPLEEXEC(py, file1, file2, comparecontents)
1103 else:
1104 return False
1105
1106 def CopyFile(self, source, destination, overwrite = True):
1107 return self.ExecMethod(self.vbMethod, 'CopyFile', source, destination, overwrite)
1108
1109 def CopyFolder(self, source, destination, overwrite = True):
1110 return self.ExecMethod(self.vbMethod, 'CopyFolder', source, destination, overwrite)
1111
1112 def CreateFolder(self, foldername):
1113 return self.ExecMethod(self.vbMethod, 'CreateFolder', foldername)
1114
1115 def CreateTextFile(self, filename, overwrite = True, encoding = 'UTF-8'):
1116 return self.ExecMethod(self.vbMethod, 'CreateTextFile', filename, overwrite, encoding)
1117
1118 def DeleteFile(self, filename):
1119 return self.ExecMethod(self.vbMethod, 'DeleteFile', filename)
1120
1121 def DeleteFolder(self, foldername):
1122 return self.ExecMethod(self.vbMethod, 'DeleteFolder', foldername)
1123
1124 def ExtensionFolder(self, extension):
1125 return self.ExecMethod(self.vbMethod, 'ExtensionFolder', extension)
1126
1127 def FileExists(self, filename):
1128 return self.ExecMethod(self.vbMethod, 'FileExists', filename)
1129
1130 def Files(self, foldername, filter = '', includesubfolders = False):
1131 return self.ExecMethod(self.vbMethod, 'Files', foldername, filter, includesubfolders)
1132
1133 def FolderExists(self, foldername):
1134 return self.ExecMethod(self.vbMethod, 'FolderExists', foldername)
1135
1136 def GetBaseName(self, filename):
1137 return self.ExecMethod(self.vbMethod, 'GetBaseName', filename)
1138
1139 def GetExtension(self, filename):
1140 return self.ExecMethod(self.vbMethod, 'GetExtension', filename)
1141
1142 def GetFileLen(self, filename):
1143 py = ScriptForge.pythonhelpermodule + '$' + '_SF_FileSystem__GetFilelen'
1144 if self.FileExists(filename):
1145 file = self._ConvertFromUrl(filename)
1146 return int(self.SIMPLEEXEC(py, file))
1147 else:
1148 return 0
1149
1150 def GetFileModified(self, filename):
1151 return self.ExecMethod(self.vbMethod + self.flgDateRet, 'GetFileModified', filename)
1152
1153 def GetName(self, filename):
1154 return self.ExecMethod(self.vbMethod, 'GetName', filename)
1155
1156 def GetParentFolderName(self, filename):
1157 return self.ExecMethod(self.vbMethod, 'GetParentFolderName', filename)
1158
1159 def GetTempName(self, extension = ''):
1160 return self.ExecMethod(self.vbMethod, 'GetTempName', extension)
1161
1162 def HashFile(self, filename, algorithm):
1163 py = ScriptForge.pythonhelpermodule + '$' + '_SF_FileSystem__HashFile'
1164 if self.FileExists(filename):
1165 file = self._ConvertFromUrl(filename)
1166 return self.SIMPLEEXEC(py, file, algorithm.lower())
1167 else:
1168 return ''
1169
1170 def MoveFile(self, source, destination):
1171 return self.ExecMethod(self.vbMethod, 'MoveFile', source, destination)
1172
1173 def Normalize(self, filename):
1174 return self.ExecMethod(self.vbMethod, 'Normalize', filename)
1175
1176 def MoveFolder(self, source, destination):
1177 return self.ExecMethod(self.vbMethod, 'MoveFolder', source, destination)
1178
1179 def OpenTextFile(self, filename, iomode = 1, create = False, encoding = 'UTF-8'):
1180 return self.ExecMethod(self.vbMethod, 'OpenTextFile', filename, iomode, create, encoding)
1181
1182 def PickFile(self, defaultfile = ScriptForge.cstSymEmpty, mode = 'OPEN', filter = ''):
1183 return self.ExecMethod(self.vbMethod, 'PickFile', defaultfile, mode, filter)
1184
1185 def PickFolder(self, defaultfolder = ScriptForge.cstSymEmpty, freetext = ''):
1186 return self.ExecMethod(self.vbMethod, 'PickFolder', defaultfolder, freetext)
1187
1188 def SubFolders(self, foldername, filter = '', includesubfolders = False):
1189 return self.ExecMethod(self.vbMethod, 'SubFolders', foldername, filter, includesubfolders)
1190
1191 @classmethod
1192 def _ConvertFromUrl(cls, filename):
1193 # Alias for same function in FileSystem Basic module
1194 return cls.SIMPLEEXEC('ScriptForge.SF_FileSystem._ConvertFromUrl', filename)
1195
1196 # #########################################################################
1197 # SF_L10N CLASS
1198 # #########################################################################
1200 """
1201 This service provides a number of methods related to the translation of strings
1202 with minimal impact on the program's source code.
1203 The methods provided by the L10N service can be used mainly to:
1204 Create POT files that can be used as templates for translation of all strings in the program.
1205 Get translated strings at runtime for the language defined in the Locale property.
1206 """
1207 # Mandatory class properties for service registration
1208 serviceimplementation = 'basic'
1209 servicename = 'ScriptForge.L10N'
1210 servicesynonyms = ('l10n', 'scriptforge.l10n')
1211 serviceproperties = dict(Folder = False, Languages = False, Locale = False)
1212
1213 @classmethod
1214 def ReviewServiceArgs(cls, foldername = '', locale = '', encoding = 'UTF-8',
1215 locale2 = '', encoding2 = 'UTF-8'):
1216 """
1217 Transform positional and keyword arguments into positional only
1218 """
1219 return foldername, locale, encoding, locale2, encoding2
1220
1221 def AddText(self, context = '', msgid = '', comment = ''):
1222 return self.ExecMethod(self.vbMethod, 'AddText', context, msgid, comment)
1223
1224 def AddTextsFromDialog(self, dialog):
1225 dialogobj = dialog.objectreference if isinstance(dialog, SFDialogs.SF_Dialog) else dialog
1226 return self.ExecMethod(self.vbMethod + self.flgObject, 'AddTextsFromDialog', dialogobj)
1227
1228 def ExportToPOTFile(self, filename, header = '', encoding = 'UTF-8'):
1229 return self.ExecMethod(self.vbMethod, 'ExportToPOTFile', filename, header, encoding)
1230
1231 def GetText(self, msgid, *args):
1232 return self.ExecMethod(self.vbMethod, 'GetText', msgid, *args)
1233
1234 _ = GetText
1235
1236 # #########################################################################
1237 # SF_Platform CLASS
1238 # #########################################################################
1239 class SF_Platform(SFServices, metaclass = _Singleton):
1240 """
1241 The 'Platform' service implements a collection of properties about the actual execution environment
1242 and context :
1243 the hardware platform
1244 the operating system
1245 the LibreOffice version
1246 the current user
1247 All those properties are read-only.
1248 The implementation is mainly based on the 'platform' module of the Python standard library
1249 """
1250 # Mandatory class properties for service registration
1251 serviceimplementation = 'basic'
1252 servicename = 'ScriptForge.Platform'
1253 servicesynonyms = ('platform', 'scriptforge.platform')
1254 serviceproperties = dict(Architecture = False, ComputerName = False, CPUCount = False, CurrentUser = False,
1255 Extensions = False, FilterNames = False, Fonts = False, FormatLocale = False,
1256 Locale = False, Machine = False, OfficeLocale = False, OfficeVersion = False,
1257 OSName = False, OSPlatform = False, OSRelease = False, OSVersion = False,
1258 Printers = False, Processor = False, PythonVersion = False, SystemLocale = False,
1259 UserData = False)
1260 # Python helper functions
1261 py = ScriptForge.pythonhelpermodule + '$' + '_SF_Platform'
1262
1263 @property
1264 def Architecture(self):
1265 return self.SIMPLEEXEC(self.py, 'Architecture')
1266
1267 @property
1268 def ComputerName(self):
1269 return self.SIMPLEEXEC(self.py, 'ComputerName')
1270
1271 @property
1272 def CPUCount(self):
1273 return self.SIMPLEEXEC(self.py, 'CPUCount')
1274
1275 @property
1276 def CurrentUser(self):
1277 return self.SIMPLEEXEC(self.py, 'CurrentUser')
1278
1279 @property
1280 def Machine(self):
1281 return self.SIMPLEEXEC(self.py, 'Machine')
1282
1283 @property
1284 def OSName(self):
1285 return self.SIMPLEEXEC(self.py, 'OSName')
1286
1287 @property
1288 def OSPlatform(self):
1289 return self.SIMPLEEXEC(self.py, 'OSPlatform')
1290
1291 @property
1292 def OSRelease(self):
1293 return self.SIMPLEEXEC(self.py, 'OSRelease')
1294
1295 @property
1296 def OSVersion(self):
1297 return self.SIMPLEEXEC(self.py, 'OSVersion')
1298
1299 @property
1300 def Processor(self):
1301 return self.SIMPLEEXEC(self.py, 'Processor')
1302
1303 @property
1304 def PythonVersion(self):
1305 return self.SIMPLEEXEC(self.py, 'PythonVersion')
1306
1307 @property
1308 def UserData(self):
1309 props = self.GetProperty('UserData') # is an array of property values
1310 if len(props) == 0:
1311 return dict()
1312 dico = CreateScriptService('Dictionary')
1313 dico.ImportFromPropertyValues(props, overwrite = True)
1314 return dico
1315
1316 # #########################################################################
1317 # SF_Region CLASS
1318 # #########################################################################
1319 class SF_Region(SFServices, metaclass = _Singleton):
1320 """
1321 The "Region" service gathers a collection of functions about languages, countries and timezones
1322 - Locales
1323 - Currencies
1324 - Numbers and dates formatting
1325 - Calendars
1326 - Timezones conversions
1327 - Numbers transformed to text
1328 """
1329 # Mandatory class properties for service registration
1330 serviceimplementation = 'basic'
1331 servicename = 'ScriptForge.Region'
1332 servicesynonyms = ('region', 'scriptforge.region')
1333 serviceproperties = dict()
1334
1335 # Next functions are implemented in Basic as read-only properties with 1 argument
1336 def Country(self, region = ''):
1337 return self.GetProperty('Country', region)
1338
1339 def Currency(self, region = ''):
1340 return self.GetProperty('Currency', region)
1341
1342 def DatePatterns(self, region = ''):
1343 return self.GetProperty('DatePatterns', region)
1344
1345 def DateSeparator(self, region = ''):
1346 return self.GetProperty('DateSeparator', region)
1347
1348 def DayAbbrevNames(self, region = ''):
1349 return self.GetProperty('DayAbbrevNames', region)
1350
1351 def DayNames(self, region = ''):
1352 return self.GetProperty('DayNames', region)
1353
1354 def DayNarrowNames(self, region = ''):
1355 return self.GetProperty('DayNarrowNames', region)
1356
1357 def DecimalPoint(self, region = ''):
1358 return self.GetProperty('DecimalPoint', region)
1359
1360 def Language(self, region = ''):
1361 return self.GetProperty('Language', region)
1362
1363 def ListSeparator(self, region = ''):
1364 return self.GetProperty('ListSeparator', region)
1365
1366 def MonthAbbrevNames(self, region = ''):
1367 return self.GetProperty('MonthAbbrevNames', region)
1368
1369 def MonthNames(self, region = ''):
1370 return self.GetProperty('MonthNames', region)
1371
1372 def MonthNarrowNames(self, region = ''):
1373 return self.GetProperty('MonthNarrowNames', region)
1374
1375 def ThousandSeparator(self, region = ''):
1376 return self.GetProperty('ThousandSeparator', region)
1377
1378 def TimeSeparator(self, region = ''):
1379 return self.GetProperty('TimeSeparator', region)
1380
1381 # Usual methods
1382 def DSTOffset(self, localdatetime, timezone, locale = ''):
1383 if isinstance(localdatetime, datetime.datetime):
1384 localdatetime = SFScriptForge.SF_Basic.CDateToUnoDateTime(localdatetime)
1385 return self.ExecMethod(self.vbMethod + self.flgDateArg, 'DSTOffset', localdatetime, timezone, locale)
1386
1387 def LocalDateTime(self, utcdatetime, timezone, locale = ''):
1388 if isinstance(utcdatetime, datetime.datetime):
1389 utcdatetime = SFScriptForge.SF_Basic.CDateToUnoDateTime(utcdatetime)
1390 localdate = self.ExecMethod(self.vbMethod + self.flgDateArg + self.flgDateRet, 'LocalDateTime',
1391 utcdatetime, timezone, locale)
1392 return SFScriptForge.SF_Basic.CDateFromUnoDateTime(localdate)
1393
1394 def Number2Text(self, number, locale = ''):
1395 return self.ExecMethod(self.vbMethod, 'Number2Text', number, locale)
1396
1397 def TimeZoneOffset(self, timezone, locale = ''):
1398 return self.ExecMethod(self.vbMethod, 'TimeZoneOffset', timezone, locale)
1399
1400 def UTCDateTime(self, localdatetime, timezone, locale = ''):
1401 if isinstance(localdatetime, datetime.datetime):
1402 localdatetime = SFScriptForge.SF_Basic.CDateToUnoDateTime(localdatetime)
1403 utcdate = self.ExecMethod(self.vbMethod + self.flgDateArg + self.flgDateRet, 'UTCDateTime', localdatetime,
1404 timezone, locale)
1405 return SFScriptForge.SF_Basic.CDateFromUnoDateTime(utcdate)
1406
1407 def UTCNow(self, timezone, locale = ''):
1408 now = self.ExecMethod(self.vbMethod + self.flgDateRet, 'UTCNow', timezone, locale)
1409 return SFScriptForge.SF_Basic.CDateFromUnoDateTime(now)
1410
1411 # #########################################################################
1412 # SF_Session CLASS
1413 # #########################################################################
1414 class SF_Session(SFServices, metaclass = _Singleton):
1415 """
1416 The Session service gathers various general-purpose methods about:
1417 - UNO introspection
1418 - the invocation of external scripts or programs
1419 """
1420 # Mandatory class properties for service registration
1421 serviceimplementation = 'basic'
1422 servicename = 'ScriptForge.Session'
1423 servicesynonyms = ('session', 'scriptforge.session')
1424 serviceproperties = dict()
1425
1426 # Class constants Where to find an invoked library ?
1427 SCRIPTISEMBEDDED = 'document' # in the document
1428 SCRIPTISAPPLICATION = 'application' # in any shared library (Basic)
1429 SCRIPTISPERSONAL = 'user' # in My Macros (Python)
1430 SCRIPTISPERSOXT = 'user:uno_packages' # in an extension installed for the current user (Python)
1431 SCRIPTISSHARED = 'share' # in LibreOffice macros (Python)
1432 SCRIPTISSHAROXT = 'share:uno_packages' # in an extension installed for all users (Python)
1433 SCRIPTISOXT = 'uno_packages' # in an extension but the installation parameters are unknown (Python)
1434
1435 @classmethod
1436 def ExecuteBasicScript(cls, scope = '', script = '', *args):
1437 if scope is None or scope == '':
1438 scope = cls.SCRIPTISAPPLICATION
1439 if len(args) == 0:
1440 args = (scope,) + (script,) + (None,)
1441 else:
1442 args = (scope,) + (script,) + args
1443 # ExecuteBasicScript method has a ParamArray parameter in Basic
1444 return cls.SIMPLEEXEC('@SF_Session.ExecuteBasicScript', args)
1445
1446 @classmethod
1447 def ExecuteCalcFunction(cls, calcfunction, *args):
1448 if len(args) == 0:
1449 # Arguments of Calc functions are strings or numbers. None == Empty is a good alias for no argument
1450 args = (calcfunction,) + (None,)
1451 else:
1452 args = (calcfunction,) + args
1453 # ExecuteCalcFunction method has a ParamArray parameter in Basic
1454 return cls.SIMPLEEXEC('@SF_Session.ExecuteCalcFunction', args)
1455
1456 @classmethod
1457 def ExecutePythonScript(cls, scope = '', script = '', *args):
1458 return cls.SIMPLEEXEC(scope + '#' + script, *args)
1459
1460 def HasUnoMethod(self, unoobject, methodname):
1461 return self.ExecMethod(self.vbMethod, 'HasUnoMethod', unoobject, methodname)
1462
1463 def HasUnoProperty(self, unoobject, propertyname):
1464 return self.ExecMethod(self.vbMethod, 'HasUnoProperty', unoobject, propertyname)
1465
1466 @classmethod
1467 def OpenURLInBrowser(cls, url):
1468 py = ScriptForge.pythonhelpermodule + '$' + '_SF_Session__OpenURLInBrowser'
1469 return cls.SIMPLEEXEC(py, url)
1470
1471 def RunApplication(self, command, parameters):
1472 return self.ExecMethod(self.vbMethod, 'RunApplication', command, parameters)
1473
1474 def SendMail(self, recipient, cc = '', bcc = '', subject = '', body = '', filenames = '', editmessage = True):
1475 return self.ExecMethod(self.vbMethod, 'SendMail', recipient, cc, bcc, subject, body, filenames, editmessage)
1476
1477 def UnoObjectType(self, unoobject):
1478 return self.ExecMethod(self.vbMethod, 'UnoObjectType', unoobject)
1479
1480 def UnoMethods(self, unoobject):
1481 return self.ExecMethod(self.vbMethod, 'UnoMethods', unoobject)
1482
1483 def UnoProperties(self, unoobject):
1484 return self.ExecMethod(self.vbMethod, 'UnoProperties', unoobject)
1485
1486 def WebService(self, uri):
1487 return self.ExecMethod(self.vbMethod, 'WebService', uri)
1488
1489 # #########################################################################
1490 # SF_String CLASS
1491 # #########################################################################
1492 class SF_String(SFServices, metaclass = _Singleton):
1493 """
1494 Focus on string manipulation, regular expressions, encodings and hashing algorithms.
1495 The methods implemented in Basic that are redundant with Python builtin functions
1496 are not duplicated
1497 """
1498 # Mandatory class properties for service registration
1499 serviceimplementation = 'basic'
1500 servicename = 'ScriptForge.String'
1501 servicesynonyms = ('string', 'scriptforge.string')
1502 serviceproperties = dict()
1503
1504 @classmethod
1505 def HashStr(cls, inputstr, algorithm):
1506 py = ScriptForge.pythonhelpermodule + '$' + '_SF_String__HashStr'
1507 return cls.SIMPLEEXEC(py, inputstr, algorithm.lower())
1508
1509 def IsADate(self, inputstr, dateformat = 'YYYY-MM-DD'):
1510 return self.ExecMethod(self.vbMethod, 'IsADate', inputstr, dateformat)
1511
1512 def IsEmail(self, inputstr):
1513 return self.ExecMethod(self.vbMethod, 'IsEmail', inputstr)
1514
1515 def IsFileName(self, inputstr, osname = ScriptForge.cstSymEmpty):
1516 return self.ExecMethod(self.vbMethod, 'IsFileName', inputstr, osname)
1517
1518 def IsIBAN(self, inputstr):
1519 return self.ExecMethod(self.vbMethod, 'IsIBAN', inputstr)
1520
1521 def IsIPv4(self, inputstr):
1522 return self.ExecMethod(self.vbMethod, 'IsIPv4', inputstr)
1523
1524 def IsLike(self, inputstr, pattern, casesensitive = False):
1525 return self.ExecMethod(self.vbMethod, 'IsLike', inputstr, pattern, casesensitive)
1526
1527 def IsSheetName(self, inputstr):
1528 return self.ExecMethod(self.vbMethod, 'IsSheetName', inputstr)
1529
1530 def IsUrl(self, inputstr):
1531 return self.ExecMethod(self.vbMethod, 'IsUrl', inputstr)
1532
1533 def SplitNotQuoted(self, inputstr, delimiter = ' ', occurrences = 0, quotechar = '"'):
1534 return self.ExecMethod(self.vbMethod, 'SplitNotQuoted', inputstr, delimiter, occurrences, quotechar)
1535
1536 def Wrap(self, inputstr, width = 70, tabsize = 8):
1537 return self.ExecMethod(self.vbMethod, 'Wrap', inputstr, width, tabsize)
1538
1539 # #########################################################################
1540 # SF_TextStream CLASS
1541 # #########################################################################
1543 """
1544 The TextStream service is used to sequentially read from and write to files opened or created
1545 using the ScriptForge.FileSystem service..
1546 """
1547 # Mandatory class properties for service registration
1548 serviceimplementation = 'basic'
1549 servicename = 'ScriptForge.TextStream'
1550 servicesynonyms = ()
1551 serviceproperties = dict(AtEndOfStream = False, Encoding = False, FileName = False, IOMode = False,
1552 Line = False, NewLine = True)
1553
1554 @property
1555 def AtEndOfStream(self):
1556 return self.GetProperty('AtEndOfStream')
1557
1558 atEndOfStream, atendofstream = AtEndOfStream, AtEndOfStream
1559
1560 @property
1561 def Line(self):
1562 return self.GetProperty('Line')
1563
1564 line = Line
1565
1566 def CloseFile(self):
1567 return self.ExecMethod(self.vbMethod, 'CloseFile')
1568
1569 def ReadAll(self):
1570 return self.ExecMethod(self.vbMethod, 'ReadAll')
1571
1572 def ReadLine(self):
1573 return self.ExecMethod(self.vbMethod, 'ReadLine')
1574
1575 def SkipLine(self):
1576 return self.ExecMethod(self.vbMethod, 'SkipLine')
1577
1578 def WriteBlankLines(self, lines):
1579 return self.ExecMethod(self.vbMethod, 'WriteBlankLines', lines)
1580
1581 def WriteLine(self, line):
1582 return self.ExecMethod(self.vbMethod, 'WriteLine', line)
1583
1584 # #########################################################################
1585 # SF_Timer CLASS
1586 # #########################################################################
1588 """
1589 The "Timer" service measures the amount of time it takes to run user scripts.
1590 """
1591 # Mandatory class properties for service registration
1592 serviceimplementation = 'basic'
1593 servicename = 'ScriptForge.Timer'
1594 servicesynonyms = ('timer', 'scriptforge.timer')
1595 serviceproperties = dict(Duration = False, IsStarted = False, IsSuspended = False,
1596 SuspendDuration = False, TotalDuration = False)
1597 # Force for each property to get its value from Basic
1598 forceGetProperty = True
1599
1600 @classmethod
1601 def ReviewServiceArgs(cls, start = False):
1602 """
1603 Transform positional and keyword arguments into positional only
1604 """
1605 return (start,)
1606
1607 def Continue(self):
1608 return self.ExecMethod(self.vbMethod, 'Continue')
1609
1610 def Restart(self):
1611 return self.ExecMethod(self.vbMethod, 'Restart')
1612
1613 def Start(self):
1614 return self.ExecMethod(self.vbMethod, 'Start')
1615
1616 def Suspend(self):
1617 return self.ExecMethod(self.vbMethod, 'Suspend')
1618
1619 def Terminate(self):
1620 return self.ExecMethod(self.vbMethod, 'Terminate')
1621
1622 # #########################################################################
1623 # SF_UI CLASS
1624 # #########################################################################
1625 class SF_UI(SFServices, metaclass = _Singleton):
1626 """
1627 Singleton class for the identification and the manipulation of the
1628 different windows composing the whole LibreOffice application:
1629 - Windows selection
1630 - Windows moving and resizing
1631 - Statusbar settings
1632 - Creation of new windows
1633 - Access to the underlying "documents"
1634 """
1635 # Mandatory class properties for service registration
1636 serviceimplementation = 'basic'
1637 servicename = 'ScriptForge.UI'
1638 servicesynonyms = ('ui', 'scriptforge.ui')
1639 serviceproperties = dict(ActiveWindow = False, Height = False, Width = False, X = False, Y = False)
1640
1641 # Class constants
1642 MACROEXECALWAYS, MACROEXECNEVER, MACROEXECNORMAL = 2, 1, 0
1643 BASEDOCUMENT, CALCDOCUMENT, DRAWDOCUMENT, IMPRESSDOCUMENT, MATHDOCUMENT, WRITERDOCUMENT = \
1644 'Base', 'Calc', 'Draw', 'Impress', 'Math', 'Writer'
1645
1646 @property
1647 def ActiveWindow(self):
1648 return self.ExecMethod(self.vbMethod, 'ActiveWindow')
1649
1650 activeWindow, activewindow = ActiveWindow, ActiveWindow
1651
1652 def Activate(self, windowname = ''):
1653 return self.ExecMethod(self.vbMethod, 'Activate', windowname)
1654
1655 def CreateBaseDocument(self, filename, embeddeddatabase = 'HSQLDB', registrationname = '', calcfilename = ''):
1656 return self.ExecMethod(self.vbMethod, 'CreateBaseDocument', filename, embeddeddatabase, registrationname,
1657 calcfilename)
1658
1659 def CreateDocument(self, documenttype = '', templatefile = '', hidden = False):
1660 return self.ExecMethod(self.vbMethod, 'CreateDocument', documenttype, templatefile, hidden)
1661
1662 def Documents(self):
1663 return self.ExecMethod(self.vbMethod, 'Documents')
1664
1665 def GetDocument(self, windowname = ''):
1666 return self.ExecMethod(self.vbMethod, 'GetDocument', windowname)
1667
1668 def Maximize(self, windowname = ''):
1669 return self.ExecMethod(self.vbMethod, 'Maximize', windowname)
1670
1671 def Minimize(self, windowname = ''):
1672 return self.ExecMethod(self.vbMethod, 'Minimize', windowname)
1673
1674 def OpenBaseDocument(self, filename = '', registrationname = '', macroexecution = MACROEXECNORMAL):
1675 return self.ExecMethod(self.vbMethod, 'OpenBaseDocument', filename, registrationname, macroexecution)
1676
1677 def OpenDocument(self, filename, password = '', readonly = False, hidden = False,
1678 macroexecution = MACROEXECNORMAL, filtername = '', filteroptions = ''):
1679 return self.ExecMethod(self.vbMethod, 'OpenDocument', filename, password, readonly, hidden,
1680 macroexecution, filtername, filteroptions)
1681
1682 def Resize(self, left = -1, top = -1, width = -1, height = -1):
1683 return self.ExecMethod(self.vbMethod, 'Resize', left, top, width, height)
1684
1685 def RunCommand(self, command, *args, **kwargs):
1686 params = tuple(list(args) + ScriptForge.unpack_args(kwargs))
1687 if len(params) == 0:
1688 params = (command,) + (None,)
1689 else:
1690 params = (command,) + params
1691 return self.SIMPLEEXEC('@SF_UI.RunCommand', params)
1692
1693 def SetStatusbar(self, text = '', percentage = -1):
1694 return self.ExecMethod(self.vbMethod, 'SetStatusbar', text, percentage)
1695
1696 def ShowProgressBar(self, title = '', text = '', percentage = -1):
1697 # From Python, the current XComponentContext must be added as last argument
1698 return self.ExecMethod(self.vbMethod, 'ShowProgressBar', title, text, percentage,
1699 ScriptForge.componentcontext)
1700
1701 def WindowExists(self, windowname):
1702 return self.ExecMethod(self.vbMethod, 'WindowExists', windowname)
1703
1704
1705# #####################################################################################################################
1706# SFDatabases CLASS (alias of SFDatabases Basic library) ###
1707# #####################################################################################################################
1709 """
1710 The SFDatabases class manages databases embedded in or connected to Base documents
1711 """
1712 pass
1713
1714 # #########################################################################
1715 # SF_Database CLASS
1716 # #########################################################################
1718 """
1719 Each instance of the current class represents a single database, with essentially its tables, queries
1720 and data
1721 The exchanges with the database are done in SQL only.
1722 To make them more readable, use optionally square brackets to surround table/query/field names
1723 instead of the (RDBMS-dependent) normal surrounding character.
1724 SQL statements may be run in direct or indirect mode. In direct mode the statement is transferred literally
1725 without syntax checking nor review to the database engine.
1726 """
1727 # Mandatory class properties for service registration
1728 serviceimplementation = 'basic'
1729 servicename = 'SFDatabases.Database'
1730 servicesynonyms = ('database', 'sfdatabases.database')
1731 serviceproperties = dict(Queries = False, Tables = False, XConnection = False, XMetaData = False)
1732
1733 @classmethod
1734 def ReviewServiceArgs(cls, filename = '', registrationname = '', readonly = True, user = '', password = ''):
1735 """
1736 Transform positional and keyword arguments into positional only
1737 """
1738 return filename, registrationname, readonly, user, password
1739
1740 def CloseDatabase(self):
1741 return self.ExecMethod(self.vbMethod, 'CloseDatabase')
1742
1743 def DAvg(self, expression, tablename, criteria = ''):
1744 return self.ExecMethod(self.vbMethod, 'DAvg', expression, tablename, criteria)
1745
1746 def DCount(self, expression, tablename, criteria = ''):
1747 return self.ExecMethod(self.vbMethod, 'DCount', expression, tablename, criteria)
1748
1749 def DLookup(self, expression, tablename, criteria = '', orderclause = ''):
1750 return self.ExecMethod(self.vbMethod, 'DLookup', expression, tablename, criteria, orderclause)
1751
1752 def DMax(self, expression, tablename, criteria = ''):
1753 return self.ExecMethod(self.vbMethod, 'DMax', expression, tablename, criteria)
1754
1755 def DMin(self, expression, tablename, criteria = ''):
1756 return self.ExecMethod(self.vbMethod, 'DMin', expression, tablename, criteria)
1757
1758 def DSum(self, expression, tablename, criteria = ''):
1759 return self.ExecMethod(self.vbMethod, 'DSum', expression, tablename, criteria)
1760
1761 def GetRows(self, sqlcommand, directsql = False, header = False, maxrows = 0):
1762 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'GetRows', sqlcommand, directsql, header, maxrows)
1763
1764 def OpenFormDocument(self, formdocument):
1765 return self.ExecMethod(self.vbMethod, 'OpenFormDocument', formdocument)
1766
1767 def OpenQuery(self, queryname):
1768 return self.ExecMethod(self.vbMethod, 'OpenQuery', queryname)
1769
1770 def OpenSql(self, sql, directsql = False):
1771 return self.ExecMethod(self.vbMethod, 'OpenSql', sql, directsql)
1772
1773 def OpenTable(self, tablename):
1774 return self.ExecMethod(self.vbMethod, 'OpenTable', tablename)
1775
1776 def RunSql(self, sqlcommand, directsql = False):
1777 return self.ExecMethod(self.vbMethod, 'RunSql', sqlcommand, directsql)
1778
1779 # #########################################################################
1780 # SF_Datasheet CLASS
1781 # #########################################################################
1783 """
1784 A datasheet is the visual representation of tabular data produced by a database.
1785 A datasheet may be opened automatically by script code at any moment.
1786 The Base document owning the data may or may not be opened.
1787 Any SELECT SQL statement may trigger the datasheet display.
1788 """
1789 # Mandatory class properties for service registration
1790 serviceimplementation = 'basic'
1791 servicename = 'SFDatabases.Datasheet'
1792 servicesynonyms = ('datasheet', 'sfdatabases.datasheet')
1793 serviceproperties = dict(ColumnHeaders = False, CurrentColumn = False, CurrentRow = False,
1794 DatabaseFileName = False, Filter = True, LastRow = False, OrderBy = True,
1795 ParentDatabase = False, Source = False, SourceType = False, XComponent = False,
1796 XControlModel = False, XTabControllerModel = False)
1797
1798 def Activate(self):
1799 return self.ExecMethod(self.vbMethod, 'Activate')
1800
1802 return self.ExecMethod(self.vbMethod, 'CloseDatasheet')
1803
1804 def CreateMenu(self, menuheader, before = '', submenuchar = '>'):
1805 return self.ExecMethod(self.vbMethod, 'CreateMenu', menuheader, before, submenuchar)
1806
1807 def GetText(self, column = 0):
1808 return self.ExecMethod(self.vbMethod, 'GetText', column)
1809
1810 def GetValue(self, column = 0):
1811 return self.ExecMethod(self.vbMethod, 'GetValue', column)
1812
1813 def GoToCell(self, row = 0, column = 0):
1814 return self.ExecMethod(self.vbMethod, 'GoToCell', row, column)
1815
1816 def RemoveMenu(self, menuheader):
1817 return self.ExecMethod(self.vbMethod, 'RemoveMenu', menuheader)
1818
1819 def Toolbars(self, toolbarname = ''):
1820 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'Toolbars', toolbarname)
1821
1822
1823# #####################################################################################################################
1824# SFDialogs CLASS (alias of SFDialogs Basic library) ###
1825# #####################################################################################################################
1827 """
1828 The SFDialogs class manages dialogs defined with the Basic IDE
1829 """
1830 pass
1831
1832 # #########################################################################
1833 # SF_Dialog CLASS
1834 # #########################################################################
1836 """
1837 Each instance of the current class represents a single dialog box displayed to the user.
1838 The dialog box must have been designed and defined with the Basic IDE previously.
1839 From a Python script, a dialog box can be displayed in modal or in non-modal modes.
1840
1841 In modal mode, the box is displayed and the execution of the macro process is suspended
1842 until one of the OK or Cancel buttons is pressed. In the meantime, other user actions
1843 executed on the box can trigger specific actions.
1844
1845 In non-modal mode, the floating dialog remains displayed until the dialog is terminated
1846 by code (Terminate()) or until the LibreOffice application stops.
1847 """
1848 # Mandatory class properties for service registration
1849 serviceimplementation = 'basic'
1850 servicename = 'SFDialogs.Dialog'
1851 servicesynonyms = ('dialog', 'sfdialogs.dialog')
1852 serviceproperties = dict(Caption = True, Height = True, Modal = False, Name = False,
1853 OnFocusGained = True, OnFocusLost = True, OnKeyPressed = True,
1854 OnKeyReleased = True, OnMouseDragged = True, OnMouseEntered = True,
1855 OnMouseExited = True, OnMouseMoved = True, OnMousePressed = True,
1856 OnMouseReleased = True,
1857 Page = True, Visible = True, Width = True, XDialogModel = False, XDialogView = False)
1858 # Class constants used together with the Execute() method
1859 OKBUTTON, CANCELBUTTON = 1, 0
1860
1861 @classmethod
1862 def ReviewServiceArgs(cls, container = '', library = 'Standard', dialogname = ''):
1863 """
1864 Transform positional and keyword arguments into positional only
1865 Add the XComponentContext as last argument
1866 """
1867 return container, library, dialogname, ScriptForge.componentcontext
1868
1869 # Methods potentially executed while the dialog is in execution require the flgHardCode flag
1870 def Activate(self):
1871 return self.ExecMethod(self.vbMethod + self.flgHardCode, 'Activate')
1872
1873 def Center(self, parent = ScriptForge.cstSymMissing):
1876 parentobj = parent.objectreference if isinstance(parent, parentclasses) else parent
1877 return self.ExecMethod(self.vbMethod + self.flgObject + self.flgHardCode, 'Center', parentobj)
1878
1879 def CloneControl(self, sourcename, controlname, left = 1, top = 1):
1880 return self.ExecMethod(self.vbMethod, 'CloneControl', sourcename, controlname, left, top)
1881
1882 def Controls(self, controlname = ''):
1883 return self.ExecMethod(self.vbMethod + self.flgArrayRet + self.flgHardCode, 'Controls', controlname)
1884
1885 def CreateButton(self, controlname, place, toggle = False, push = ''):
1886 return self.ExecMethod(self.vbMethod, 'CreateButton', controlname, place, toggle, push)
1887
1888 def CreateCheckBox(self, controlname, place, multiline = False):
1889 return self.ExecMethod(self.vbMethod, 'CreateCheckBox', controlname, place, multiline)
1890
1891 def CreateComboBox(self, controlname, place, border = '3D', dropdown = True, linecount = 5):
1892 return self.ExecMethod(self.vbMethod, 'CreateComboBox', controlname, place, border, dropdown, linecount)
1893
1894 def CreateCurrencyField(self, controlname, place, border = '3D', spinbutton = False, minvalue = -1000000,
1895 maxvalue = +1000000, increment = 1, accuracy = 2):
1896 return self.ExecMethod(self.vbMethod, 'CreateCurrencyField', controlname, place, border, spinbutton,
1897 minvalue, maxvalue, increment, accuracy)
1898
1899 def CreateDateField(self, controlname, place, border = '3D', dropdown = True,
1900 mindate = datetime.datetime(1900, 1, 1, 0, 0, 0, 0),
1901 maxdate = datetime.datetime(2200, 12, 31, 0, 0, 0, 0)):
1902 if isinstance(mindate, datetime.datetime):
1903 mindate = SFScriptForge.SF_Basic.CDateToUnoDateTime(mindate)
1904 if isinstance(maxdate, datetime.datetime):
1905 maxdate = SFScriptForge.SF_Basic.CDateToUnoDateTime(maxdate)
1906 return self.ExecMethod(self.vbMethod + self.flgDateArg, 'CreateDateField', controlname, place, border,
1907 dropdown, mindate, maxdate)
1908
1909 def CreateFileControl(self, controlname, place, border = '3D'):
1910 return self.ExecMethod(self.vbMethod, 'CreateFileControl', controlname, place, border)
1911
1912 def CreateFixedLine(self, controlname, place, orientation):
1913 return self.ExecMethod(self.vbMethod, 'CreateFixedLine', controlname, place, orientation)
1914
1915 def CreateFixedText(self, controlname, place, border = 'NONE', multiline = False, align = 'LEFT',
1916 verticalalign = 'TOP'):
1917 return self.ExecMethod(self.vbMethod, 'CreateFixedText', controlname, place, border, multiline, align,
1918 verticalalign)
1919
1920 def CreateFormattedField(self, controlname, place, border = '3D', spinbutton = False,
1921 minvalue = -1000000, maxvalue = +1000000):
1922 return self.ExecMethod(self.vbMethod, 'CreateFormattedField', controlname, place, border, spinbutton,
1923 minvalue, maxvalue)
1924
1925 def CreateGroupBox(self, controlname, place):
1926 return self.ExecMethod(self.vbMethod, 'CreateGroupBox', controlname, place)
1927
1928 def CreateHyperlink(self, controlname, place, border = 'NONE', multiline = False, align = 'LEFT',
1929 verticalalign = 'TOP'):
1930 return self.ExecMethod(self.vbMethod, 'CreateHyperlink', controlname, place, border, multiline, align,
1931 verticalalign)
1932
1933 def CreateImageControl(self, controlname, place, border = '3D', scale = 'FITTOSIZE'):
1934 return self.ExecMethod(self.vbMethod, 'CreateImageControl', controlname, place, border, scale)
1935
1936 def CreateListBox(self, controlname, place, border = '3D', dropdown = True, linecount = 5,
1937 multiselect = False):
1938 return self.ExecMethod(self.vbMethod, 'CreateListBox', controlname, place, border, dropdown,
1939 linecount, multiselect)
1940
1941 def CreateNumericField(self, controlname, place, border = '3D', spinbutton = False,
1942 minvalue = -1000000, maxvalue = +1000000, increment = 1, accuracy = 2):
1943 return self.ExecMethod(self.vbMethod, 'CreateNumericField', controlname, place, border, spinbutton,
1944 minvalue, maxvalue, increment, accuracy)
1945
1946 def CreatePatternField(self, controlname, place, border = '3D', editmask = '', literalmask = ''):
1947 return self.ExecMethod(self.vbMethod, 'CreatePatternField', controlname, place, border,
1948 editmask, literalmask)
1949
1950 def CreateProgressBar(self, controlname, place, border = '3D', minvalue = 0, maxvalue = 100):
1951 return self.ExecMethod(self.vbMethod, 'CreateProgressBar', controlname, place, border, minvalue, maxvalue)
1952
1953 def CreateRadioButton(self, controlname, place, multiline = False):
1954 return self.ExecMethod(self.vbMethod, 'CreateRadioButton', controlname, place, multiline)
1955
1956 def CreateScrollBar(self, controlname, place, orientation, border = '3D', minvalue = 0, maxvalue = 100):
1957 return self.ExecMethod(self.vbMethod, 'CreateScrollBar', controlname, place, orientation, border,
1958 minvalue, maxvalue)
1959
1960 def CreateTableControl(self, controlname, place, border = '3D', rowheaders = True, columnheaders = True,
1961 scrollbars = 'None', gridlines = False):
1962 return self.ExecMethod(self.vbMethod, 'CreateTableControl', controlname, place, border,
1963 rowheaders, columnheaders, scrollbars, gridlines)
1964
1965 def CreateTextField(self, controlname, place, border = '3D', multiline = False,
1966 maximumlength = 0, passwordcharacter = ''):
1967 return self.ExecMethod(self.vbMethod, 'CreateTextField', controlname, place, border,
1968 multiline, maximumlength, passwordcharacter)
1969
1970 def CreateTimeField(self, controlname, place, border = '3D',
1971 mintime = datetime.datetime(1899, 12, 30, 0, 0, 0, 0),
1972 maxtime = datetime.datetime(1899, 12, 30, 23, 59, 59, 0)):
1973 if isinstance(mintime, datetime.datetime):
1974 mintime = SFScriptForge.SF_Basic.CDateToUnoDateTime(mintime)
1975 if isinstance(maxtime, datetime.datetime):
1976 maxtime = SFScriptForge.SF_Basic.CDateToUnoDateTime(maxtime)
1977 return self.ExecMethod(self.vbMethod + self.flgDateArg, 'CreateTimeField', controlname, place, border,
1978 mintime, maxtime)
1979
1980 def CreateTreeControl(self, controlname, place, border = '3D'):
1981 return self.ExecMethod(self.vbMethod, 'CreateTreeControl', controlname, place, border)
1982
1983 def EndExecute(self, returnvalue):
1984 return self.ExecMethod(self.vbMethod + self.flgHardCode, 'EndExecute', returnvalue)
1985
1986 def Execute(self, modal = True):
1987 return self.ExecMethod(self.vbMethod + self.flgHardCode, 'Execute', modal)
1988
1989 def GetTextsFromL10N(self, l10n):
1990 l10nobj = l10n.objectreference if isinstance(l10n, SFScriptForge.SF_L10N) else l10n
1991 return self.ExecMethod(self.vbMethod + self.flgObject, 'GetTextsFromL10N', l10nobj)
1992
1993 def OrderTabs(self, tabslist, start = 1, increment = 1):
1994 return self.ExecMethod(self.vbMethod, 'OrderTabs', tabslist, start, increment)
1995
1996 def Resize(self, left = -99999, top = -99999, width = -1, height = -1):
1997 return self.ExecMethod(self.vbMethod + self.flgHardCode, 'Resize', left, top, width, height)
1998
1999 def SetPageManager(self, pilotcontrols = '', tabcontrols = '', wizardcontrols = '', lastpage = 0):
2000 return self.ExecMethod(self.vbMethod, 'SetPageManager', pilotcontrols, tabcontrols, wizardcontrols,
2001 lastpage)
2002
2003 def Terminate(self):
2004 return self.ExecMethod(self.vbMethod, 'Terminate')
2005
2006 # #########################################################################
2007 # SF_NewDialog CLASS
2008 # #########################################################################
2010 """
2011 Pseudo service never returned from the Basic world. A SF_Dialog instance is returned instead.
2012 Main purpose: manage the arguments of CreateScriptService() for the creation of a dialog from scratch
2013 """
2014 # Mandatory class properties for service registration
2015 serviceimplementation = 'basic'
2016 servicename = 'SFDialogs.NewDialog'
2017 servicesynonyms = ('newdialog', 'sfdialogs.newdialog')
2018 serviceproperties = dict()
2019
2020 @classmethod
2021 def ReviewServiceArgs(cls, dialogname = '', place = (0, 0, 0, 0)):
2022 """
2023 Transform positional and keyword arguments into positional only
2024 Add the XComponentContext as last argument
2025 """
2026 outsideprocess = len(ScriptForge.hostname) > 0 and ScriptForge.port > 0
2027 if outsideprocess:
2028 return dialogname, place, ScriptForge.componentcontext
2029 else:
2030 return dialogname, place
2031
2032 # #########################################################################
2033 # SF_DialogControl CLASS
2034 # #########################################################################
2036 """
2037 Each instance of the current class represents a single control within a dialog box.
2038 The focus is clearly set on getting and setting the values displayed by the controls of the dialog box,
2039 not on their formatting.
2040 A special attention is given to controls with type TreeControl.
2041 """
2042 # Mandatory class properties for service registration
2043 serviceimplementation = 'basic'
2044 servicename = 'SFDialogs.DialogControl'
2045 servicesynonyms = ()
2046 serviceproperties = dict(Border = True, Cancel = True, Caption = True, ControlType = False, CurrentNode = True,
2047 Default = True, Enabled = True, Format = True, Height = True, ListCount = False,
2048 ListIndex = True, Locked = True, MultiSelect = True, Name = False,
2049 OnActionPerformed = True, OnAdjustmentValueChanged = True, OnFocusGained = True,
2050 OnFocusLost = True, OnItemStateChanged = True, OnKeyPressed = True,
2051 OnKeyReleased = True, OnMouseDragged = True, OnMouseEntered = True,
2052 OnMouseExited = True, OnMouseMoved = True, OnMousePressed = True,
2053 OnMouseReleased = True, OnNodeExpanded = True, OnNodeSelected = True,
2054 OnTextChanged = True, Page = True, Parent = False, Picture = True,
2055 RootNode = False, RowSource = True, TabIndex = True, Text = False, TipText = True,
2056 TripleState = True, URL = True, Value = True, Visible = True, Width = True,
2057 X = True, Y = True, XControlModel = False, XControlView = False,
2058 XGridColumnModel = False, XGridDataModel = False, XTreeDataModel = False)
2059
2060 # Root related properties do not start with X and, nevertheless, return a UNO object
2061 @property
2062 def CurrentNode(self):
2063 return self.EXEC(self.objectreference, self.vbGet + self.flgUno, 'CurrentNode')
2064
2065 @property
2066 def RootNode(self):
2067 return self.EXEC(self.objectreference, self.vbGet + self.flgUno, 'RootNode')
2068
2069 def AddSubNode(self, parentnode, displayvalue, datavalue = ScriptForge.cstSymEmpty):
2070 return self.ExecMethod(self.vbMethod + self.flgUno, 'AddSubNode', parentnode, displayvalue, datavalue)
2071
2072 def AddSubTree(self, parentnode, flattree, withdatavalue = False):
2073 return self.ExecMethod(self.vbMethod, 'AddSubTree', parentnode, flattree, withdatavalue)
2074
2075 def CreateRoot(self, displayvalue, datavalue = ScriptForge.cstSymEmpty):
2076 return self.ExecMethod(self.vbMethod + self.flgUno, 'CreateRoot', displayvalue, datavalue)
2077
2078 def FindNode(self, displayvalue, datavalue = ScriptForge.cstSymEmpty, casesensitive = False):
2079 return self.ExecMethod(self.vbMethod + self.flgUno, 'FindNode', displayvalue, datavalue, casesensitive)
2080
2081 def Resize(self, left = -99999, top = -99999, width = -1, height = -1):
2082 return self.ExecMethod(self.vbMethod, 'Resize', left, top, width, height)
2083
2084 def SetFocus(self):
2085 return self.ExecMethod(self.vbMethod, 'SetFocus')
2086
2087 def SetTableData(self, dataarray, widths = (1,), alignments = '', rowheaderwidth = 10):
2088 return self.ExecMethod(self.vbMethod + self.flgArrayArg, 'SetTableData', dataarray, widths, alignments,
2089 rowheaderwidth)
2090
2091 def WriteLine(self, line = ''):
2092 return self.ExecMethod(self.vbMethod, 'WriteLine', line)
2093
2094
2095# #####################################################################################################################
2096# SFDocuments CLASS (alias of SFDocuments Basic library) ###
2097# #####################################################################################################################
2099 """
2100 The SFDocuments class gathers a number of classes, methods and properties making easy
2101 managing and manipulating LibreOffice documents
2102 """
2103 pass
2104
2105 # #########################################################################
2106 # SF_Document CLASS
2107 # #########################################################################
2109 """
2110 The methods and properties are generic for all types of documents: they are combined in the
2111 current SF_Document class
2112 - saving, closing documents
2113 - accessing their standard or custom properties
2114 Specific properties and methods are implemented in the concerned subclass(es) SF_Calc, SF_Base, ...
2115 """
2116 # Mandatory class properties for service registration
2117 serviceimplementation = 'basic'
2118 servicename = 'SFDocuments.Document'
2119 servicesynonyms = ('document', 'sfdocuments.document')
2120 serviceproperties = dict(Description = True, DocumentType = False, ExportFilters = False, FileSystem = False,
2121 ImportFilters = False, IsBase = False, IsCalc = False, IsDraw = False,
2122 IsFormDocument = False, IsImpress = False, IsMath = False, IsWriter = False,
2123 Keywords = True, Readonly = False, Subject = True, Title = True, XComponent = False)
2124 # Force for each property to get its value from Basic - due to intense interactivity with user
2125 forceGetProperty = True
2126
2127 @classmethod
2128 def ReviewServiceArgs(cls, windowname = ''):
2129 """
2130 Transform positional and keyword arguments into positional only
2131 """
2132 return windowname,
2133
2134 def Activate(self):
2135 return self.ExecMethod(self.vbMethod, 'Activate')
2136
2137 def CloseDocument(self, saveask = True):
2138 return self.ExecMethod(self.vbMethod, 'CloseDocument', saveask)
2139
2140 def CreateMenu(self, menuheader, before = '', submenuchar = '>'):
2141 return self.ExecMethod(self.vbMethod, 'CreateMenu', menuheader, before, submenuchar)
2142
2143 def Echo(self, echoon = True, hourglass = False):
2144 return self.ExecMethod(self.vbMethod, 'Echo', echoon, hourglass)
2145
2146 def ExportAsPDF(self, filename, overwrite = False, pages = '', password = '', watermark = ''):
2147 return self.ExecMethod(self.vbMethod, 'ExportAsPDF', filename, overwrite, pages, password, watermark)
2148
2149 def PrintOut(self, pages = '', copies = 1):
2150 return self.ExecMethod(self.vbMethod, 'PrintOut', pages, copies)
2151
2152 def RemoveMenu(self, menuheader):
2153 return self.ExecMethod(self.vbMethod, 'RemoveMenu', menuheader)
2154
2155 def RunCommand(self, command, *args, **kwargs):
2156 params = tuple([command] + list(args) + ScriptForge.unpack_args(kwargs))
2157 return self.ExecMethod(self.vbMethod, 'RunCommand', *params)
2158
2159 def Save(self):
2160 return self.ExecMethod(self.vbMethod, 'Save')
2161
2162 def SaveAs(self, filename, overwrite = False, password = '', filtername = '', filteroptions = ''):
2163 return self.ExecMethod(self.vbMethod, 'SaveAs', filename, overwrite, password, filtername, filteroptions)
2164
2165 def SaveCopyAs(self, filename, overwrite = False, password = '', filtername = '', filteroptions = ''):
2166 return self.ExecMethod(self.vbMethod, 'SaveCopyAs', filename, overwrite,
2167 password, filtername, filteroptions)
2168
2169 def SetPrinter(self, printer = '', orientation = '', paperformat = ''):
2170 return self.ExecMethod(self.vbMethod, 'SetPrinter', printer, orientation, paperformat)
2171
2172 def Toolbars(self, toolbarname = ''):
2173 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'Toolbars', toolbarname)
2174
2175 # #########################################################################
2176 # SF_Base CLASS
2177 # #########################################################################
2179 """
2180 The SF_Base module is provided mainly to block parent properties that are NOT applicable to Base documents
2181 In addition, it provides methods to identify form documents and access their internal forms
2182 (read more elsewhere (the "SFDocuments.Form" service) about this subject)
2183 """
2184 # Mandatory class properties for service registration
2185 serviceimplementation = 'basic'
2186 servicename = 'SFDocuments.Base'
2187 servicesynonyms = ('base', 'scriptforge.base')
2188 serviceproperties = dict(DocumentType = False, FileSystem = False, IsBase = False, IsCalc = False,
2189 IsDraw = False, IsFormDocument = False, IsImpress = False, IsMath = False,
2190 IsWriter = False, XComponent = False)
2191
2192 @classmethod
2193 def ReviewServiceArgs(cls, windowname = ''):
2194 """
2195 Transform positional and keyword arguments into positional only
2196 """
2197 return windowname,
2198
2199 def CloseDocument(self, saveask = True):
2200 return self.ExecMethod(self.vbMethod, 'CloseDocument', saveask)
2201
2202 def CloseFormDocument(self, formdocument):
2203 return self.ExecMethod(self.vbMethod, 'CloseFormDocument', formdocument)
2204
2205 def FormDocuments(self):
2206 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'FormDocuments')
2207
2208 def Forms(self, formdocument, form = ''):
2209 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'Forms', formdocument, form)
2210
2211 def GetDatabase(self, user = '', password = ''):
2212 return self.ExecMethod(self.vbMethod, 'GetDatabase', user, password)
2213
2214 def IsLoaded(self, formdocument):
2215 return self.ExecMethod(self.vbMethod, 'IsLoaded', formdocument)
2216
2217 def OpenFormDocument(self, formdocument, designmode = False):
2218 return self.ExecMethod(self.vbMethod, 'OpenFormDocument', formdocument, designmode)
2219
2220 def OpenQuery(self, queryname):
2221 return self.ExecMethod(self.vbMethod, 'OpenQuery', queryname)
2222
2223 def OpenTable(self, tablename):
2224 return self.ExecMethod(self.vbMethod, 'OpenTable', tablename)
2225
2226 def PrintOut(self, formdocument, pages = '', copies = 1):
2227 return self.ExecMethod(self.vbMethod, 'PrintOut', formdocument, pages, copies)
2228
2229 def SetPrinter(self, formdocument = '', printer = '', orientation = '', paperformat = ''):
2230 return self.ExecMethod(self.vbMethod, 'SetPrinter', formdocument, printer, orientation, paperformat)
2231
2232 # #########################################################################
2233 # SF_Calc CLASS
2234 # #########################################################################
2236 """
2237 The SF_Calc module is focused on :
2238 - management (copy, insert, move, ...) of sheets within a Calc document
2239 - exchange of data between Basic data structures and Calc ranges of values
2240 """
2241 # Mandatory class properties for service registration
2242 serviceimplementation = 'basic'
2243 servicename = 'SFDocuments.Calc'
2244 servicesynonyms = ('calc', 'sfdocuments.calc')
2245 serviceproperties = dict(CurrentSelection = True, Sheets = False,
2246 Description = True, DocumentType = False, ExportFilters = False, FileSystem = False,
2247 ImportFilters = False, IsBase = False, IsCalc = False, IsDraw = False,
2248 IsFormDocument = False, IsImpress = False, IsMath = False, IsWriter = False,
2249 Keywords = True, Readonly = False, Subject = True, Title = True, XComponent = False)
2250 # Force for each property to get its value from Basic - due to intense interactivity with user
2251 forceGetProperty = True
2252
2253 @classmethod
2254 def ReviewServiceArgs(cls, windowname = ''):
2255 """
2256 Transform positional and keyword arguments into positional only
2257 """
2258 return windowname,
2259
2260 # Next functions are implemented in Basic as read-only properties with 1 argument
2261 def FirstCell(self, rangename):
2262 return self.GetProperty('FirstCell', rangename)
2263
2264 def FirstColumn(self, rangename):
2265 return self.GetProperty('FirstColumn', rangename)
2266
2267 def FirstRow(self, rangename):
2268 return self.GetProperty('FirstRow', rangename)
2269
2270 def Height(self, rangename):
2271 return self.GetProperty('Height', rangename)
2272
2273 def LastCell(self, rangename):
2274 return self.GetProperty('LastCell', rangename)
2275
2276 def LastColumn(self, rangename):
2277 return self.GetProperty('LastColumn', rangename)
2278
2279 def LastRow(self, rangename):
2280 return self.GetProperty('LastRow', rangename)
2281
2282 def Range(self, rangename):
2283 return self.GetProperty('Range', rangename)
2284
2285 def Region(self, rangename):
2286 return self.GetProperty('Region', rangename)
2287
2288 def Sheet(self, sheetname):
2289 return self.GetProperty('Sheet', sheetname)
2290
2291 def SheetName(self, rangename):
2292 return self.GetProperty('SheetName', rangename)
2293
2294 def Width(self, rangename):
2295 return self.GetProperty('Width', rangename)
2296
2297 def XCellRange(self, rangename):
2298 return self.ExecMethod(self.vbGet + self.flgUno, 'XCellRange', rangename)
2299
2300 def XSheetCellCursor(self, rangename):
2301 return self.ExecMethod(self.vbGet + self.flgUno, 'XSheetCellCursor', rangename)
2302
2303 def XSpreadsheet(self, sheetname):
2304 return self.ExecMethod(self.vbGet + self.flgUno, 'XSpreadsheet', sheetname)
2305
2306 # Usual methods
2307 def A1Style(self, row1, column1, row2 = 0, column2 = 0, sheetname = '~'):
2308 return self.ExecMethod(self.vbMethod, 'A1Style', row1, column1, row2, column2, sheetname)
2309
2310 def Activate(self, sheetname = ''):
2311 return self.ExecMethod(self.vbMethod, 'Activate', sheetname)
2312
2313 def Charts(self, sheetname, chartname = ''):
2314 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'Charts', sheetname, chartname)
2315
2316 def ClearAll(self, range, filterformula = '', filterscope = ''):
2317 return self.ExecMethod(self.vbMethod, 'ClearAll', range, filterformula, filterscope)
2318
2319 def ClearFormats(self, range, filterformula = '', filterscope = ''):
2320 return self.ExecMethod(self.vbMethod, 'ClearFormats', range, filterformula, filterscope)
2321
2322 def ClearValues(self, range, filterformula = '', filterscope = ''):
2323 return self.ExecMethod(self.vbMethod, 'ClearValues', range, filterformula, filterscope)
2324
2325 def CompactLeft(self, range, wholecolumn = False, filterformula = ''):
2326 return self.ExecMethod(self.vbMethod, 'CompactLeft', range, wholecolumn, filterformula)
2327
2328 def CompactUp(self, range, wholerow = False, filterformula = ''):
2329 return self.ExecMethod(self.vbMethod, 'CompactUp', range, wholerow, filterformula)
2330
2331 def CopySheet(self, sheetname, newname, beforesheet = 32768):
2332 sheet = (sheetname.objectreference if isinstance(sheetname, SFDocuments.SF_CalcReference) else sheetname)
2333 return self.ExecMethod(self.vbMethod + self.flgObject, 'CopySheet', sheet, newname, beforesheet)
2334
2335 def CopySheetFromFile(self, filename, sheetname, newname, beforesheet = 32768):
2336 sheet = (sheetname.objectreference if isinstance(sheetname, SFDocuments.SF_CalcReference) else sheetname)
2337 return self.ExecMethod(self.vbMethod + self.flgObject, 'CopySheetFromFile',
2338 filename, sheet, newname, beforesheet)
2339
2340 def CopyToCell(self, sourcerange, destinationcell):
2341 range = (sourcerange.objectreference if isinstance(sourcerange, SFDocuments.SF_CalcReference)
2342 else sourcerange)
2343 return self.ExecMethod(self.vbMethod + self.flgObject, 'CopyToCell', range, destinationcell)
2344
2345 def CopyToRange(self, sourcerange, destinationrange):
2346 range = (sourcerange.objectreference if isinstance(sourcerange, SFDocuments.SF_CalcReference)
2347 else sourcerange)
2348 return self.ExecMethod(self.vbMethod + self.flgObject, 'CopyToRange', range, destinationrange)
2349
2350 def CreateChart(self, chartname, sheetname, range, columnheader = False, rowheader = False):
2351 return self.ExecMethod(self.vbMethod, 'CreateChart', chartname, sheetname, range, columnheader, rowheader)
2352
2353 def CreatePivotTable(self, pivottablename, sourcerange, targetcell, datafields = ScriptForge.cstSymEmpty,
2354 rowfields = ScriptForge.cstSymEmpty, columnfields = ScriptForge.cstSymEmpty,
2355 filterbutton = True, rowtotals = True, columntotals = True):
2356 return self.ExecMethod(self.vbMethod, 'CreatePivotTable', pivottablename, sourcerange, targetcell,
2357 datafields, rowfields, columnfields, filterbutton, rowtotals, columntotals)
2358
2359 def DAvg(self, range):
2360 return self.ExecMethod(self.vbMethod, 'DAvg', range)
2361
2362 def DCount(self, range):
2363 return self.ExecMethod(self.vbMethod, 'DCount', range)
2364
2365 def DMax(self, range):
2366 return self.ExecMethod(self.vbMethod, 'DMax', range)
2367
2368 def DMin(self, range):
2369 return self.ExecMethod(self.vbMethod, 'DMin', range)
2370
2371 def DSum(self, range):
2372 return self.ExecMethod(self.vbMethod, 'DSum', range)
2373
2374 def ExportRangeToFile(self, range, filename, imagetype = 'pdf', overwrite = False):
2375 return self.ExecMethod(self.vbMethod, 'ExportRangeToFile', range, filename, imagetype, overwrite)
2376
2377 def Forms(self, sheetname, form = ''):
2378 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'Forms', sheetname, form)
2379
2380 def GetColumnName(self, columnnumber):
2381 return self.ExecMethod(self.vbMethod, 'GetColumnName', columnnumber)
2382
2383 def GetFormula(self, range):
2384 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'GetFormula', range)
2385
2386 def GetValue(self, range):
2387 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'GetValue', range)
2388
2389 def ImportFromCSVFile(self, filename, destinationcell, filteroptions = ScriptForge.cstSymEmpty):
2390 return self.ExecMethod(self.vbMethod, 'ImportFromCSVFile', filename, destinationcell, filteroptions)
2391
2392 def ImportFromDatabase(self, filename = '', registrationname = '', destinationcell = '', sqlcommand = '',
2393 directsql = False):
2394 return self.ExecMethod(self.vbMethod, 'ImportFromDatabase', filename, registrationname,
2395 destinationcell, sqlcommand, directsql)
2396
2397 def InsertSheet(self, sheetname, beforesheet = 32768):
2398 return self.ExecMethod(self.vbMethod, 'InsertSheet', sheetname, beforesheet)
2399
2400 def MoveRange(self, source, destination):
2401 return self.ExecMethod(self.vbMethod, 'MoveRange', source, destination)
2402
2403 def MoveSheet(self, sheetname, beforesheet = 32768):
2404 return self.ExecMethod(self.vbMethod, 'MoveSheet', sheetname, beforesheet)
2405
2406 def Offset(self, range, rows = 0, columns = 0, height = ScriptForge.cstSymEmpty,
2407 width = ScriptForge.cstSymEmpty):
2408 return self.ExecMethod(self.vbMethod, 'Offset', range, rows, columns, height, width)
2409
2410 def OpenRangeSelector(self, title = '', selection = '~', singlecell = False, closeafterselect = True):
2411 return self.ExecMethod(self.vbMethod, 'OpenRangeSelector', title, selection, singlecell, closeafterselect)
2412
2413 def Printf(self, inputstr, range, tokencharacter = '%'):
2414 return self.ExecMethod(self.vbMethod, 'Printf', inputstr, range, tokencharacter)
2415
2416 def PrintOut(self, sheetname = '~', pages = '', copies = 1):
2417 return self.ExecMethod(self.vbMethod, 'PrintOut', sheetname, pages, copies)
2418
2419 def RemoveDuplicates(self, range, columns = 1, header = False, casesensitive = False, mode = 'COMPACT'):
2420 return self.ExecMethod(self.vbMethod, 'RemoveDuplicates', range, columns, header, casesensitive, mode)
2421
2422 def RemoveSheet(self, sheetname):
2423 return self.ExecMethod(self.vbMethod, 'RemoveSheet', sheetname)
2424
2425 def RenameSheet(self, sheetname, newname):
2426 return self.ExecMethod(self.vbMethod, 'RenameSheet', sheetname, newname)
2427
2428 def SetArray(self, targetcell, value):
2429 return self.ExecMethod(self.vbMethod + self.flgArrayArg, 'SetArray', targetcell, value)
2430
2431 def SetCellStyle(self, targetrange, style, filterformula = '', filterscope = ''):
2432 return self.ExecMethod(self.vbMethod, 'SetCellStyle', targetrange, style, filterformula, filterscope)
2433
2434 def SetFormula(self, targetrange, formula):
2435 return self.ExecMethod(self.vbMethod + self.flgArrayArg, 'SetFormula', targetrange, formula)
2436
2437 def SetValue(self, targetrange, value):
2438 return self.ExecMethod(self.vbMethod + self.flgArrayArg, 'SetValue', targetrange, value)
2439
2440 def ShiftDown(self, range, wholerow = False, rows = 0):
2441 return self.ExecMethod(self.vbMethod, 'ShiftDown', range, wholerow, rows)
2442
2443 def ShiftLeft(self, range, wholecolumn = False, columns = 0):
2444 return self.ExecMethod(self.vbMethod, 'ShiftLeft', range, wholecolumn, columns)
2445
2446 def ShiftRight(self, range, wholecolumn = False, columns = 0):
2447 return self.ExecMethod(self.vbMethod, 'ShiftRight', range, wholecolumn, columns)
2448
2449 def ShiftUp(self, range, wholerow = False, rows = 0):
2450 return self.ExecMethod(self.vbMethod, 'ShiftUp', range, wholerow, rows)
2451
2452 def SortRange(self, range, sortkeys, sortorder = 'ASC', destinationcell = ScriptForge.cstSymEmpty,
2453 containsheader = False, casesensitive = False, sortcolumns = False):
2454 return self.ExecMethod(self.vbMethod, 'SortRange', range, sortkeys, sortorder, destinationcell,
2455 containsheader, casesensitive, sortcolumns)
2456
2457 # #########################################################################
2458 # SF_CalcReference CLASS
2459 # #########################################################################
2461 """
2462 The SF_CalcReference class has as unique role to hold sheet and range references.
2463 They are implemented in Basic as Type ... End Type data structures
2464 """
2465 # Mandatory class properties for service registration
2466 serviceimplementation = 'basic'
2467 servicename = 'SFDocuments.CalcReference'
2468 servicesynonyms = ()
2469 serviceproperties = dict()
2470
2471 # #########################################################################
2472 # SF_Chart CLASS
2473 # #########################################################################
2475 """
2476 The SF_Chart module is focused on the description of chart documents
2477 stored in Calc sheets.
2478 With this service, many chart types and chart characteristics available
2479 in the user interface can be read or modified.
2480 """
2481 # Mandatory class properties for service registration
2482 serviceimplementation = 'basic'
2483 servicename = 'SFDocuments.Chart'
2484 servicesynonyms = ()
2485 serviceproperties = dict(ChartType = True, Deep = True, Dim3D = True, Exploded = True, Filled = True,
2486 Legend = True, Percent = True, Stacked = True, Title = True,
2487 XChartObj = False, XDiagram = False, XShape = False, XTableChart = False,
2488 XTitle = True, YTitle = True)
2489
2490 def Resize(self, xpos = -1, ypos = -1, width = -1, height = -1):
2491 return self.ExecMethod(self.vbMethod, 'Resize', xpos, ypos, width, height)
2492
2493 def ExportToFile(self, filename, imagetype = 'png', overwrite = False):
2494 return self.ExecMethod(self.vbMethod, 'ExportToFile', filename, imagetype, overwrite)
2495
2496 # #########################################################################
2497 # SF_Form CLASS
2498 # #########################################################################
2500 """
2501 Management of forms defined in LibreOffice documents. Supported types are Base, Calc and Writer documents.
2502 It includes the management of subforms
2503 Each instance of the current class represents a single form or a single subform
2504 A form may optionally be (understand "is often") linked to a data source manageable with
2505 the SFDatabases.Database service. The current service offers rapid access to that service.
2506 """
2507 # Mandatory class properties for service registration
2508 serviceimplementation = 'basic'
2509 servicename = 'SFDocuments.Form'
2510 servicesynonyms = ()
2511 serviceproperties = dict(AllowDeletes = True, AllowInserts = True, AllowUpdates = True, BaseForm = False,
2512 Bookmark = True, CurrentRecord = True, Filter = True, LinkChildFields = False,
2513 LinkParentFields = False, Name = False,
2514 OnApproveCursorMove = True, OnApproveParameter = True, OnApproveReset = True,
2515 OnApproveRowChange = True, OnApproveSubmit = True, OnConfirmDelete = True,
2516 OnCursorMoved = True, OnErrorOccurred = True, OnLoaded = True, OnReloaded = True,
2517 OnReloading = True, OnResetted = True, OnRowChanged = True, OnUnloaded = True,
2518 OnUnloading = True,
2519 OrderBy = True, Parent = False, RecordSource = True, XForm = False)
2520
2521 def Activate(self):
2522 return self.ExecMethod(self.vbMethod, 'Activate')
2523
2525 return self.ExecMethod(self.vbMethod, 'CloseFormDocument')
2526
2527 def Controls(self, controlname = ''):
2528 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'Controls', controlname)
2529
2530 def GetDatabase(self, user = '', password = ''):
2531 return self.ExecMethod(self.vbMethod, 'GetDatabase', user, password)
2532
2533 def MoveFirst(self):
2534 return self.ExecMethod(self.vbMethod, 'MoveFirst')
2535
2536 def MoveLast(self):
2537 return self.ExecMethod(self.vbMethod, 'MoveLast')
2538
2539 def MoveNew(self):
2540 return self.ExecMethod(self.vbMethod, 'MoveNew')
2541
2542 def MoveNext(self, offset = 1):
2543 return self.ExecMethod(self.vbMethod, 'MoveNext', offset)
2544
2545 def MovePrevious(self, offset = 1):
2546 return self.ExecMethod(self.vbMethod, 'MovePrevious', offset)
2547
2548 def Requery(self):
2549 return self.ExecMethod(self.vbMethod, 'Requery')
2550
2551 def Subforms(self, subform = ''):
2552 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'Subforms', subform)
2553
2554 # #########################################################################
2555 # SF_FormControl CLASS
2556 # #########################################################################
2558 """
2559 Manage the controls belonging to a form or subform stored in a document.
2560 Each instance of the current class represents a single control within a form, a subform or a tablecontrol.
2561 A prerequisite is that all controls within the same form, subform or tablecontrol must have
2562 a unique name.
2563 """
2564 # Mandatory class properties for service registration
2565 serviceimplementation = 'basic'
2566 servicename = 'SFDocuments.FormControl'
2567 servicesynonyms = ()
2568 serviceproperties = dict(Action = True, Caption = True, ControlSource = False, ControlType = False,
2569 Default = True, DefaultValue = True, Enabled = True, Format = True,
2570 ListCount = False, ListIndex = True, ListSource = True, ListSourceType = True,
2571 Locked = True, MultiSelect = True, Name = False,
2572 OnActionPerformed = True, OnAdjustmentValueChanged = True,
2573 OnApproveAction = True, OnApproveReset = True, OnApproveUpdate = True,
2574 OnChanged = True, OnErrorOccurred = True, OnFocusGained = True, OnFocusLost = True,
2575 OnItemStateChanged = True, OnKeyPressed = True, OnKeyReleased = True,
2576 OnMouseDragged = True, OnMouseEntered = True, OnMouseExited = True,
2577 OnMouseMoved = True, OnMousePressed = True, OnMouseReleased = True, OnResetted = True,
2578 OnTextChanged = True, OnUpdated = True, Parent = False, Picture = True,
2579 Required = True, Text = False, TipText = True, TripleState = True, Value = True,
2580 Visible = True, XControlModel = False, XControlView = False)
2581
2582 def Controls(self, controlname = ''):
2583 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'Controls', controlname)
2584
2585 def SetFocus(self):
2586 return self.ExecMethod(self.vbMethod, 'SetFocus')
2587
2588 # #########################################################################
2589 # SF_FormDocument CLASS
2590 # #########################################################################
2592 """
2593 The orchestration of Base form documents (aka Base Forms, but this is confusing)
2594 and the identification of and the access to their controls.
2595 Form documents are always contained in a Base document.
2596 They should not be confused with Writer documents containing forms,
2597 even if it is easy to convert the former to the latter.
2598 """
2599 # Mandatory class properties for service registration
2600 serviceimplementation = 'basic'
2601 servicename = 'SFDocuments.FormDocument'
2602 servicesynonyms = ('formdocument', 'sfdocuments.formdocument')
2603 serviceproperties = dict(DocumentType = False, FileSystem = False, IsBase = False, IsCalc = False,
2604 IsDraw = False, IsFormDocument = False, IsImpress = False, IsMath = False,
2605 IsWriter = False, Readonly = False, XComponent = False)
2606
2607 @classmethod
2608 def ReviewServiceArgs(cls, windowname = ''):
2609 """
2610 Transform positional and keyword arguments into positional only
2611 """
2612 return windowname,
2613
2614 def CloseDocument(self):
2615 return self.ExecMethod(self.vbMethod, 'CloseDocument')
2616
2617 def Forms(self, form = ''):
2618 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'Forms', form)
2619
2620 def GetDatabase(self, user = '', password = ''):
2621 return self.ExecMethod(self.vbMethod, 'GetDatabase', user, password)
2622
2623 def PrintOut(self, pages = '', copies = 1, printbackground = True, printblankpages = False,
2624 printevenpages = True, printoddpages = True, printimages = True):
2625 return self.ExecMethod(self.vbMethod, 'PrintOut', pages, copies, printbackground, printblankpages,
2626 printevenpages, printoddpages, printimages)
2627
2628 # #########################################################################
2629 # SF_Writer CLASS
2630 # #########################################################################
2632 """
2633 The SF_Writer module is focused on :
2634 - TBD
2635 """
2636 # Mandatory class properties for service registration
2637 serviceimplementation = 'basic'
2638 servicename = 'SFDocuments.Writer'
2639 servicesynonyms = ('writer', 'sfdocuments.writer')
2640 serviceproperties = dict(Description = True, DocumentType = False, ExportFilters = False, FileSystem = False,
2641 ImportFilters = False, IsBase = False, IsCalc = False, IsDraw = False,
2642 IsFormDocument = False, IsImpress = False, IsMath = False, IsWriter = False,
2643 Keywords = True, Readonly = False, Subject = True, Title = True, XComponent = False)
2644 # Force for each property to get its value from Basic - due to intense interactivity with user
2645 forceGetProperty = True
2646
2647 @classmethod
2648 def ReviewServiceArgs(cls, windowname = ''):
2649 """
2650 Transform positional and keyword arguments into positional only
2651 """
2652 return windowname,
2653
2654 def Forms(self, form = ''):
2655 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'Forms', form)
2656
2657 def PrintOut(self, pages = '', copies = 1, printbackground = True, printblankpages = False,
2658 printevenpages = True, printoddpages = True, printimages = True):
2659 return self.ExecMethod(self.vbMethod, 'PrintOut', pages, copies, printbackground, printblankpages,
2660 printevenpages, printoddpages, printimages)
2661
2662
2663# #####################################################################################################################
2664# SFWidgets CLASS (alias of SFWidgets Basic library) ###
2665# #####################################################################################################################
2667 """
2668 The SFWidgets class manages toolbars and popup menus
2669 """
2670 pass
2671
2672 # #########################################################################
2673 # SF_Menu CLASS
2674 # #########################################################################
2676 """
2677 Display a menu in the menubar of a document or a form document.
2678 After use, the menu will not be saved neither in the application settings, nor in the document.
2679 The menu will be displayed, as usual, when its header in the menubar is clicked.
2680 When one of its items is selected, there are 3 alternative options:
2681 - a UNO command (like ".uno:About") is triggered
2682 - a user script is run receiving a standard argument defined in this service
2683 - one of above combined with a toggle of the status of the item
2684 The menu is described from top to bottom. Each menu item receives a numeric and a string identifier.
2685 """
2686 # Mandatory class properties for service registration
2687 serviceimplementation = 'basic'
2688 servicename = 'SFWidgets.Menu'
2689 servicesynonyms = ('menu', 'sfwidgets.menu')
2690 serviceproperties = dict(ShortcutCharacter = False, SubmenuCharacter = False)
2691
2692 def AddCheckBox(self, menuitem, name = '', status = False, icon = '', tooltip = '',
2693 command = '', script = ''):
2694 return self.ExecMethod(self.vbMethod, 'AddCheckBox', menuitem, name, status, icon, tooltip,
2695 command, script)
2696
2697 def AddItem(self, menuitem, name = '', icon = '', tooltip = '', command = '', script = ''):
2698 return self.ExecMethod(self.vbMethod, 'AddItem', menuitem, name, icon, tooltip, command, script)
2699
2700 def AddRadioButton(self, menuitem, name = '', status = False, icon = '', tooltip = '',
2701 command = '', script = ''):
2702 return self.ExecMethod(self.vbMethod, 'AddRadioButton', menuitem, name, status, icon, tooltip,
2703 command, script)
2704
2705 # #########################################################################
2706 # SF_PopupMenu CLASS
2707 # #########################################################################
2709 """
2710 Display a popup menu anywhere and any time.
2711 A popup menu is usually triggered by a mouse action (typically a right-click) on a dialog, a form
2712 or one of their controls. In this case the menu will be displayed below the clicked area.
2713 When triggered by other events, including in the normal flow of a user script, the script should
2714 provide the coordinates of the topleft edge of the menu versus the actual component.
2715 The menu is described from top to bottom. Each menu item receives a numeric and a string identifier.
2716 The execute() method returns the item selected by the user.
2717 """
2718 # Mandatory class properties for service registration
2719 serviceimplementation = 'basic'
2720 servicename = 'SFWidgets.PopupMenu'
2721 servicesynonyms = ('popupmenu', 'sfwidgets.popupmenu')
2722 serviceproperties = dict(ShortcutCharacter = False, SubmenuCharacter = False)
2723
2724 @classmethod
2725 def ReviewServiceArgs(cls, event = None, x = 0, y = 0, submenuchar = ''):
2726 """
2727 Transform positional and keyword arguments into positional only
2728 """
2729 return event, x, y, submenuchar
2730
2731 def AddCheckBox(self, menuitem, name = '', status = False, icon = '', tooltip = ''):
2732 return self.ExecMethod(self.vbMethod, 'AddCheckBox', menuitem, name, status, icon, tooltip)
2733
2734 def AddItem(self, menuitem, name = '', icon = '', tooltip = ''):
2735 return self.ExecMethod(self.vbMethod, 'AddItem', menuitem, name, icon, tooltip)
2736
2737 def AddRadioButton(self, menuitem, name = '', status = False, icon = '', tooltip = ''):
2738 return self.ExecMethod(self.vbMethod, 'AddRadioButton', menuitem, name, status, icon, tooltip)
2739
2740 def Execute(self, returnid = True):
2741 return self.ExecMethod(self.vbMethod, 'Execute', returnid)
2742
2743 # #########################################################################
2744 # SF_Toolbar CLASS
2745 # #########################################################################
2747 """
2748 Each component has its own set of toolbars, depending on the component type
2749 (Calc, Writer, Basic IDE, ...).
2750 In the context of the actual class, a toolbar is presumed defined statically:
2751 - either by the application
2752 - or by a customization done by the user.
2753 """
2754 # Mandatory class properties for service registration
2755 serviceimplementation = 'basic'
2756 servicename = 'SFWidgets.Toolbar'
2757 servicesynonyms = ('toolbar', 'sfwidgets.toolbar')
2758 serviceproperties = dict(BuiltIn = False, Docked = False, HasGlobalScope = False, Name = False,
2759 ResourceURL = False, Visible = True, XUIElement = False)
2760
2761 def ToolbarButtons(self, buttonname = ''):
2762 return self.ExecMethod(self.vbMethod + self.flgArrayRet, 'ToolbarButtons', buttonname)
2763
2764 # #########################################################################
2765 # SF_ToolbarButton CLASS
2766 # #########################################################################
2768 """
2769 A toolbar consists in a series of graphical controls to trigger actions.
2770 The "Toolbar" service gives access to the "ToolbarButton" service to manage
2771 the individual buttons belonging to the toolbar.
2772 """
2773 # Mandatory class properties for service registration
2774 serviceimplementation = 'basic'
2775 servicename = 'SFWidgets.ToolbarButton'
2776 servicesynonyms = ('toolbarbutton', 'sfwidgets.toolbarbutton')
2777 serviceproperties = dict(Caption = False, Height = False, Index = False, OnClick = True, Parent = False,
2778 TipText = True, Visible = True, Width = False, X = False, Y = False)
2779
2780 def Execute(self):
2781 return self.ExecMethod(self.vbMethod, 'Execute')
2782
2783
2784# ##############################################False##################################################################
2785# CreateScriptService() ###
2786# #####################################################################################################################
2787def CreateScriptService(service, *args, **kwargs):
2788 """
2789 A service being the name of a collection of properties and methods,
2790 this method returns either
2791 - the Python object mirror of the Basic object implementing the requested service
2792 - the Python object implementing the service itself
2793
2794 A service may be designated by its official name, stored in its class.servicename
2795 or by one of its synonyms stored in its class.servicesynonyms list
2796 If the service is not identified, the service creation is delegated to Basic, that might raise an error
2797 if still not identified there
2798
2799 :param service: the name of the service as a string 'library.service' - cased exactly
2800 or one of its synonyms
2801 :param args: the arguments to pass to the service constructor
2802 :return: the service as a Python object
2803 """
2804 # Init at each CreateScriptService() invocation
2805 # CreateScriptService is usually the first statement in user scripts requesting ScriptForge services
2806 # ScriptForge() is optional in user scripts when Python process inside LibreOffice process
2807 if ScriptForge.SCRIPTFORGEINITDONE is False:
2808 ScriptForge()
2809
2810 def ResolveSynonyms(servicename):
2811 """
2812 Synonyms within service names implemented in Python or predefined are resolved here
2813 :param servicename: The short name of the service
2814 :return: The official service name if found, the argument otherwise
2815 """
2816 for cls in SFServices.__subclasses__():
2817 if servicename.lower() in cls.servicesynonyms:
2818 return cls.servicename
2819 return servicename
2820
2821 #
2822 # Check the list of available services
2823 scriptservice = ResolveSynonyms(service)
2824 if scriptservice in ScriptForge.serviceslist:
2825 serv = ScriptForge.serviceslist[scriptservice]
2826 # Check if the requested service is within the Python world
2827 if serv.serviceimplementation == 'python':
2828 return serv(*args)
2829 # Check if the service is a predefined standard Basic service
2830 elif scriptservice in ScriptForge.servicesmodules:
2831 return serv(ScriptForge.servicesmodules[scriptservice], classmodule = SFServices.moduleStandard)
2832 else:
2833 serv = None
2834 # The requested service is to be found in the Basic world
2835 # Check if the service must review the arguments
2836 if serv is not None:
2837 if hasattr(serv, 'ReviewServiceArgs'):
2838 # ReviewServiceArgs() must be a class method
2839 args = serv.ReviewServiceArgs(*args, **kwargs)
2840 # Get the service object back from Basic
2841 if len(args) == 0:
2842 serv = ScriptForge.InvokeBasicService('SF_Services', SFServices.vbMethod, 'CreateScriptService', service)
2843 else:
2844 serv = ScriptForge.InvokeBasicService('SF_Services', SFServices.vbMethod, 'CreateScriptService',
2845 service, *args)
2846 return serv
2847
2848
2849createScriptService, createscriptservice = CreateScriptService, CreateScriptService
2850
2851# ######################################################################
2852# Lists the scripts, that shall be visible inside the Basic/Python IDE
2853# ######################################################################
2854
2855g_exportedScripts = ()
def DLookup(self, expression, tablename, criteria='', orderclause='')
def RunSql(self, sqlcommand, directsql=False)
def DMax(self, expression, tablename, criteria='')
def OpenFormDocument(self, formdocument)
def DAvg(self, expression, tablename, criteria='')
def DCount(self, expression, tablename, criteria='')
def DSum(self, expression, tablename, criteria='')
def ReviewServiceArgs(cls, filename='', registrationname='', readonly=True, user='', password='')
def DMin(self, expression, tablename, criteria='')
def GetRows(self, sqlcommand, directsql=False, header=False, maxrows=0)
def OpenSql(self, sql, directsql=False)
def CreateMenu(self, menuheader, before='', submenuchar='>')
def Toolbars(self, toolbarname='')
def RemoveMenu(self, menuheader)
def GoToCell(self, row=0, column=0)
def CreateRoot(self, displayvalue, datavalue=ScriptForge.cstSymEmpty)
def SetTableData(self, dataarray, widths=(1,), alignments='', rowheaderwidth=10)
def AddSubTree(self, parentnode, flattree, withdatavalue=False)
def FindNode(self, displayvalue, datavalue=ScriptForge.cstSymEmpty, casesensitive=False)
def Resize(self, left=-99999, top=-99999, width=-1, height=-1)
def AddSubNode(self, parentnode, displayvalue, datavalue=ScriptForge.cstSymEmpty)
def SetPageManager(self, pilotcontrols='', tabcontrols='', wizardcontrols='', lastpage=0)
def CreateFileControl(self, controlname, place, border='3D')
def CreateNumericField(self, controlname, place, border='3D', spinbutton=False, minvalue=-1000000, maxvalue=+1000000, increment=1, accuracy=2)
def CreateTimeField(self, controlname, place, border='3D', mintime=datetime.datetime(1899, 12, 30, 0, 0, 0, 0), maxtime=datetime.datetime(1899, 12, 30, 23, 59, 59, 0))
def CreateFixedText(self, controlname, place, border='NONE', multiline=False, align='LEFT', verticalalign='TOP')
def Execute(self, modal=True)
def CreateFormattedField(self, controlname, place, border='3D', spinbutton=False, minvalue=-1000000, maxvalue=+1000000)
def CreateListBox(self, controlname, place, border='3D', dropdown=True, linecount=5, multiselect=False)
def OrderTabs(self, tabslist, start=1, increment=1)
def Center(self, parent=ScriptForge.cstSymMissing)
def CreateDateField(self, controlname, place, border='3D', dropdown=True, mindate=datetime.datetime(1900, 1, 1, 0, 0, 0, 0), maxdate=datetime.datetime(2200, 12, 31, 0, 0, 0, 0))
def CreateRadioButton(self, controlname, place, multiline=False)
def CreateTreeControl(self, controlname, place, border='3D')
def CreateTextField(self, controlname, place, border='3D', multiline=False, maximumlength=0, passwordcharacter='')
def CloneControl(self, sourcename, controlname, left=1, top=1)
def EndExecute(self, returnvalue)
def CreateButton(self, controlname, place, toggle=False, push='')
def Resize(self, left=-99999, top=-99999, width=-1, height=-1)
def ReviewServiceArgs(cls, container='', library='Standard', dialogname='')
def CreateTableControl(self, controlname, place, border='3D', rowheaders=True, columnheaders=True, scrollbars='None', gridlines=False)
def CreateGroupBox(self, controlname, place)
def CreatePatternField(self, controlname, place, border='3D', editmask='', literalmask='')
def CreateCheckBox(self, controlname, place, multiline=False)
def CreateScrollBar(self, controlname, place, orientation, border='3D', minvalue=0, maxvalue=100)
def Controls(self, controlname='')
def CreateFixedLine(self, controlname, place, orientation)
def CreateCurrencyField(self, controlname, place, border='3D', spinbutton=False, minvalue=-1000000, maxvalue=+1000000, increment=1, accuracy=2)
def CreateImageControl(self, controlname, place, border='3D', scale='FITTOSIZE')
def CreateProgressBar(self, controlname, place, border='3D', minvalue=0, maxvalue=100)
def CreateComboBox(self, controlname, place, border='3D', dropdown=True, linecount=5)
def CreateHyperlink(self, controlname, place, border='NONE', multiline=False, align='LEFT', verticalalign='TOP')
def ReviewServiceArgs(cls, dialogname='', place=(0, 0, 0, 0))
def SetPrinter(self, formdocument='', printer='', orientation='', paperformat='')
def OpenTable(self, tablename)
def IsLoaded(self, formdocument)
def GetDatabase(self, user='', password='')
def PrintOut(self, formdocument, pages='', copies=1)
def ReviewServiceArgs(cls, windowname='')
def Forms(self, formdocument, form='')
def CloseDocument(self, saveask=True)
def OpenFormDocument(self, formdocument, designmode=False)
def CloseFormDocument(self, formdocument)
def OpenQuery(self, queryname)
def SetCellStyle(self, targetrange, style, filterformula='', filterscope='')
def ImportFromCSVFile(self, filename, destinationcell, filteroptions=ScriptForge.cstSymEmpty)
def XCellRange(self, rangename)
def FirstColumn(self, rangename)
def ShiftDown(self, range, wholerow=False, rows=0)
def InsertSheet(self, sheetname, beforesheet=32768)
def ShiftRight(self, range, wholecolumn=False, columns=0)
def MoveRange(self, source, destination)
def RemoveDuplicates(self, range, columns=1, header=False, casesensitive=False, mode='COMPACT')
def Activate(self, sheetname='')
def Width(self, rangename)
def RemoveSheet(self, sheetname)
def CompactUp(self, range, wholerow=False, filterformula='')
def Region(self, rangename)
def ReviewServiceArgs(cls, windowname='')
def ClearValues(self, range, filterformula='', filterscope='')
def Height(self, rangename)
def MoveSheet(self, sheetname, beforesheet=32768)
def CopyToCell(self, sourcerange, destinationcell)
def Charts(self, sheetname, chartname='')
def LastCell(self, rangename)
def GetColumnName(self, columnnumber)
def XSpreadsheet(self, sheetname)
def CopySheet(self, sheetname, newname, beforesheet=32768)
def ExportRangeToFile(self, range, filename, imagetype='pdf', overwrite=False)
def Offset(self, range, rows=0, columns=0, height=ScriptForge.cstSymEmpty, width=ScriptForge.cstSymEmpty)
def A1Style(self, row1, column1, row2=0, column2=0, sheetname='~')
def ClearAll(self, range, filterformula='', filterscope='')
def CopyToRange(self, sourcerange, destinationrange)
def CompactLeft(self, range, wholecolumn=False, filterformula='')
def ShiftLeft(self, range, wholecolumn=False, columns=0)
def Printf(self, inputstr, range, tokencharacter='%')
def LastRow(self, rangename)
def RenameSheet(self, sheetname, newname)
def CreateChart(self, chartname, sheetname, range, columnheader=False, rowheader=False)
def FirstCell(self, rangename)
def ClearFormats(self, range, filterformula='', filterscope='')
def Range(self, rangename)
def PrintOut(self, sheetname='~', pages='', copies=1)
def Sheet(self, sheetname)
def SheetName(self, rangename)
def XSheetCellCursor(self, rangename)
def SetArray(self, targetcell, value)
def Forms(self, sheetname, form='')
def SetValue(self, targetrange, value)
def SetFormula(self, targetrange, formula)
def ShiftUp(self, range, wholerow=False, rows=0)
def CreatePivotTable(self, pivottablename, sourcerange, targetcell, datafields=ScriptForge.cstSymEmpty, rowfields=ScriptForge.cstSymEmpty, columnfields=ScriptForge.cstSymEmpty, filterbutton=True, rowtotals=True, columntotals=True)
def LastColumn(self, rangename)
def FirstRow(self, rangename)
def CopySheetFromFile(self, filename, sheetname, newname, beforesheet=32768)
def SortRange(self, range, sortkeys, sortorder='ASC', destinationcell=ScriptForge.cstSymEmpty, containsheader=False, casesensitive=False, sortcolumns=False)
def ImportFromDatabase(self, filename='', registrationname='', destinationcell='', sqlcommand='', directsql=False)
def OpenRangeSelector(self, title='', selection='~', singlecell=False, closeafterselect=True)
def Resize(self, xpos=-1, ypos=-1, width=-1, height=-1)
def ExportToFile(self, filename, imagetype='png', overwrite=False)
def SetPrinter(self, printer='', orientation='', paperformat='')
def Toolbars(self, toolbarname='')
def RunCommand(self, command, *args, **kwargs)
def RemoveMenu(self, menuheader)
def ExportAsPDF(self, filename, overwrite=False, pages='', password='', watermark='')
def SaveCopyAs(self, filename, overwrite=False, password='', filtername='', filteroptions='')
def SaveAs(self, filename, overwrite=False, password='', filtername='', filteroptions='')
def PrintOut(self, pages='', copies=1)
def CloseDocument(self, saveask=True)
def CreateMenu(self, menuheader, before='', submenuchar='>')
def Echo(self, echoon=True, hourglass=False)
def ReviewServiceArgs(cls, windowname='')
def Controls(self, controlname='')
def PrintOut(self, pages='', copies=1, printbackground=True, printblankpages=False, printevenpages=True, printoddpages=True, printimages=True)
def GetDatabase(self, user='', password='')
def ReviewServiceArgs(cls, windowname='')
def GetDatabase(self, user='', password='')
def Controls(self, controlname='')
def Subforms(self, subform='')
def MovePrevious(self, offset=1)
def MoveNext(self, offset=1)
def ReviewServiceArgs(cls, windowname='')
def PrintOut(self, pages='', copies=1, printbackground=True, printblankpages=False, printevenpages=True, printoddpages=True, printimages=True)
def ImportFromCSVFile(self, filename, delimiter=',', dateformat='')
Definition: scriptforge.py:623
def DateDiff(cls, interval, date1, date2, firstdayofweek=1, firstweekofyear=1)
Definition: scriptforge.py:743
def MsgBox(cls, prompt, buttons=0, title='')
Definition: scriptforge.py:801
def CreateUnoService(cls, servicename)
Definition: scriptforge.py:728
def InputBox(cls, prompt, title='', default='', xpostwips=-1, ypostwips=-1)
Definition: scriptforge.py:795
def Format(cls, expression, format='')
Definition: scriptforge.py:764
def Xray(cls, unoobject=None)
Definition: scriptforge.py:879
def RGB(cls, red, green, blue)
Definition: scriptforge.py:809
def CreateUnoStruct(cls, unostructure)
Definition: scriptforge.py:732
def DateAdd(cls, interval, number, date)
Definition: scriptforge.py:736
def ConvertToUrl(cls, systempath)
Definition: scriptforge.py:724
def DatePart(cls, interval, date, firstdayofweek=1, firstweekofyear=1)
Definition: scriptforge.py:751
def ImportFromPropertyValues(self, propertyvalues, overwrite=False)
Definition: scriptforge.py:948
def PythonShell(cls, variables=None)
def _RaiseFatal(cls, sub, subargs, errorcode, *args)
def RaiseFatal(cls, errorcode, *args)
def GetTempName(self, extension='')
def HashFile(self, filename, algorithm)
def CopyFile(self, source, destination, overwrite=True)
def MoveFolder(self, source, destination)
def Files(self, foldername, filter='', includesubfolders=False)
def SubFolders(self, foldername, filter='', includesubfolders=False)
def BuildPath(self, foldername, name)
def CopyFolder(self, source, destination, overwrite=True)
def CompareFiles(self, filename1, filename2, comparecontents=False)
def PickFile(self, defaultfile=ScriptForge.cstSymEmpty, mode='OPEN', filter='')
def CreateTextFile(self, filename, overwrite=True, encoding='UTF-8')
def MoveFile(self, source, destination)
def PickFolder(self, defaultfolder=ScriptForge.cstSymEmpty, freetext='')
def OpenTextFile(self, filename, iomode=1, create=False, encoding='UTF-8')
def AddText(self, context='', msgid='', comment='')
def AddTextsFromDialog(self, dialog)
def ReviewServiceArgs(cls, foldername='', locale='', encoding='UTF-8', locale2='', encoding2='UTF-8')
def GetText(self, msgid, *args)
def ExportToPOTFile(self, filename, header='', encoding='UTF-8')
def TimeSeparator(self, region='')
def UTCDateTime(self, localdatetime, timezone, locale='')
def ThousandSeparator(self, region='')
def LocalDateTime(self, utcdatetime, timezone, locale='')
def DayNarrowNames(self, region='')
def DecimalPoint(self, region='')
def UTCNow(self, timezone, locale='')
def DatePatterns(self, region='')
def DayAbbrevNames(self, region='')
def MonthNarrowNames(self, region='')
def TimeZoneOffset(self, timezone, locale='')
def Number2Text(self, number, locale='')
def MonthAbbrevNames(self, region='')
def DateSeparator(self, region='')
def DSTOffset(self, localdatetime, timezone, locale='')
def ListSeparator(self, region='')
def ExecutePythonScript(cls, scope='', script='', *args)
def SendMail(self, recipient, cc='', bcc='', subject='', body='', filenames='', editmessage=True)
def ExecuteBasicScript(cls, scope='', script='', *args)
def HasUnoMethod(self, unoobject, methodname)
def UnoObjectType(self, unoobject)
def HasUnoProperty(self, unoobject, propertyname)
def UnoProperties(self, unoobject)
def ExecuteCalcFunction(cls, calcfunction, *args)
def RunApplication(self, command, parameters)
def IsFileName(self, inputstr, osname=ScriptForge.cstSymEmpty)
def IsADate(self, inputstr, dateformat='YYYY-MM-DD')
def SplitNotQuoted(self, inputstr, delimiter=' ', occurrences=0, quotechar='"')
def IsLike(self, inputstr, pattern, casesensitive=False)
def Wrap(self, inputstr, width=70, tabsize=8)
def HashStr(cls, inputstr, algorithm)
def ReviewServiceArgs(cls, start=False)
def ShowProgressBar(self, title='', text='', percentage=-1)
def Resize(self, left=-1, top=-1, width=-1, height=-1)
def Maximize(self, windowname='')
def OpenBaseDocument(self, filename='', registrationname='', macroexecution=MACROEXECNORMAL)
def CreateBaseDocument(self, filename, embeddeddatabase='HSQLDB', registrationname='', calcfilename='')
def RunCommand(self, command, *args, **kwargs)
def SetStatusbar(self, text='', percentage=-1)
def CreateDocument(self, documenttype='', templatefile='', hidden=False)
def WindowExists(self, windowname)
def Activate(self, windowname='')
def GetDocument(self, windowname='')
def Minimize(self, windowname='')
def OpenDocument(self, filename, password='', readonly=False, hidden=False, macroexecution=MACROEXECNORMAL, filtername='', filteroptions='')
def __init__(self, reference=-1, objtype=None, classmodule=0, name='')
Definition: scriptforge.py:475
def __setattr__(self, name, value)
Definition: scriptforge.py:515
def GetProperty(self, propertyname, arg=None)
Definition: scriptforge.py:559
dictionary propertysynonyms
Definition: scriptforge.py:466
def SetProperty(self, propertyname, value)
Definition: scriptforge.py:587
def __getattr__(self, name)
Definition: scriptforge.py:488
def ExecMethod(self, flags=0, methodname='', *args)
Definition: scriptforge.py:553
def AddItem(self, menuitem, name='', icon='', tooltip='', command='', script='')
def AddRadioButton(self, menuitem, name='', status=False, icon='', tooltip='', command='', script='')
def AddCheckBox(self, menuitem, name='', status=False, icon='', tooltip='', command='', script='')
def ReviewServiceArgs(cls, event=None, x=0, y=0, submenuchar='')
def Execute(self, returnid=True)
def AddItem(self, menuitem, name='', icon='', tooltip='')
def AddCheckBox(self, menuitem, name='', status=False, icon='', tooltip='')
def AddRadioButton(self, menuitem, name='', status=False, icon='', tooltip='')
def ToolbarButtons(self, buttonname='')
def __init__(self, hostname='', port=0)
Definition: scriptforge.py:132
def InvokeBasicService(cls, basicobject, flags, method, *args)
Definition: scriptforge.py:266
def ScriptProvider(cls, context=None)
Definition: scriptforge.py:185
def ConnectToLOProcess(cls, hostname='', port=0)
Definition: scriptforge.py:156
def InvokeSimpleScript(cls, script, *args)
Definition: scriptforge.py:195
def __call__(cls, *args, **kwargs)
Definition: scriptforge.py:71
def CreateScriptService(service, *args, **kwargs)
def getComponentContext()
def createUnoStruct(typeName, *args, **kwargs)