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