scriptforge.py 131 KB

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