Version 6.4.0.0.beta1, tag libreoffice-6.4.0.0.beta1
[LibreOffice.git] / wizards / source / access2base / access2base.py
blobaf14a880cb3dc26fb3cf24e0a3d68e788f9933be
1 # -*- coding: utf-8 -*-
3 # Copyright 2012-2020 Jean-Pierre LEDURE
5 # =====================================================================================================================
6 # === The Access2Base library is a part of the LibreOffice project. ===
7 # === Full documentation is available on http://www.access2base.com ===
8 # =====================================================================================================================
10 # Access2Base is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 # Access2Base is free software; you can redistribute it and/or modify it under the terms of either (at your option):
16 # 1) The Mozilla Public License, v. 2.0. If a copy of the MPL was not
17 # distributed with this file, you can obtain one at http://mozilla.org/MPL/2.0/ .
19 # 2) The GNU Lesser General Public License as published by
20 # the Free Software Foundation, either version 3 of the License, or
21 # (at your option) any later version. If a copy of the LGPL was not
22 # distributed with this file, see http://www.gnu.org/licenses/ .
24 """
25 The access2base.py module implements an interface between Python (user) scripts and the Access2Base Basic library.
27 Usage:
28 from access2base import *
29 Additionally, if Python and LibreOffice are started in separate processes:
30 If LibreOffice started from console ... (example for Linux)
31 ./soffice --accept='socket,host=localhost,port=2019;urp;'
32 then insert next statement
33 A2BConnect(hostname = 'localhost', port = 2019)
35 Specific documentation about Access2Base and Python:
36 http://www.access2base.com/access2base.html#%5B%5BAccess2Base%20and%20Python%5D%5D
37 """
39 from __future__ import unicode_literals
41 import uno
42 XSCRIPTCONTEXT = uno
44 from platform import system as _opsys
45 import datetime, os, sys, traceback
47 _LIBRARY = '' # Should be 'Access2Base' or 'Access2BaseDev'
48 _VERSION = '6.4' # Actual version number
49 _WRAPPERMODULE = 'Python' # Module name in the Access2Base library containing Python interfaces
51 # CallByName types
52 _vbGet, _vbLet, _vbMethod, _vbSet, _vbUNO = 2, 4, 1, 8, 16
55 class _Singleton(type):
56 """
57 A Singleton design pattern
58 Credits: « Python in a Nutshell » by Alex Martelli, O'Reilly
59 """
60 instances = {}
61 def __call__(cls, *args, **kwargs):
62 if cls not in cls.instances:
63 cls.instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
64 return cls.instances[cls]
67 class acConstants(object, metaclass = _Singleton):
68 """
69 VBA constants used in the Access2Base API.
70 Values derived from MSAccess, except when conflicts
71 """
72 # Python special constants (used in the protocol between Python and Basic)
73 # -----------------------------------------------------------------
74 Empty = '+++EMPTY+++'
75 Null = '+++NULL+++'
76 Missing = '+++MISSING+++'
77 FromIsoFormat = '%Y-%m-%d %H:%M:%S' # To be used with datetime.datetime.strptime()
79 # AcCloseSave
80 # -----------------------------------------------------------------
81 acSaveNo = 2
82 acSavePrompt = 0
83 acSaveYes = 1
85 # AcFormView
86 # -----------------------------------------------------------------
87 acDesign = 1
88 acNormal = 0
89 acPreview = 2
91 # AcFormOpenDataMode
92 # -----------------------------------------------------------------
93 acFormAdd = 0
94 acFormEdit = 1
95 acFormPropertySettings = -1
96 acFormReadOnly = 2
98 # acView
99 # -----------------------------------------------------------------
100 acViewDesign = 1
101 acViewNormal = 0
102 acViewPreview = 2
104 # acOpenDataMode
105 # -----------------------------------------------------------------
106 acAdd = 0
107 acEdit = 1
108 acReadOnly = 2
110 # AcObjectType
111 # -----------------------------------------------------------------
112 acDefault = -1
113 acDiagram = 8
114 acForm = 2
115 acQuery = 1
116 acReport = 3
117 acTable = 0
118 # Unexisting in MS/Access
119 acBasicIDE = 101
120 acDatabaseWindow = 102
121 acDocument = 111
122 acWelcome = 112
123 # Subtype if acDocument
124 docWriter = "Writer"
125 docCalc = "Calc"
126 docImpress = "Impress"
127 docDraw = "Draw"
128 docMath = "Math"
130 # AcWindowMode
131 # -----------------------------------------------------------------
132 acDialog = 3
133 acHidden = 1
134 acIcon = 2
135 acWindowNormal = 0
137 # VarType constants
138 # -----------------------------------------------------------------
139 vbEmpty = 0
140 vbNull = 1
141 vbInteger = 2
142 vbLong = 3
143 vbSingle = 4
144 vbDouble = 5
145 vbCurrency = 6
146 vbDate = 7
147 vbString = 8
148 vbObject = 9
149 vbBoolean = 11
150 vbVariant = 12
151 vbByte = 17
152 vbUShort = 18
153 vbULong = 19
154 vbBigint = 35
155 vbDecimal = 37
156 vbArray = 8192
158 # MsgBox constants
159 # -----------------------------------------------------------------
160 vbOKOnly = 0 # OK button only (default)
161 vbOKCancel = 1 # OK and Cancel buttons
162 vbAbortRetryIgnore = 2 # Abort, Retry, and Ignore buttons
163 vbYesNoCancel = 3 # Yes, No, and Cancel buttons
164 vbYesNo = 4 # Yes and No buttons
165 vbRetryCancel = 5 # Retry and Cancel buttons
166 vbCritical = 16 # Critical message
167 vbQuestion = 32 # Warning query
168 vbExclamation = 48 # Warning message
169 vbInformation = 64 # Information message
170 vbDefaultButton1 = 128 # First button is default (default) (VBA: 0)
171 vbDefaultButton2 = 256 # Second button is default
172 vbDefaultButton3 = 512 # Third button is default
173 vbApplicationModal = 0 # Application modal message box (default)
174 # MsgBox Return Values
175 # -----------------------------------------------------------------
176 vbOK = 1 # OK button pressed
177 vbCancel = 2 # Cancel button pressed
178 vbAbort = 3 # Abort button pressed
179 vbRetry = 4 # Retry button pressed
180 vbIgnore = 5 # Ignore button pressed
181 vbYes = 6 # Yes button pressed
182 vbNo = 7 # No button pressed
184 # Dialogs Return Values
185 # ------------------------------------------------------------------
186 dlgOK = 1 # OK button pressed
187 dlgCancel = 0 # Cancel button pressed
189 # Control Types
190 # -----------------------------------------------------------------
191 acCheckBox = 5
192 acComboBox = 7
193 acCommandButton = 2
194 acToggleButton = 122
195 acCurrencyField = 18
196 acDateField = 15
197 acFileControl = 12
198 acFixedLine = 24 # FREE ENTRY (USEFUL IN DIALOGS)
199 acFixedText = 10
200 acLabel = 10
201 acFormattedField = 1 # FREE ENTRY TAKEN TO NOT CONFUSE WITH acTextField
202 acGridControl = 11
203 acGroupBox = 8
204 acOptionGroup = 8
205 acHiddenControl = 13
206 acImageButton = 4
207 acImageControl = 14
208 acImage = 14
209 acListBox = 6
210 acNavigationBar = 22
211 acNumericField = 17
212 acPatternField = 19
213 acProgressBar = 23 # FREE ENTRY (USEFUL IN DIALOGS)
214 acRadioButton = 3
215 acOptionButton = 3
216 acScrollBar = 20
217 acSpinButton = 21
218 acSubform = 112
219 acTextField = 9
220 acTextBox = 9
221 acTimeField = 16
223 # AcRecord
224 # -----------------------------------------------------------------
225 acFirst = 2
226 acGoTo = 4
227 acLast = 3
228 acNewRec = 5
229 acNext = 1
230 acPrevious = 0
232 # FindRecord
233 # -----------------------------------------------------------------
234 acAnywhere = 0
235 acEntire = 1
236 acStart = 2
237 acDown = 1
238 acSearchAll = 2
239 acUp = 0
240 acAll = 0
241 acCurrent = -1
243 # AcDataObjectType
244 # -----------------------------------------------------------------
245 acActiveDataObject = -1
246 acDataForm = 2
247 acDataQuery = 1
248 acDataServerView = 7
249 acDataStoredProcedure = 9
250 acDataTable = 0
252 # AcQuitOption
253 # -----------------------------------------------------------------
254 acQuitPrompt = 0
255 acQuitSaveAll = 1
256 acQuitSaveNone = 2
258 # AcCommand
259 # -----------------------------------------------------------------
260 acCmdAboutMicrosoftAccess = 35
261 acCmdAboutOpenOffice = 35
262 acCmdAboutLibreOffice = 35
263 acCmdVisualBasicEditor = 525
264 acCmdBringToFront = 52
265 acCmdClose = 58
266 acCmdToolbarsCustomize = 165
267 acCmdChangeToCommandButton = 501
268 acCmdChangeToCheckBox = 231
269 acCmdChangeToComboBox = 230
270 acCmdChangeToTextBox = 227
271 acCmdChangeToLabel = 228
272 acCmdChangeToImage = 234
273 acCmdChangeToListBox = 229
274 acCmdChangeToOptionButton = 233
275 acCmdCopy = 190
276 acCmdCut = 189
277 acCmdCreateRelationship = 150
278 acCmdDelete = 337
279 acCmdDatabaseProperties = 256
280 acCmdSQLView = 184
281 acCmdRemove = 366
282 acCmdDesignView = 183
283 acCmdFormView = 281
284 acCmdNewObjectForm = 136
285 acCmdNewObjectTable = 134
286 acCmdNewObjectView = 350
287 acCmdOpenDatabase = 25
288 acCmdNewObjectQuery = 135
289 acCmdShowAllRelationships = 149
290 acCmdNewObjectReport = 137
291 acCmdSelectAll = 333
292 acCmdRemoveTable = 84
293 acCmdOpenTable = 221
294 acCmdRename = 143
295 acCmdDeleteRecord = 223
296 acCmdApplyFilterSort = 93
297 acCmdSnapToGrid = 62
298 acCmdViewGrid = 63
299 acCmdInsertHyperlink = 259
300 acCmdMaximumRecords = 508
301 acCmdObjectBrowser = 200
302 acCmdPaste = 191
303 acCmdPasteSpecial = 64
304 acCmdPrint = 340
305 acCmdPrintPreview = 54
306 acCmdSaveRecord = 97
307 acCmdFind = 30
308 acCmdUndo = 292
309 acCmdRefresh = 18
310 acCmdRemoveFilterSort = 144
311 acCmdRunMacro = 31
312 acCmdSave = 20
313 acCmdSaveAs = 21
314 acCmdSelectAllRecords = 109
315 acCmdSendToBack = 53
316 acCmdSortDescending = 164
317 acCmdSortAscending = 163
318 acCmdTabOrder = 41
319 acCmdDatasheetView = 282
320 acCmdZoomSelection = 371
322 # AcSendObjectType
323 # -----------------------------------------------------------------
324 acSendForm = 2
325 acSendNoObject = -1
326 acSendQuery = 1
327 acSendReport = 3
328 acSendTable = 0
330 # AcOutputObjectType
331 # -----------------------------------------------------------------
332 acOutputTable = 0
333 acOutputQuery = 1
334 acOutputForm = 2
335 acOutputArray = -1
337 # AcEncoding
338 # -----------------------------------------------------------------
339 acUTF8Encoding = 76
341 # AcFormat
342 # -----------------------------------------------------------------
343 acFormatPDF = "writer_pdf_Export"
344 acFormatODT = "writer8"
345 acFormatDOC = "MS Word 97"
346 acFormatHTML = "HTML"
347 acFormatODS = "calc8"
348 acFormatXLS = "MS Excel 97"
349 acFormatXLSX = "Calc MS Excel 2007 XML"
350 acFormatTXT = "Text - txt - csv (StarCalc)"
352 # AcExportQuality
353 # -----------------------------------------------------------------
354 acExportQualityPrint = 0
355 acExportQualityScreen = 1
357 # AcSysCmdAction
358 # -----------------------------------------------------------------
359 acSysCmdAccessDir = 9
360 acSysCmdAccessVer = 7
361 acSysCmdClearHelpTopic = 11
362 acSysCmdClearStatus = 5
363 acSysCmdGetObjectState = 10
364 acSysCmdGetWorkgroupFile = 13
365 acSysCmdIniFile = 8
366 acSysCmdInitMeter = 1
367 acSysCmdProfile = 12
368 acSysCmdRemoveMeter = 3
369 acSysCmdRuntime = 6
370 acSysCmdSetStatus = 4
371 acSysCmdUpdateMeter = 2
373 # Type property
374 # -----------------------------------------------------------------
375 dbBigInt = 16
376 dbBinary = 9
377 dbBoolean = 1
378 dbByte = 2
379 dbChar = 18
380 dbCurrency = 5
381 dbDate = 8
382 dbDecimal = 20
383 dbDouble = 7
384 dbFloat = 21
385 dbGUID = 15
386 dbInteger = 3
387 dbLong = 4
388 dbLongBinary = 11 # (OLE Object)
389 dbMemo = 12
390 dbNumeric = 19
391 dbSingle = 6
392 dbText = 10
393 dbTime = 22
394 dbTimeStamp = 23
395 dbVarBinary = 17
396 dbUndefined = -1
398 # Attributes property
399 # -----------------------------------------------------------------
400 dbAutoIncrField = 16
401 dbDescending = 1
402 dbFixedField = 1
403 dbHyperlinkField = 32768
404 dbSystemField = 8192
405 dbUpdatableField = 32
406 dbVariableField = 2
408 # OpenRecordset
409 # -----------------------------------------------------------------
410 dbOpenForwardOnly = 8
411 dbSQLPassThrough = 64
412 dbReadOnly = 4
414 # Query types
415 # -----------------------------------------------------------------
416 dbQAction = 240
417 dbQAppend = 64
418 dbQDDL = 4 # 96
419 dbQDelete = 32
420 dbQMakeTable = 128 # 80
421 dbQSelect = 0
422 dbQSetOperation = 8 # 128
423 dbQSQLPassThrough = 1 # 112
424 dbQUpdate = 16 # 48
426 # Edit mode
427 # -----------------------------------------------------------------
428 dbEditNone = 0
429 dbEditInProgress = 1
430 dbEditAdd = 2
432 # Toolbars
433 # -----------------------------------------------------------------
434 msoBarTypeNormal = 0 # Usual toolbar
435 msoBarTypeMenuBar = 1 # Menu bar
436 msoBarTypePopup = 2 # Shortcut menu
437 msoBarTypeStatusBar = 11 # Status bar
438 msoBarTypeFloater = 12 # Floating window
440 msoControlButton = 1 # Command button
441 msoControlPopup = 10 # Popup, submenu
443 # New Lines
444 # -----------------------------------------------------------------
445 vbCr = chr(13)
446 vbLf = chr(10)
448 def _NewLine():
449 if _opsys == 'Windows': return chr(13) + chr(10)
450 return chr(10)
452 vbNewLine = _NewLine()
453 vbTab = chr(9)
455 # Module types
456 # -----------------------------------------------------------------
457 acClassModule = 1
458 acStandardModule = 0
460 # (Module) procedure types
461 # -----------------------------------------------------------------
462 vbext_pk_Get = 1 # A Property Get procedure
463 vbext_pk_Let = 2 # A Property Let procedure
464 vbext_pk_Proc = 0 # A Sub or Function procedure
465 vbext_pk_Set = 3 # A Property Set procedure
468 COMPONENTCONTEXT, DESKTOP, SCRIPTPROVIDER, THISDATABASEDOCUMENT = None, None, None, None
470 def _ErrorHandler(type, value, tb):
472 Is the function to be set as new sys.excepthook to bypass the standard error handler
473 Derived from https://stackoverflow.com/questions/31949760/how-to-limit-python-traceback-to-specific-files
474 Handler removes traces pointing to methods located in access2base.py when error is due to a user programming error
475 sys.excepthook = _ErrorHandler
476 NOT APPLIED YET
479 def check_file(name):
480 return 'access2base.py' not in name
482 show = (fs for fs in traceback.extract_tb(tb) if check_file(fs.filename))
483 fmt = traceback.format_list(show) + traceback.format_exception_only(type, value)
484 print(''.join(fmt), end = '', file = sys.stderr)
485 # Reset to standard handler
486 sys.excepthook = sys.__excepthook__
489 def A2BConnect(hostname = '', port = 0):
491 To be called explicitly by user scripts when Python process runs outside the LibreOffice process.
492 LibreOffice started as (Linux):
493 ./soffice --accept='socket,host=localhost,port=xxxx;urp;'
494 Otherwise called implicitly by the current module without arguments
495 Initializes COMPONENTCONTEXT, SCRIPTPROVIDER and DESKTOP
496 :param hostname: probably 'localhost' or ''
497 :param port: port number or 0
498 :return: None
500 global XSCRIPTCONTEXT, COMPONENTCONTEXT, DESKTOP, SCRIPTPROVIDER
501 # Determine COMPONENTCONTEXT, via socket or inside LibreOffice
502 if len(hostname) > 0 and port > 0: # Explicit connection request via socket
503 # Code derived from Bridge.py by Alain H. Romedenne
504 local_context = XSCRIPTCONTEXT.getComponentContext()
505 resolver = local_context.ServiceManager.createInstanceWithContext(
506 'com.sun.star.bridge.UnoUrlResolver', local_context)
507 try:
508 conn = 'socket,host=%s,port=%d' % (hostname, port)
509 connection_url = 'uno:%s;urp;StarOffice.ComponentContext' % conn
510 established_context = resolver.resolve(connection_url)
511 except Exception: # thrown when LibreOffice specified instance isn't started
512 raise ConnectionError('Connection to LibreOffice failed (host = ' + hostname + ', port = ' + str(port) + ')')
513 COMPONENTCONTEXT = established_context
514 DESKTOP = None
515 elif len(hostname) == 0 and port == 0: # Usual interactive mode
516 COMPONENTCONTEXT = XSCRIPTCONTEXT.getComponentContext()
517 DESKTOP = COMPONENTCONTEXT.ServiceManager.createInstanceWithContext( 'com.sun.star.frame.Desktop', COMPONENTCONTEXT)
518 else:
519 raise SystemExit('The invocation of A2BConnect() has invalid arguments')
520 # Determine SCRIPTPROVIDER
521 servicemanager = COMPONENTCONTEXT.ServiceManager
522 masterscript = servicemanager.createInstanceWithContext("com.sun.star.script.provider.MasterScriptProviderFactory", COMPONENTCONTEXT)
523 SCRIPTPROVIDER = masterscript.createScriptProvider("")
524 Script = _A2B.xScript('TraceLog', 'Trace') # Don't use invokeMethod() to force reset of error stack
525 Script.invoke(('===>', 'Python wrapper loaded V.' + _VERSION, False), (), ())
526 return None
529 class _A2B(object, metaclass = _Singleton):
531 Collection of helper functions implementing the protocol between Python and Basic
532 Read comments in PythonWrapper Basic function
535 @classmethod
536 def BasicObject(cls, objectname):
537 objs = {'COLLECTION': _Collection
538 , 'COMMANDBAR': _CommandBar
539 , 'COMMANDBARCONTROL': _CommandBarControl
540 , 'CONTROL': _Control
541 , 'DATABASE': _Database
542 , 'DIALOG': _Dialog
543 , 'EVENT': _Event
544 , 'FIELD': _Field
545 , 'FORM': _Form
546 , 'MODULE': _Module
547 , 'OPTIONGROUP': _OptionGroup
548 , 'PROPERTY': _Property
549 , 'QUERYDEF': _QueryDef
550 , 'RECORDSET': _Recordset
551 , 'SUBFORM': _SubForm
552 , 'TABLEDEF': _TableDef
553 , 'TEMPVAR': _TempVar
555 return objs[objectname]
557 @classmethod
558 def xScript(cls, script, module):
560 At first call checks the existence of the Access2Base library
561 Initializes _LIBRARY with the found library name
562 First and next calls execute the given script in the given module of the _LIBRARY library
563 The script and module are presumed to exist
564 :param script: name of script
565 :param module: name of module
566 :return: the script object. NB: the execution is done with the invoke() method applied on the returned object
568 global _LIBRARY
569 Script = None
570 def sScript(lib):
571 return 'vnd.sun.star.script:' + lib + '.' + module + '.' + script + '?language=Basic&location=application'
572 if _LIBRARY == '':
573 # Check the availability of the Access2Base library
574 for lib in ('Access2BaseDev', 'Access2Base'):
575 try:
576 if Script == None:
577 Script = SCRIPTPROVIDER.getScript(sScript(lib))
578 _LIBRARY = lib
579 except Exception:
580 pass
581 if Script == None:
582 raise SystemExit('Access2Base basic library not found')
583 else:
584 Script = SCRIPTPROVIDER.getScript(sScript(_LIBRARY))
585 return Script
587 @classmethod
588 def A2BErrorCode(cls):
590 Return the Access2Base error stack as a tuple
591 0 => error code
592 1 => severity level
593 2 => short error message
594 3 => long error message
596 Script = cls.xScript('TraceErrorCode', 'Trace')
597 return Script.invoke((), (), ())[0]
599 @classmethod
600 def invokeMethod(cls, script, module, *args):
602 Direct call to a named script/module pair with their arguments
603 If the arguments do not match their definition at the Basic side, a TypeError is raised
604 :param script: name of script
605 :param module: name of module
606 :param args: list of arguments to be passed to the script
607 :return: the value returned by the script execution
609 if COMPONENTCONTEXT == None: A2BConnect() # Connection from inside LibreOffice is done at first API invocation
610 Script = cls.xScript(script, module)
611 try:
612 Returned = Script.invoke((args), (), ())[0]
613 except:
614 raise TypeError("Access2Base error: method '" + script + "' in Basic module '" + module + "' call error. Check its arguments.")
615 else:
616 if Returned == None:
617 if cls.VerifyNoError(): return None
618 return Returned
620 @classmethod
621 def invokeWrapper(cls, action, basic, script, *args):
623 Call the Basic wrapper to invite it to execute the proposed action on a Basic object
624 If the arguments do not match their definition at the Basic side, a TypeError is raised
625 After execution, a check is done if the execution has raised an error within Basic
626 If yes, a TypeError is raised
627 :param action: Property Get, Property Let, Property Set, invoke Method or return UNO object
628 :param basic: the reference of the Basic object, i.e. the index in the array caching the addresses of the objects
629 conventionally Application = -1 and DoCmd = -2
630 :param script: the property or method name
631 :param args: the arguments of the method, if any
632 :return: the value returned by the execution of the Basic routine
634 if COMPONENTCONTEXT == None: A2BConnect() # Connection from inside LibreOffice is done at first API invocation
635 # Intercept special call to Application.Events()
636 if basic == Application.basicmodule and script == 'Events':
637 Script = cls.xScript('PythonEventsWrapper', _WRAPPERMODULE)
638 Returned = Script.invoke((args[0],), (), ())
639 else:
640 Script = cls.xScript('PythonWrapper', _WRAPPERMODULE)
641 NoArgs = '+++NOARGS+++' # Conventional notation for properties/methods without arguments
642 if len(args) == 0:
643 args = (action,) + (basic,) + (script,) + (NoArgs,)
644 else:
645 args = (action,) + (basic,) + (script,) + args
646 try:
647 Returned = Script.invoke((args), (), ())
648 except:
649 raise TypeError("Access2Base error: method '" + script + "' call error. Check its arguments.")
651 if isinstance(Returned[0], tuple):
652 # Is returned value a reference to a basic object, a scalar or a UNO object ?
653 if len(Returned[0]) in (3, 4):
654 if Returned[0][0] == 0: # scalar
655 return Returned[0][1]
656 elif Returned[0][0] == 1: # reference to objects cache
657 basicobject = cls.BasicObject(Returned[0][2])
658 if len(Returned[0]) == 3:
659 return basicobject(Returned[0][1], Returned[0][2])
660 else:
661 return basicobject(Returned[0][1], Returned[0][2], Returned[0][3])
662 elif Returned[0][0] == 2: # Null value
663 return None
664 else: # Should not happen
665 return None
666 else: # UNO object
667 return Returned[0]
668 elif Returned[0] == None:
669 if cls.VerifyNoError(): return None
670 else: # Should not happen
671 return Returned[0]
673 @classmethod
674 def VerifyNoError(cls):
675 # has Access2Base generated an error ?
676 errorstack = cls.A2BErrorCode() # 0 = code, 1 = severity, 2 = short text, 3 = long text
677 if errorstack[1] in ('ERROR', 'FATAL', 'ABORT'):
678 raise TypeError('Access2Base error: ' + errorstack[3])
679 return True
682 class Application(object, metaclass = _Singleton):
683 """ Collection of methods located in the Application (Basic) module """
684 W = _A2B.invokeWrapper
685 basicmodule = -1
687 @classmethod
688 def AllDialogs(cls, dialog = acConstants.Missing):
689 return cls.W(_vbMethod, cls.basicmodule, 'AllDialogs', dialog)
690 @classmethod
691 def AllForms(cls, form = acConstants.Missing):
692 return cls.W(_vbMethod, cls.basicmodule, 'AllForms', form)
693 @classmethod
694 def AllModules(cls, module = acConstants.Missing):
695 return cls.W(_vbMethod, cls.basicmodule, 'AllModules', module)
696 @classmethod
697 def CloseConnection(cls):
698 return cls.W(_vbMethod, cls.basicmodule, 'CloseConnection')
699 @classmethod
700 def CommandBars(cls, bar = acConstants.Missing):
701 return cls.W(_vbMethod, cls.basicmodule, 'CommandBars', bar)
702 @classmethod
703 def CurrentDb(cls):
704 return cls.W(_vbMethod, cls.basicmodule, 'CurrentDb')
705 @classmethod
706 def CurrentUser(cls):
707 return cls.W(_vbMethod, cls.basicmodule, 'CurrentUser')
708 @classmethod
709 def DAvg(cls, expression, domain, criteria = ''):
710 return cls.W(_vbMethod, cls.basicmodule, 'DAvg', expression, domain, criteria)
711 @classmethod
712 def DCount(cls, expression, domain, criteria = ''):
713 return cls.W(_vbMethod, cls.basicmodule, 'DCount', expression, domain, criteria)
714 @classmethod
715 def DLookup(cls, expression, domain, criteria = '', orderclause = ''):
716 return cls.W(_vbMethod, cls.basicmodule, 'DLookup', expression, domain, criteria, orderclause)
717 @classmethod
718 def DMax(cls, expression, domain, criteria = ''):
719 return cls.W(_vbMethod, cls.basicmodule, 'DMax', expression, domain, criteria)
720 @classmethod
721 def DMin(cls, expression, domain, criteria = ''):
722 return cls.W(_vbMethod, cls.basicmodule, 'DMin', expression, domain, criteria)
723 @classmethod
724 def DStDev(cls, expression, domain, criteria = ''):
725 return cls.W(_vbMethod, cls.basicmodule, 'DStDev', expression, domain, criteria)
726 @classmethod
727 def DStDevP(cls, expression, domain, criteria = ''):
728 return cls.W(_vbMethod, cls.basicmodule, 'DStDevP', expression, domain, criteria)
729 @classmethod
730 def DSum(cls, expression, domain, criteria = ''):
731 return cls.W(_vbMethod, cls.basicmodule, 'DSum', expression, domain, criteria)
732 @classmethod
733 def DVar(cls, expression, domain, criteria = ''):
734 return cls.W(_vbMethod, cls.basicmodule, 'DVar', expression, domain, criteria)
735 @classmethod
736 def DVarP(cls, expression, domain, criteria = ''):
737 return cls.W(_vbMethod, cls.basicmodule, 'DVarP', expression, domain, criteria)
738 @classmethod
739 def Events(cls, event):
740 return cls.W(_vbMethod, cls.basicmodule, 'Events', event)
741 @classmethod
742 def Forms(cls, form = acConstants.Missing):
743 return cls.W(_vbMethod, cls.basicmodule, 'Forms', form)
744 @classmethod
745 def getObject(cls, shortcut):
746 return cls.W(_vbMethod, cls.basicmodule, 'getObject', shortcut)
747 GetObject = getObject
748 @classmethod
749 def getValue(cls, shortcut):
750 return cls.W(_vbMethod, cls.basicmodule, 'getValue', shortcut)
751 GetValue = getValue
752 @classmethod
753 def HtmlEncode(cls, string, length = 0):
754 return cls.W(_vbMethod, cls.basicmodule, 'HtmlEncode', string, length)
755 @classmethod
756 def OpenConnection(cls, thisdatabasedocument = acConstants.Missing):
757 global THISDATABASEDOCUMENT
758 if COMPONENTCONTEXT == None: A2BConnect() # Connection from inside LibreOffice is done at first API invocation
759 if DESKTOP != None:
760 THISDATABASEDOCUMENT = DESKTOP.getCurrentComponent()
761 return _A2B.invokeMethod('OpenConnection', 'Application', THISDATABASEDOCUMENT)
762 @classmethod
763 def OpenDatabase(cls, connectionstring, username = '', password = '', readonly = False):
764 return cls.W(_vbMethod, cls.basicmodule, 'OpenDatabase', connectionstring, username
765 , password, readonly)
766 @classmethod
767 def ProductCode(cls):
768 return cls.W(_vbMethod, cls.basicmodule, 'ProductCode')
769 @classmethod
770 def setValue(cls, shortcut, value):
771 return cls.W(_vbMethod, cls.basicmodule, 'setValue', shortcut, value)
772 SetValue = setValue
773 @classmethod
774 def SysCmd(cls, action, text = '', value = -1):
775 return cls.W(_vbMethod, cls.basicmodule, 'SysCmd', action, text, value)
776 @classmethod
777 def TempVars(cls, var = acConstants.Missing):
778 return cls.W(_vbMethod, cls.basicmodule, 'TempVars', var)
779 @classmethod
780 def Version(cls):
781 return cls.W(_vbMethod, cls.basicmodule, 'Version')
784 class DoCmd(object, metaclass = _Singleton):
785 """ Collection of methods located in the DoCmd (Basic) module """
786 W = _A2B.invokeWrapper
787 basicmodule = -2
789 @classmethod
790 def ApplyFilter(cls, filter = '', sqlwhere = '', controlname = ''):
791 return cls.W(_vbMethod, cls.basicmodule, 'ApplyFilter', filter, sqlwhere, controlname)
792 @classmethod
793 def Close(cls, objecttype, objectname, save = acConstants.acSavePrompt):
794 return cls.W(_vbMethod, cls.basicmodule, 'Close', objecttype, objectname, save)
795 @classmethod
796 def CopyObject(cls, sourcedatabase, newname, sourceobjecttype, sourceobjectname): # 1st argument must be set
797 return cls.W(_vbMethod, cls.basicmodule, 'CopyObject', sourcedatabase, newname, sourceobjecttype
798 , sourceobjectname)
799 @classmethod
800 def FindNext(cls):
801 return cls.W(_vbMethod, cls.basicmodule, 'FindNext')
802 @classmethod
803 def FindRecord(cls, findwhat, match = acConstants.acEntire, matchcase = False, search = acConstants.acSearchAll
804 , searchasformatted = False, onlycurrentfield = acConstants.acCurrent, findfirst = True):
805 return cls.W(_vbMethod, cls.basicmodule, 'FindRecord', findwhat, match, matchcase, search
806 , searchasformatted, onlycurrentfield, findfirst)
807 @classmethod
808 def GetHiddenAttribute(cls, objecttype, objectname = ''):
809 return cls.W(_vbMethod, cls.basicmodule, 'GetHiddenAttribute', objecttype, objectname)
810 @classmethod
811 def GoToControl(cls, controlname):
812 return cls.W(_vbMethod, cls.basicmodule, 'GoToControl', controlname)
813 @classmethod
814 def GoToRecord(cls, objecttype = acConstants.acActiveDataObject, objectname = '', record = acConstants.acNext
815 , offset = 1):
816 return cls.W(_vbMethod, cls.basicmodule, 'GoToRecord', objecttype, objectname, record, offset)
817 @classmethod
818 def Maximize(cls):
819 return cls.W(_vbMethod, cls.basicmodule, 'Maximize')
820 @classmethod
821 def Minimize(cls):
822 return cls.W(_vbMethod, cls.basicmodule, 'Minimize')
823 @classmethod
824 def MoveSize(cls, left = -1, top = -1, width = -1, height = -1):
825 return cls.W(_vbMethod, cls.basicmodule, 'MoveSize', left, top, width, height)
826 @classmethod
827 def OpenForm(cls, formname, view = acConstants.acNormal, filter = '', wherecondition = ''
828 , datamode = acConstants.acFormEdit, windowmode = acConstants.acWindowNormal, openargs = ''):
829 return cls.W(_vbMethod, cls.basicmodule, 'OpenForm', formname, view, filter, wherecondition
830 , datamode, windowmode, openargs)
831 @classmethod
832 def OpenQuery(cls, queryname, view = acConstants.acNormal, datamode = acConstants.acEdit):
833 return cls.W(_vbMethod, cls.basicmodule, 'OpenQuery', queryname, view, datamode)
834 @classmethod
835 def OpenReport(cls, queryname, view = acConstants.acNormal):
836 return cls.W(_vbMethod, cls.basicmodule, 'OpenReport', queryname, view)
837 @classmethod
838 def OpenSQL(cls, sql, option = -1):
839 return cls.W(_vbMethod, cls.basicmodule, 'OpenSQL', sql, option)
840 @classmethod
841 def OpenTable(cls, tablename, view = acConstants.acNormal, datamode = acConstants.acEdit):
842 return cls.W(_vbMethod, cls.basicmodule, 'OpenTable', tablename, view, datamode)
843 @classmethod
844 def OutputTo(cls, objecttype, objectname = '', outputformat = '', outputfile = '', autostart = False, templatefile = ''
845 , encoding = acConstants.acUTF8Encoding, quality = acConstants.acExportQualityPrint):
846 if objecttype == acConstants.acOutputForm: encoding = 0
847 return cls.W(_vbMethod, cls.basicmodule, 'OutputTo', objecttype, objectname, outputformat
848 , outputfile, autostart, templatefile, encoding, quality)
849 @classmethod
850 def Quit(cls):
851 return cls.W(_vbMethod, cls.basicmodule, 'Quit')
852 @classmethod
853 def RunApp(cls, commandline):
854 return cls.W(_vbMethod, cls.basicmodule, 'RunApp', commandline)
855 @classmethod
856 def RunCommand(cls, command):
857 return cls.W(_vbMethod, cls.basicmodule, 'RunCommand', command)
858 @classmethod
859 def RunSQL(cls, SQL, option = -1):
860 return cls.W(_vbMethod, cls.basicmodule, 'RunSQL', SQL, option)
861 @classmethod
862 def SelectObject(cls, objecttype, objectname = '', indatabasewindow = False):
863 return cls.W(_vbMethod, cls.basicmodule, 'SelectObject', objecttype, objectname, indatabasewindow)
864 @classmethod
865 def SendObject(cls, objecttype = acConstants.acSendNoObject, objectname = '', outputformat = '', to = '', cc = ''
866 , bcc = '', subject = '', messagetext = '', editmessage = True, templatefile = ''):
867 return cls.W(_vbMethod, cls.basicmodule, 'SendObject', objecttype, objectname, outputformat, to, cc
868 , bcc, subject, messagetext, editmessage, templatefile)
869 @classmethod
870 def SetHiddenAttribute(cls, objecttype, objectname = '', hidden = True):
871 return cls.W(_vbMethod, cls.basicmodule, 'SetHiddenAttribute', objecttype, objectname, hidden)
872 @classmethod
873 def SetOrderBy(cls, orderby = '', controlname = ''):
874 return cls.W(_vbMethod, cls.basicmodule, 'SetOrderBy', orderby, controlname)
875 @classmethod
876 def ShowAllRecords(cls):
877 return cls.W(_vbMethod, cls.basicmodule, 'ShowAllRecords')
880 class Basic(object, metaclass = _Singleton):
881 """ Collection of helper functions having the same behaviour as their Basic counterparts """
882 M = _A2B.invokeMethod
884 @classmethod
885 def ConvertFromUrl(cls, url):
886 return cls.M('PyConvertFromUrl', _WRAPPERMODULE, url)
888 @classmethod
889 def ConvertToUrl(cls, file):
890 return cls.M('PyConvertToUrl', _WRAPPERMODULE, file)
892 @classmethod
893 def CreateUnoService(cls, servicename):
894 return cls.M('PyCreateUnoService', _WRAPPERMODULE, servicename)
896 @classmethod
897 def DateAdd(cls, add, count, datearg):
898 if isinstance(datearg, datetime.datetime): datearg = datearg.isoformat()
899 dateadd = cls.M('PyDateAdd', _WRAPPERMODULE, add, count, datearg)
900 return datetime.datetime.strptime(dateadd, acConstants.FromIsoFormat)
902 @classmethod
903 def DateDiff(cls, add, date1, date2, weekstart = 1, yearstart = 1):
904 if isinstance(date1, datetime.datetime): date1 = date1.isoformat()
905 if isinstance(date2, datetime.datetime): date2 = date1.isoformat()
906 return cls.M('PyDateDiff', _WRAPPERMODULE, add, date1, date2, weekstart, yearstart)
908 @classmethod
909 def DatePart(cls, add, datearg, weekstart = 1, yearstart = 1):
910 if isinstance(datearg, datetime.datetime): datearg = datearg.isoformat()
911 return cls.M('PyDatePart', _WRAPPERMODULE, add, datearg, weekstart, yearstart)
913 @classmethod
914 def DateValue(cls, datestring):
915 datevalue = cls.M('PyDateValue', _WRAPPERMODULE, datestring)
916 return datetime.datetime.strptime(datevalue, acConstants.FromIsoFormat)
918 @classmethod
919 def Format(cls, value, format = None):
920 if isinstance(value, (datetime.datetime, datetime.date, datetime.time, )):
921 value = value.isoformat()
922 return cls.M('PyFormat', _WRAPPERMODULE, value, format)
924 @classmethod
925 def GetGUIType(cls):
926 return cls.M('PyGetGUIType', _WRAPPERMODULE)
928 @staticmethod
929 def GetPathSeparator():
930 return os.sep
932 @classmethod
933 def GetSystemTicks(cls):
934 return cls.M('PyGetSystemTicks', _WRAPPERMODULE)
936 @classmethod
937 def MsgBox(cls, text, type = None, dialogtitle = None):
938 return cls.M('PyMsgBox', _WRAPPERMODULE, text, type, dialogtitle)
940 class GlobalScope(object, metaclass = _Singleton):
941 @classmethod
942 def BasicLibraries(cls):
943 return Basic.M('PyGlobalScope', _WRAPPERMODULE, 'Basic')
944 @classmethod
945 def DialogLibraries(self):
946 return Basic.M('PyGlobalScope', _WRAPPERMODULE, 'Dialog')
948 @classmethod
949 def InputBox(cls, text, title = None, default = None, xpos = None, ypos = None):
950 return cls.M('PyInputBox', _WRAPPERMODULE, text, title, default, xpos, ypos)
952 @staticmethod
953 def Now():
954 return datetime.datetime.now()
956 @staticmethod
957 def RGB(red, green, blue):
958 return int('%02x%02x%02x' % (red, green, blue), 16)
960 @classmethod
961 def Timer(cls):
962 return cls.M('PyTimer', _WRAPPERMODULE)
964 @staticmethod
965 def Xray(myObject):
966 xrayscript = 'vnd.sun.star.script:XrayTool._Main.Xray?language=Basic&location=application'
967 xScript = SCRIPTPROVIDER.getScript(xrayscript)
968 xScript.invoke((myObject,), (), ())
969 return
972 class _BasicObject(object):
974 Parent class of Basic objects
975 Each subclass is identified by its classProperties:
976 dictionary with keys = allowed properties, value = True if editable or False
977 Each instance is identified by its
978 - reference in the cache managed by Basic
979 - type ('DATABASE', 'COLLECTION', ...)
980 - name (form, control, ... name) - may be blank
981 Properties are got and set following next strategy:
982 1. Property names are controlled strictly ('Value' and not 'value')
983 2. Getting a property value for the first time is always done via a Basic call
984 3. Next occurrences are fetched from the Python dictionary of the instance if the property is read-only, otherwise via a Basic call
985 4. Methods output might force the deletion of a property from the dictionary ('MoveNext' changes 'BOF' and 'EOF' properties)
986 5. Setting a property value is done via a Basic call, except if self.internal == True
988 W = _A2B.invokeWrapper
989 internal_attributes = ('objectreference', 'objecttype', 'name', 'internal')
991 def __init__(self, reference = -1, objtype = None, name = ''):
992 self.objectreference = reference # reference in the cache managed by Basic
993 self.objecttype = objtype # ('DATABASE', 'COLLECTION', ...)
994 self.name = name # '' when no name
995 self.internal = False # True to exceptionally allow assigning a new value to a read-only property
996 self.localProperties = ()
998 def __getattr__(self, name):
999 if name in ('classProperties', 'localProperties'):
1000 pass
1001 elif name in self.classProperties:
1002 # Get Property from Basic
1003 return self.W(_vbGet, self.objectreference, name)
1004 # Usual attributes getter
1005 return super(_BasicObject, self).__getattribute__(name)
1007 def __setattr__(self, name, value):
1008 if name in ('classProperties', 'localProperties'):
1009 pass
1010 elif name in self.classProperties:
1011 if self.internal: # internal = True forces property setting even if property is read-only
1012 pass
1013 elif self.classProperties[name] == True: # True == Editable
1014 self.W(_vbLet, self.objectreference, name, value)
1015 else:
1016 raise AttributeError("type object '" + self.objecttype + "' has no editable attribute '" + name + "'")
1017 elif name[0:2] == '__' or name in self.internal_attributes or name in self.localProperties:
1018 pass
1019 else:
1020 raise AttributeError("type object '" + self.objecttype + "' has no attribute '" + name + "'")
1021 object.__setattr__(self, name, value)
1022 return
1024 def __repr__(self):
1025 repr = "Basic object (type='" + self.objecttype + "', index=" + str(self.objectreference)
1026 if len(self.name) > 0: repr += ", name='" + self.name + "'"
1027 return repr + ")"
1029 def _Reset(self, propertyname, basicreturn = None):
1030 """ force new value or erase properties from dictionary (done to optimize calls to Basic scripts) """
1031 if propertyname in ('BOF', 'EOF'):
1032 # After a Move method invocation on a Recordset object, BOF or EOF likely to be got soon
1033 if isinstance(basicreturn, int):
1034 self.internal = True
1035 # f.i. basicreturn = 0b10 means: BOF = True, EOF = False
1036 self.BOF = basicreturn in (2, 3, -2, -3)
1037 self.EOF = basicreturn in (1, 3, -1, -3)
1038 self.internal = False
1039 return ( basicreturn >= 0 )
1040 else:
1041 # Suppress possibly invalid property values: e.g. RecordCount after Delete applied on Recordset object
1042 if property in self.__dict__:
1043 del(self.propertyname)
1044 return basicreturn
1046 @property
1047 def Name(self): return self.name
1048 @property
1049 def ObjectType(self): return self.objecttype
1051 def Dispose(self):
1052 return self.W(_vbMethod, self.objectreference, 'Dispose')
1053 def getProperty(self, propertyname, index = acConstants.Missing):
1054 return self.W(_vbMethod, self.objectreference, 'getProperty', propertyname, index)
1055 GetProperty = getProperty
1056 def hasProperty(self, propertyname):
1057 return propertyname in tuple(self.classProperties.keys())
1058 HasProperty = hasProperty
1059 def Properties(self, index = acConstants.Missing):
1060 return self.W(_vbMethod, self.objectreference, 'Properties', index)
1061 def setProperty(self, propertyname, value, index = acConstants.Missing):
1062 if self.hasProperty(propertyname):
1063 if self.W(_vbMethod, self.objectreference, 'setProperty', propertyname, value, index):
1064 return self.__setattr__(propertyname, value)
1065 raise AttributeError("type object '" + self.objecttype + "' has no editable attribute '" + propertyname + "'")
1066 SetProperty = setProperty
1069 class _Collection(_BasicObject):
1070 """ Collection object built as a Python iterator """
1071 classProperties = dict(Count = False)
1072 def __init__(self, reference = -1, objtype = None):
1073 super().__init__(reference, objtype)
1074 self.localProperties = ('count', 'index')
1075 self.count = self.Count
1076 self.index = 0
1077 def __iter__(self):
1078 self.index = 0
1079 return self
1080 def __next__(self):
1081 if self.index >= self.count:
1082 raise StopIteration
1083 next = self.Item(self.index)
1084 self.index = self.index + 1
1085 return next
1086 def __len__(self):
1087 return self.count
1089 def Add(self, table, value = acConstants.Missing):
1090 if isinstance(table, _BasicObject): # Add method applied to a TABLEDEFS collection
1091 return self.W(_vbMethod, self.objectreference, 'Add', table.objectreference)
1092 else: # Add method applied to a TEMPVARS collection
1093 add = self.W(_vbMethod, self.objectreference, 'Add', table, value)
1094 self.count = self.Count
1095 return add
1096 def Delete(self, name):
1097 return self.W(_vbMethod, self.objectreference, 'Delete', name)
1098 def Item(self, index):
1099 return self.W(_vbMethod, self.objectreference, 'Item', index)
1100 def Remove(self, tempvarname):
1101 remove = self.W(_vbMethod, self.objectreference, 'Remove', tempvarname)
1102 self.count = self.Count
1103 return remove
1104 def RemoveAll(self):
1105 remove = self.W(_vbMethod, self.objectreference, 'RemoveAll')
1106 self.count = self.Count
1107 return remove
1110 class _CommandBar(_BasicObject):
1111 classProperties = dict(BuiltIn = False, Parent = False, Visible = True)
1113 def CommandBarControls(self, index = acConstants.Missing):
1114 return self.W(_vbMethod, self.objectreference, 'CommandBarControls', index)
1115 def Reset(self):
1116 return self.W(_vbMethod, self.objectreference, 'Reset')
1119 class _CommandBarControl(_BasicObject):
1120 classProperties = dict(BeginGroup = False, BuiltIn = False, Caption = True, Index = False, OnAction = True
1121 , Parent = False, TooltipText = True, Type = False, Visible = True)
1123 def Execute(self):
1124 return self.W(_vbMethod, self.objectreference, 'Execute')
1127 class _Control(_BasicObject):
1128 classProperties = dict(BackColor = True, BorderColor = True, BorderStyle = True, Cancel = True, Caption = True
1129 , ControlSource = False, ControlTipText = True, ControlType = False, Default = True
1130 , DefaultValue = True, Enabled = True, FontBold = True, FontItalic = True, FontName = True
1131 , FontSize = True, FontUnderline = True, FontWeight = True, ForeColor = True, Form = False
1132 , Format = True, ItemData = False, ListCount = False, ListIndex = True, Locked = True, MultiSelect = True
1133 , OnActionPerformed = True, OnAdjustmentValueChanged = True, OnApproveAction = True
1134 , OnApproveReset = True, OnApproveUpdate = True, OnChanged = True, OnErrorOccurred = True
1135 , OnFocusGained = True, OnFocusLost = True, OnItemStateChanged = True, OnKeyPressed = True
1136 , OnKeyReleased = True, OnMouseDragged = True, OnMouseEntered = True, OnMouseExited = True
1137 , OnMouseMoved = True, OnMousePressed = True, OnMouseReleased = True, OnResetted = True, OnTextChanged = True
1138 , OnUpdated = True, OptionValue = False, Page = False, Parent = False, Picture = True, Required = True
1139 , RowSource = True, RowSourceType = True, Selected = True, SelLength = True, SelStart = True, SelText = True
1140 , SubType = False, TabIndex = True, TabStop = True, Tag = True, Text = False, TextAlign = True
1141 , TripleState = True, Value = True, Visible = True
1144 @property
1145 def BoundField(self): return self.W(_vbUNO, self.objectreference, 'BoundField')
1146 @property
1147 def ControlModel(self): return self.W(_vbUNO, self.objectreference, 'ControlModel')
1148 @property
1149 def ControlView(self): return self.W(_vbUNO, self.objectreference, 'ControlView')
1150 @property
1151 def LabelControl(self): return self.W(_vbUNO, self.objectreference, 'LabelControl')
1153 def AddItem(self, value, index = -1):
1154 basicreturn = self.W(_vbMethod, self.objectreference, 'AddItem', value, index)
1155 self._Reset('ItemData')
1156 self._Reset('ListCount')
1157 return basicreturn
1158 def Controls(self, index = acConstants.Missing):
1159 return self.W(_vbMethod, self.objectreference, 'Controls', index)
1160 # Overrides method in parent class: list of properties is strongly control type dependent
1161 def hasProperty(self, propertyname):
1162 return self.W(_vbMethod, self.objectreference, 'hasProperty', propertyname)
1163 HasProperty = hasProperty
1164 def RemoveItem(self, index):
1165 basicreturn = self.W(_vbMethod, self.objectreference, 'RemoveItem', index)
1166 self._Reset('ItemData')
1167 self._Reset('ListCount')
1168 return basicreturn
1169 def Requery(self):
1170 return self.W(_vbMethod, self.objectreference, 'Requery')
1171 def SetSelected(self, value, index):
1172 return self.W(_vbMethod, self.objectreference, 'SetSelected', value, index)
1173 def SetFocus(self):
1174 return self.W(_vbMethod, self.objectreference, 'SetFocus')
1177 class _Database(_BasicObject):
1178 classProperties = dict(Connect = False, OnCreate = True
1179 , OnFocus = True, OnLoad = True, OnLoadFinished = True, OnModifyChanged = True, OnNew = True
1180 , OnPrepareUnload = True, OnPrepareViewClosing = True, OnSave = True, OnSaveAs = True
1181 , OnSaveAsDone = True, OnSaveAsFailed = True, OnSaveDone = True, OnSaveFailed = True
1182 , OnSubComponentClosed = True, OnSubComponentOpened = True, OnTitleChanged = True, OnUnfocus = True
1183 , OnUnload = True, OnViewClosed = True, OnViewCreated = True, Version = False
1186 @property
1187 def Connection(self): return self.W(_vbUNO, self.objectreference, 'Connection')
1188 @property
1189 def Document(self): return self.W(_vbUNO, self.objectreference, 'Document')
1190 @property
1191 def MetaData(self): return self.W(_vbUNO, self.objectreference, 'MetaData')
1193 def Close(self):
1194 return self.W(_vbMethod, self.objectreference, 'Close')
1195 def CloseAllRecordsets(self):
1196 return self.W(_vbMethod, self.objectreference, 'CloseAllRecordsets')
1197 def CreateQueryDef(self, name, sqltext, option = -1):
1198 return self.W(_vbMethod, self.objectreference, 'CreateQueryDef', name, sqltext, option)
1199 def CreateTableDef(self, name):
1200 return self.W(_vbMethod, self.objectreference, 'CreateTableDef', name)
1201 def DAvg(self, expression, domain, criteria = ''):
1202 return self.W(_vbMethod, self.objectreference, 'DAvg', expression, domain, criteria)
1203 def DCount(self, expression, domain, criteria = ''):
1204 return self.W(_vbMethod, self.objectreference, 'DCount', expression, domain, criteria)
1205 def DLookup(self, expression, domain, criteria = '', orderclause = ''):
1206 return self.W(_vbMethod, self.objectreference, 'DLookup', expression, domain, criteria, orderclause)
1207 def DMax(self, expression, domain, criteria = ''):
1208 return self.W(_vbMethod, self.objectreference, 'DMax', expression, domain, criteria)
1209 def DMin(self, expression, domain, criteria = ''):
1210 return self.W(_vbMethod, self.objectreference, 'DMin', expression, domain, criteria)
1211 def DStDev(self, expression, domain, criteria = ''):
1212 return self.W(_vbMethod, self.objectreference, 'DStDev', expression, domain, criteria)
1213 def DStDevP(self, expression, domain, criteria = ''):
1214 return self.W(_vbMethod, self.objectreference, 'DStDevP', expression, domain, criteria)
1215 def DVar(self, expression, domain, criteria = ''):
1216 return self.W(_vbMethod, self.objectreference, 'DVar', expression, domain, criteria)
1217 def DVarP(self, expression, domain, criteria = ''):
1218 return self.W(_vbMethod, self.objectreference, 'DVarP', expression, domain, criteria)
1219 def OpenRecordset(self, source, type = -1, option = -1, lockedit = -1):
1220 return self.W(_vbMethod, self.objectreference, 'OpenRecordset', source, type, option, lockedit)
1221 def OpenSQL(self, SQL, option = -1):
1222 return self.W(_vbMethod, self.objectreference, 'OpenSQL', SQL, option)
1223 def OutputTo(self, objecttype, objectname = '', outputformat = '', outputfile = '', autostart = False, templatefile = ''
1224 , encoding = acConstants.acUTF8Encoding, quality = acConstants.acExportQualityPrint):
1225 if objecttype == acConstants.acOutputForm: encoding = 0
1226 return self.W(_vbMethod, self.objectreference, 'OutputTo', objecttype, objectname, outputformat, outputfile
1227 , autostart, templatefile, encoding, quality)
1228 def QueryDefs(self, index = acConstants.Missing):
1229 return self.W(_vbMethod, self.objectreference, 'QueryDefs', index)
1230 def Recordsets(self, index = acConstants.Missing):
1231 return self.W(_vbMethod, self.objectreference, 'Recordsets', index)
1232 def RunSQL(self, SQL, option = -1):
1233 return self.W(_vbMethod, self.objectreference, 'RunSQL', SQL, option)
1234 def TableDefs(self, index = acConstants.Missing):
1235 return self.W(_vbMethod, self.objectreference, 'TableDefs', index)
1238 class _Dialog(_BasicObject):
1239 classProperties = dict(Caption = True, Height = True, IsLoaded = False, OnFocusGained = True
1240 , OnFocusLost = True, OnKeyPressed = True, OnKeyReleased = True, OnMouseDragged = True
1241 , OnMouseEntered = True, OnMouseExited = True, OnMouseMoved = True, OnMousePressed = True
1242 , OnMouseReleased = True, Page = True, Parent = False, Visible = True, Width = True
1245 @property
1246 def UnoDialog(self): return self.W(_vbUNO, self.objectreference, 'UnoDialog')
1248 def EndExecute(self, returnvalue):
1249 return self.W(_vbMethod, self.objectreference, 'EndExecute', returnvalue)
1250 def Execute(self):
1251 return self.W(_vbMethod, self.objectreference, 'Execute')
1252 def Move(left = -1, top = -1, width = -1, height = -1):
1253 return self.W(_vbMethod, self.objectreference, 'Move', left, top, width, height)
1254 def OptionGroup(self, groupname):
1255 return self.W(_vbMethod, self.objectreference, 'OptionGroup', groupname)
1256 def Start(self):
1257 return self.W(_vbMethod, self.objectreference, 'Start')
1258 def Terminate(self):
1259 return self.W(_vbMethod, self.objectreference, 'Terminate')
1261 class _Event(_BasicObject):
1262 classProperties = dict(ButtonLeft = False, ButtonMiddle = False, ButtonRight = False, ClickCount = False
1263 , ContextShortcut = False, EventName = False, EventType = False, FocusChangeTemporary = False
1264 , KeyAlt = False, KeyChar = False, KeyCode = False, KeyCtrl = False, KeyFunction = False, KeyShift = False
1265 , Recommendation = False, RowChangeAction = False, Source = False, SubComponentName = False
1266 , SubComponentType = False, XPos = False, YPos = False
1270 class _Field(_BasicObject):
1271 classProperties = dict(DataType = False, DataUpdatable = False, DbType = False, DefaultValue = True
1272 , Description = True, FieldSize = False, Size = False, Source = False
1273 , SourceField = False, SourceTable = False, TypeName = False, Value = True
1276 @property
1277 def Column(self): return self.W(_vbUNO, self.objectreference, 'Column')
1279 def AppendChunk(self, value):
1280 return self.W(_vbMethod, self.objectreference, 'AppendChunk', value)
1281 def GetChunk(self, offset, numbytes):
1282 return self.W(_vbMethod, self.objectreference, 'GetChunk', offset, numbytes)
1283 def ReadAllBytes(self, file):
1284 return self.W(_vbMethod, self.objectreference, 'ReadAllBytes', file)
1285 def ReadAllText(self, file):
1286 return self.W(_vbMethod, self.objectreference, 'ReadAllText', file)
1287 def WriteAllBytes(self, file):
1288 return self.W(_vbMethod, self.objectreference, 'WriteAllBytes', file)
1289 def WriteAllText(self, file):
1290 return self.W(_vbMethod, self.objectreference, 'WriteAllText', file)
1293 class _Form(_BasicObject):
1294 classProperties = dict(AllowAdditions = True, AllowDeletions = True, AllowEdits = True, Bookmark = True
1295 , Caption = True, CurrentRecord = True, Filter = True, FilterOn = True, Height = True
1296 , IsLoaded = False, OnApproveCursorMove = True, OnApproveParameter = True, OnApproveReset = True
1297 , OnApproveRowChange = True, OnApproveSubmit = True, OnConfirmDelete = True, OnCursorMoved = True
1298 , OnErrorOccurred = True, OnLoaded = True, OnReloaded = True, OnReloading = True, OnResetted = True
1299 , OnRowChanged = True, OnUnloaded = True, OnUnloading = True, OpenArgs = False, OrderBy = True
1300 , OrderByOn = True, Parent = False, Recordset = False, RecordSource = True, Visible = True
1301 , Width = True
1304 @property
1305 def Component(self): return self.W(_vbUNO, self.objectreference, 'Component')
1306 @property
1307 def ContainerWindow(self): return self.W(_vbUNO, self.objectreference, 'ContainerWindow')
1308 @property
1309 def DatabaseForm(self): return self.W(_vbUNO, self.objectreference, 'DatabaseForm')
1311 def Close(self):
1312 return self.W(_vbMethod, self.objectreference, 'Close')
1313 def Controls(self, index = acConstants.Missing):
1314 return self.W(_vbMethod, self.objectreference, 'Controls', index)
1315 def Move(self, left = -1, top = -1, width = -1, height = -1):
1316 return self.W(_vbMethod, self.objectreference, 'Move', left, top, width, height)
1317 def OptionGroup(self, groupname):
1318 return self.W(_vbMethod, self.objectreference, 'OptionGroup', groupname)
1319 def Refresh(self):
1320 return self.W(_vbMethod, self.objectreference, 'Refresh')
1321 def Requery(self):
1322 return self.W(_vbMethod, self.objectreference, 'Requery')
1323 def SetFocus(self):
1324 return self.W(_vbMethod, self.objectreference, 'SetFocus')
1327 class _Module(_BasicObject):
1328 classProperties = dict(CountOfDeclarationLines = False, CountOfLines = False
1329 , ProcStartLine = False, Type = False
1331 def __init__(self, reference = -1, objtype = None, name = ''):
1332 super().__init__(reference, objtype, name)
1333 self.localProperties = ('startline', 'startcolumn', 'endline', 'endcolumn', 'prockind')
1335 def Find(self, target, startline, startcolumn, endline, endcolumn, wholeword = False
1336 , matchcase = False, patternsearch = False):
1337 Returned = self.W(_vbMethod, self.objectreference, 'Find', target, startline, startcolumn, endline
1338 , endcolumn, wholeword, matchcase, patternsearch)
1339 if isinstance(Returned, tuple):
1340 if Returned[0] == True and len(Returned) == 5:
1341 self.startline = Returned[1]
1342 self.startcolumn = Returned[2]
1343 self.endline = Returned[3]
1344 self.endcolumn = Returned[4]
1345 return Returned[0]
1346 return Returned
1347 def Lines(self, line, numlines):
1348 return self.W(_vbMethod, self.objectreference, 'Lines', line, numlines)
1349 def ProcBodyLine(self, procname, prockind):
1350 return self.W(_vbMethod, self.objectreference, 'ProcBodyLine', procname, prockind)
1351 def ProcCountLines(self, procname, prockind):
1352 return self.W(_vbMethod, self.objectreference, 'ProcCountLines', procname, prockind)
1353 def ProcOfLine(self, line, prockind):
1354 Returned = self.W(_vbMethod, self.objectreference, 'ProcOfLine', line, prockind)
1355 if isinstance(Returned, tuple):
1356 if len(Returned) == 2:
1357 self.prockind = Returned[1]
1358 return Returned[0]
1359 return Returned
1360 def ProcStartLine(self, procname, prockind):
1361 return self.W(_vbMethod, self.objectreference, 'ProcStartLine', procname, prockind)
1364 class _OptionGroup(_BasicObject):
1365 classProperties = dict(Count = False, Value = True)
1367 def Controls(self, index = acConstants.Missing):
1368 return self.W(_vbMethod, self.objectreference, 'Controls', index)
1371 class _Property(_BasicObject):
1372 classProperties = dict(Value = True)
1375 class _QueryDef(_BasicObject):
1376 classProperties = dict(SQL = True, Type = False)
1378 @property
1379 def Query(self): return self.W(_vbUNO, self.objectreference, 'Query')
1381 def Execute(self, options = acConstants.Missing):
1382 return self.W(_vbMethod, self.objectreference, 'Execute', options)
1383 def Fields(self, index = acConstants.Missing):
1384 return self.W(_vbMethod, self.objectreference, 'Fields', index)
1385 def OpenRecordset(self, type = -1, option = -1, lockedit = -1):
1386 return self.W(_vbMethod, self.objectreference, 'OpenRecordset', type, option, lockedit)
1389 class _Recordset(_BasicObject):
1390 classProperties = dict(AbsolutePosition = True, BOF = False, Bookmark = True, Bookmarkable = False
1391 , EditMode = False, EOF = False, Filter = True, RecordCount = False
1394 @property
1395 def RowSet(self): return self.W(_vbUNO, self.objectreference, 'RowSet')
1397 def AddNew(self):
1398 return self.W(_vbMethod, self.objectreference, 'AddNew')
1399 def CancelUpdate(self):
1400 return self.W(_vbMethod, self.objectreference, 'CancelUpdate')
1401 def Clone(self):
1402 return self.W(_vbMethod, self.objectreference, 'Clone')
1403 def Close(self):
1404 return self.W(_vbMethod, self.objectreference, 'Close')
1405 def Delete(self):
1406 return self._Reset('RecordCount',self.W(_vbMethod, self.objectreference, 'Delete'))
1407 def Edit(self):
1408 return self.W(_vbMethod, self.objectreference, 'Edit')
1409 def Fields(self, index = acConstants.Missing):
1410 return self.W(_vbMethod, self.objectreference, 'Fields', index)
1411 def GetRows(self, numrows):
1412 return self.W(_vbMethod, self.objectreference, 'GetRows', numrows)
1413 def Move(self, rows, startbookmark = acConstants.Missing):
1414 return self._Reset('BOF', self.W(_vbMethod, self.objectreference, 'Move', rows, startbookmark))
1415 def MoveFirst(self):
1416 return self._Reset('BOF', self.W(_vbMethod, self.objectreference, 'MoveFirst'))
1417 def MoveLast(self):
1418 return self._Reset('BOF', self.W(_vbMethod, self.objectreference, 'MoveLast'))
1419 def MoveNext(self):
1420 return self._Reset('BOF', self.W(_vbMethod, self.objectreference, 'MoveNext'))
1421 def MovePrevious(self):
1422 return self._Reset('BOF', self.W(_vbMethod, self.objectreference, 'MovePrevious'))
1423 def OpenRecordset(self, type = -1, option = -1, lockedit = -1):
1424 return self.W(_vbMethod, self.objectreference, 'OpenRecordset', type, option, lockedit)
1425 def Update(self):
1426 return self._Reset('RecordCount',self.W(_vbMethod, self.objectreference, 'Update'))
1429 class _SubForm(_Form):
1430 classProperties = dict(AllowAdditions = True, AllowDeletions = True, AllowEdits = True, CurrentRecord = True
1431 , Filter = True, FilterOn = True, LinkChildFields = False, LinkMasterFields = False
1432 , OnApproveCursorMove = True, OnApproveParameter = True, OnApproveReset = True
1433 , OnApproveRowChange = True, OnApproveSubmit = True, OnConfirmDelete = True, OnCursorMoved = True
1434 , OnErrorOccurred = True, OnLoaded = True, OnReloaded = True, OnReloading = True, OnResetted = True
1435 , OnRowChanged = True, OnUnloaded = True, OnUnloading = True, OrderBy = True
1436 , OrderByOn = True, Parent = False, Recordset = False, RecordSource = True, Visible = True
1439 def SetFocus(self):
1440 raise AttributeError("type object 'SubForm' has no method 'SetFocus'")
1443 class _TableDef(_BasicObject):
1444 classProperties = dict()
1446 @property
1447 def Table(self): return self.W(_vbUNO, self.objectreference, 'Table')
1449 def CreateField(self, name, type, size = 0, attributes = 0):
1450 return self.W(_vbMethod, self.objectreference, 'CreateField', name, type, size, attributes)
1451 def Fields(self, index = acConstants.Missing):
1452 return self.W(_vbMethod, self.objectreference, 'Fields', index)
1453 def OpenRecordset(self, type = -1, option = -1, lockedit = -1):
1454 return self.W(_vbMethod, self.objectreference, 'OpenRecordset', type, option, lockedit)
1457 class _TempVar(_BasicObject):
1458 classProperties = dict(Value = True)
1461 Set of directly callable error handling methods
1463 def DebugPrint(*args):
1464 dargs = ()
1465 for arg in args:
1466 if isinstance(arg, _BasicObject):
1467 arg = ('[' + arg.objecttype + '] ' + arg.name).rstrip()
1468 dargs = dargs + (arg,)
1469 return _A2B.invokeMethod('DebugPrint', _WRAPPERMODULE, *dargs)
1470 def TraceConsole(): return _A2B.invokeMethod('TraceConsole', 'Trace')
1471 def TraceError(tracelevel, errorcode, errorprocedure, errorline):
1472 return _A2B.invokeMethod('TraceError', 'Trace', tracelevel, errorcode, errorprocedure, errorline)
1473 def TraceLevel(newtracelevel = 'ERROR'): return _A2B.invokeMethod('TraceLevel', 'Trace', newtracelevel)
1474 def TraceLog(tracelevel, text, messagebox = True):
1475 return _A2B.invokeMethod('TraceLog', 'Trace', tracelevel, text, messagebox)