1 # -*- coding: utf-8 -*-
3 # Copyright 2020-2024 Jean-Pierre LEDURE, Rafael LIMA, @AmourSpirit, Alain ROMEDENNE
5 # =====================================================================================================================
6 # === The ScriptForge library and its associated libraries are part of the LibreOffice project. ===
7 # === Full documentation is available on https://help.libreoffice.org/ ===
8 # =====================================================================================================================
10 # ScriptForge is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 # ScriptForge 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/ .
25 ScriptForge libraries are an extensible and robust collection of macro scripting resources for LibreOffice
26 to be invoked from user Basic or Python macros. Users familiar with other BASIC macro variants often face hard
27 times to dig into the extensive LibreOffice Application Programming Interface even for the simplest operations.
28 By collecting most-demanded document operations in a set of easy to use, easy to read routines, users can now
29 program document macros with much less hassle and get quicker results.
31 The use of the ScriptForge interfaces in user scripts hides the complexity of the usual UNO interfaces.
32 However, it does not replace them. At the opposite their coexistence is ensured.
33 Indeed, ScriptForge provides a number of shortcuts to key UNO objects.
35 The scriptforge.py module
36 - describes the interfaces (classes and attributes) to be used in Python user scripts
37 to run the services implemented in the standard modules shipped with LibreOffice
38 - implements a protocol between those interfaces and, when appropriate, the corresponding ScriptForge
39 Basic libraries implementing the requested services.
41 The scriptforge.pyi module
42 - provides the static type checking of all the visible interfaces of the ScriptForge API.
43 - when the user uses an IDE like PyCharm or VSCode, (s)he might benefit from the typing
44 hints provided by them thanks to the actual scriptforge.pyi module.
46 Specific documentation about the use of ScriptForge from Python scripts:
47 https://help.libreoffice.org/latest/en-US/text/sbasic/shared/03/sf_intro.html?DbPAR=BASIC
50 from __future__ import annotations
53 from typing import Any, Dict, List, Literal, NewType, Optional, overload, Sequence, Tuple, TypeVar, Union
55 # List the available service types
57 ARRAY = SFScriptForge.SF_Array
58 BASIC = SFScriptForge.SF_Basic
59 DICTIONARY = SFScriptForge.SF_Dictionary
60 EXCEPTION = SFScriptForge.SF_Exception
61 FILESYSTEM = SFScriptForge.SF_FileSystem
62 L10N = SFScriptForge.SF_L10N
63 PLATFORM = SFScriptForge.SF_Platform
64 REGION = SFScriptForge.SF_Region
65 SESSION = SFScriptForge.SF_Session
66 STRING = SFScriptForge.SF_String
67 TEXTSTREAM = SFScriptForge.SF_TextStream
68 TIMER = SFScriptForge.SF_Timer
69 UI = SFScriptForge.SF_UI
71 DATABASE = SFDatabases.SF_Database
72 DATASET = SFDatabases.SF_Dataset
73 DATASHEET = SFDatabases.SF_Datasheet
75 DIALOG = SFDialogs.SF_Dialog
76 DIALOGCONTROL = SFDialogs.SF_DialogControl
78 DOCUMENT = SFDocuments.SF_Document
79 BASE = SFDocuments.SF_Base
80 CALC = SFDocuments.SF_Calc
81 CALCREFERENCE = SFDocuments.SF_CalcReference
82 CHART = SFDocuments.SF_Chart
83 FORM = SFDocuments.SF_Form
84 FORMCONTROL = SFDocuments.SF_FormControl
85 FORMDOCUMENT = SFDocuments.SF_FormDocument
86 WRITER = SFDocuments.SF_Writer
88 MENU = SFWidgets.SF_Menu
89 CONTEXTMENU = SFWidgets.SF_ContextMenu
90 POPUPMENU = SFWidgets.SF_PopupMenu
91 TOOLBAR = SFWidgets.SF_Toolbar
92 TOOLBARBUTTON = SFWidgets.SF_ToolbarButton
94 SERVICE = Union[ARRAY, BASIC, DICTIONARY, EXCEPTION, FILESYSTEM, L10N, PLATFORM, REGION, SESSION, STRING,
95 TEXTSTREAM, TIMER, UI,
96 DATABASE, DATASET, DATASHEET,
97 DIALOG, DIALOGCONTROL,
98 DOCUMENT, BASE, CALC, CALCREFERENCE, CHART, FORM, FORMCONTROL, FORMDOCUMENT, WRITER,
99 MENU, CONTEXTMENU, POPUPMENU, TOOLBAR, TOOLBARBUTTON]
103 FILE = TypeVar('FILE', str, str)
104 """ File or folder name expressed in accordance with the ``FileSystem.FileNaming`` notation. """
106 SHEETNAME = TypeVar('SHEETNAME', str, str)
107 """ A sheet in a Calc document, as a string. It must not contain next characters: "[]*?:\\\/". The apostrophe (')
108 is forbidden in the first and last positions. The "~" (tilde) character designates the active sheet. """
109 RANGE = TypeVar('RANGE', str, str)
110 """ A set of contiguous cells located in a sheet.
112 The sheet name is optional. If no sheet name is provided, then the active sheet is used.
113 The use of single quotes to enclose the sheet name is required if the name contains blank spaces " " or periods ".".
114 Otherwise surrounding single quotes and $ signs are allowed but ignored.
116 The shortcut "~" (tilde) represents the current selection or the first selected range if multiple ranges are selected.
117 The shortcut "*" represents all used cells.
120 - ``$'SheetX'.D2``, ``$D$2`` - Single cells
121 - ``$'SheetX'.D2:F6``, ``D2:D10`` - Single ranges with multiple cells
122 - ``$'SheetX'.*`` - All used cells in the given sheet
123 - ``$'SheetX'.A:A``, ``3:5`` - All cells in contiguous columns or rows up to the last used cell
124 - ``myRange`` - A range named "myRange" at spreadsheet level
125 - ``~.someRange``, ``SheetX.someRange`` - Range names at sheet level
126 - ``~.~`` or ``~`` - The current selection in the active sheet
128 SCRIPT_URI = TypeVar('SCRIPT_URI', str, str)
129 """ String reference to a Basic or Python macro as described in
130 ``https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework#Scripting_Framework_URI_Specification``
132 SQL_SELECT = TypeVar('SQL_SELECT', str, str)
133 """ A SQL command containing a SELECT statement, a tablename or a queryname.
134 In a SELECT statement, table-, query- and field names may be surrounded by square brackets. """
135 SQL_ACTION = TypeVar('SQL_ACTION', str, str)
136 """ A SQL command containing an action statement (CREATE TABLE, INSERT, DELETE, ...).
137 Table- and field names may be surrounded by square brackets. """
138 SCALAR = Union[int, float, str, datetime.datetime]
139 VECTOR = Sequence[SCALAR]
140 MATRIX = Sequence[VECTOR]
142 # Define the used UNO types
144 # Next code can succeed only when types-unopy is installed
145 from com.sun.star.awt import XControl
146 from com.sun.star.awt import XControlModel
147 from com.sun.star.awt import XTabControllerModel
148 from com.sun.star.awt import XWindow
149 from com.sun.star.awt.tree import XMutableTreeDataModel
150 from com.sun.star.awt.tree import XMutableTreeNode
151 from com.sun.star.beans import PropertyValue
152 from com.sun.star.chart import XDiagram
153 from com.sun.star.document import XEmbeddedScripts
154 from com.sun.star.drawing import XShape
155 from com.sun.star.form import ListSourceType
156 from com.sun.star.form import XForm
157 from com.sun.star.frame import XDesktop
158 from com.sun.star.lang import XComponent
159 from com.sun.star.script import XLibraryContainer
160 from com.sun.star.script.provider import XScriptProvider
161 from com.sun.star.sdb import XOfficeDatabaseDocument
162 from com.sun.star.sdbc import XConnection as UNOXConnection
163 from com.sun.star.sdbc import XDatabaseMetaData
164 from com.sun.star.sheet import XSheetCellCursor
165 from com.sun.star.sheet import XSpreadsheet
166 from com.sun.star.table import XCellRange
167 from com.sun.star.table import XTableChart
168 from com.sun.star.uno import XComponentContext
169 from com.sun.star.uno import XInterface
170 from com.sun.star.util import Date as UNODate
171 from com.sun.star.util import DateTime as UNODateTime
172 from com.sun.star.util import Time as UNOTime
174 # types-unopy is not installed
175 XControl = NewType('XControl', UNO)
176 XControlModel = NewType('XControlModel', UNO)
177 XTabControllerModel = NewType('XTabControllerModel', UNO)
178 XWindow = NewType('XWindow', UNO)
179 XMutableTreeDataModel = NewType('XMutableTreeDataModel', UNO)
180 XMutableTreeNode = NewType('XMutableTreeNode', UNO)
181 PropertyValue = NewType('PropertyValue', UNO)
182 XDiagram = NewType('XDiagram', UNO)
183 XEmbeddedScripts = NewType('XEmbeddedScripts', UNO)
184 XShape = NewType('XShape', UNO)
185 ListSourceType = NewType('ListSourceType', UNO)
186 XForm = NewType('XForm', UNO)
187 XDesktop = NewType('XDesktop', UNO)
188 XComponent = NewType('XComponent', UNO)
189 XLibraryContainer = NewType('XLibraryContainer', UNO)
190 XScriptProvider = NewType('XScriptProvider', UNO)
191 XOfficeDatabaseDocument = NewType('XOfficeDatabaseDocument', UNO)
192 UNOXConnection = NewType('UNOXConnection', UNO)
193 XDatabaseMetaData = NewType('XDatabaseMetaData', UNO)
194 XSheetCellCursor = NewType('XSheetCellCursor', UNO)
195 XSpreadsheet = NewType('XSpreadsheet', UNO)
196 XCellRange = NewType('XCellRange', UNO)
197 XTableChart = NewType('XTableChart', UNO)
198 XComponentContext = NewType('XComponentContext', UNO)
199 XInterface = NewType('XInterface', UNO)
200 UNODate = NewType('UNODate', UNO)
201 UNODateTime = NewType('UNODateTime', UNO)
202 UNOTime = NewType('UNOTime', UNO)
204 # Docstring rules to display readable text both in PyCharm and VS Code
205 # Indentation and punctuation are required like in the example below.
206 # def ImportFromCSVFile(self, filename: FILE, delimiter: str = ',',
207 # dateformat: Literal['YYYY-MM-DD', 'DD-MM-YYYY', 'MM-DD-YYYY'] = ...) -> Tuple[str, ...]:
209 # Import the data contained in a comma-separated values (CSV) file. The comma may be replaced
211 # Difference with the Basic version: dates are returned in their iso format,
212 # not as any of the datetime objects.
213 # Args <<<<< No colon (:)
214 # ``filename``: The name of the text file containing the data.
215 # The name must be expressed according to the current FileNaming property of the FileSystem
217 # <<<<< When multiple arguments, a linefeed is required here
218 # ``dateformat``: A special mechanism handles dates when ``dateformat`` is not the empty string.
219 # The dash (-) may be replaced by a dot (.), a slash (/) or a space. Other date formats
221 # Returns <<<<< No colon (:)
222 # A ``list`` of ``lists``.
227 # #####################################################################################################################
228 # ScriptForge CLASS ###
229 # #####################################################################################################################
231 class ScriptForge(object, metaclass = ...):
233 The ScriptForge class encapsulates the core of the ScriptForge run-time
234 - Bridge with the LibreOffice process
235 - Implementation of the interlanguage protocol with the Basic libraries
236 - Identification of the available services interfaces
237 - Dispatching of services
238 - Coexistence with UNO
240 The class may be instantiated several times. Only the first instance will be retained ("Singleton").
243 def __init__(self, hostname: str = ..., port: int = ..., pipe: str = ...):
245 The ScriptForge class encapsulates the core of the ScriptForge run-time
246 - Bridge with the LibreOffice process
247 - Implementation of the interlanguage protocol with the Basic libraries
248 - Identification of the available services interfaces
249 - Dispatching of services
250 - Coexistence with UNO
252 The class may be instantiated several times. Only the first instance will be retained ("Singleton").
254 Both arguments are mandatory when Python and LibreOffice run in separate processes.
255 Otherwise, do not call this routine or leave both arguments out.
256 To execute at most once by LibreOffice session.
258 ``hostname``: probably 'localhost'
260 ``port``: port number
267 # #####################################################################################################################
268 # SFServices CLASS (ScriptForge services superclass) ###
269 # #####################################################################################################################
271 class SFServices(object):
273 Generic implementation of a parent Service class.
275 Every service must subclass this class to be recognized as a valid service.
276 A service instance is created by the ``CreateScriptService`` method.
278 It can have a mirror in the ``Basic`` world or be totally defined in ``Python``.
281 def Dispose(self) -> None:
282 """ Free up the object's resources after usage. """
285 def GetProperty(self, propertyname: str, arg: Any = ...) -> Any:
286 """ Get the given property from the Basic world """
289 def Properties(self) -> Tuple[str, ...]:
290 """ Properties list. """
294 # #####################################################################################################################
295 # SFScriptForge CLASS (alias of ScriptForge Basic library) ###
296 # #####################################################################################################################
298 """ SF_ScriptForge all-purpose services. """
300 # #########################################################################
302 # #########################################################################
303 class SF_Array(SFServices, metaclass = ...):
305 def ImportFromCSVFile(self,
307 delimiter: str = ',',
308 dateformat: Literal['YYYY-MM-DD', 'DD-MM-YYYY', 'MM-DD-YYYY',
309 'YYYY/MM/DD', 'DD/MM/YYYY', 'MM/DD/YYYY',
310 'YYYY.MM.DD', 'DD.MM.YYYY', 'MM.DD.YYYY',
311 'YYYY MM DD', 'DD MM YYYY', 'MM DD YYYY'] = ...
314 Import the data contained in a comma-separated values (CSV) file. The comma may be replaced
316 Difference with the Basic version: dates are returned in their iso format,
317 not as any of the datetime objects.
319 ``filename``: The name of the text file containing the data.
320 The name must be expressed according to the current FileNaming property of the FileSystem
323 ``dateformat``: A special mechanism handles dates when ``dateformat`` is not the empty string.
324 The dash (-) may be replaced by a dot (.), a slash (/) or a space. Other date formats
327 A ``list`` of ``lists``.
331 # #########################################################################
333 # #########################################################################
334 class SF_Basic(SFServices, metaclass = ...):
336 This service proposes a collection of Basic methods to be executed in a Python context
337 simulating the exact syntax and behavior of the identical Basic builtin method.\n
339 ``basic = CreateScriptService('basic')``
340 ``basic.MsgBox('This has to be displayed in a message box')``
343 MB_ABORTRETRYIGNORE: Literal[2]
344 MB_DEFBUTTON1: Literal[128]
345 MB_DEFBUTTON2: Literal[258]
346 MB_DEFBUTTON3: Literal[215]
347 MB_ICONEXCLAMATION: Literal[48]
348 MB_ICONINFORMATION: Literal[64]
349 MB_ICONQUESTION: Literal[32]
350 MB_ICONSTOP: Literal[16]
352 MB_OKCANCEL: Literal[1]
353 MB_RETRYCANCEL: Literal[5]
355 MB_YESNOCANCEL: Literal[3]
365 def CDate(cls, datevalue: Union[int, float, str]) -> Optional[datetime.datetime]:
367 Converts a numeric expression or a string to a ``datetime.datetime`` Python native object.
369 ``datevalue``: A numeric expression or a ``string`` representing a date.
371 The equivalent ``datetime.datetime``.
376 def CDateFromUnoDateTime(unodate: Union[UNODateTime, UNODate, UNOTime]) -> datetime.datetime:
378 Converts a ``UNO date/time`` representation to a ``datetime.datetime`` Python native object.
380 ``unodate``: A ``UNO date`` object, ``com.sun.star.util.DateTime``, ``.Date`` or ``.Time``.
382 The equivalent ``datetime.datetime``.
387 def CDateToUnoDateTime(date: Union[float, time.struct_time, datetime.datetime, datetime.date, datetime.time]
390 Converts a date representation into the ``com.sun.star.util.DateTime`` date format.
392 ``date``: A ``datetime`` like object.
393 When ``date`` is a ``float`` it is considered a ``time.time`` value.
395 A ``com.sun.star.util.DateTime`` UNO object.
400 def ConvertFromUrl(cls, url: str) -> str:
404 ``url``: A string representing a file in URL format.
406 The same file name in native operating system notation._
411 def ConvertToUrl(cls, systempath: str) -> str:
415 ``systempath``: A string representing a file in native operating system notation.
417 The same file name in URL format.
422 def CreateUnoService(cls, servicename: str) -> UNO:
424 Instantiates a UNO service
426 ``servicename``: A string representing the service to create.
433 def CreateUnoStruct(cls, unostructure: str) -> UNO:
435 Returns an instance of a UNO structure of the specified type.
437 ``unostructure``: A UNO Struct typename such as ``com.sun.star.awt.Size``.
445 interval: Literal['yyyy', 'q', 'm','y', 'w', 'ww', 'd', 'h', 'n', 's'],
447 date: Union[float, time.struct_time, datetime.datetime, datetime.date, datetime.time]
448 ) -> datetime.datetime:
450 Adds a date or time interval to a given date/time a number of times and returns the resulting date.
452 ``interval``: A string expression specifying the date or time interval.
454 ``number``: A numerical expression specifying how often the interval value will be added when
455 positive or subtracted when negative.
457 ``date``: A given ``datetime.datetime`` value, the interval value will be added ``number``
458 times to this ``date`` value.
460 A ``datetime.datetime`` value.
466 interval: Literal['yyyy', 'q', 'm','y', 'w', 'ww', 'd', 'h', 'n', 's'],
467 date1: Union[float, time.struct_time, datetime.datetime, datetime.date, datetime.time],
468 date2: Union[float, time.struct_time, datetime.datetime, datetime.date, datetime.time],
469 firstdayofweek: Literal[0, 1, 2, 3, 4, 5, 6, 7] = ...,
470 firstweekofyear: Literal[0, 1, 2, 3] = ...,
473 Gets the number of date or time intervals between two given date/time values.
475 ``interval``: A string expression specifying the date interval.
477 ``date1``: The first ``datetime.datetime`` values to be compared.
479 ``firstdayofweek``: An optional parameter that specifies the starting day of a week.
481 ``firstweekofyear``: An optional parameter that specifies the starting week of a year.
489 interval: Literal['yyyy', 'q', 'm','y', 'w', 'ww', 'd', 'h', 'n', 's'],
490 date: Union[float, time.struct_time, datetime.datetime, datetime.date, datetime.time],
491 firstdayofweek: Literal[0, 1, 2, 3, 4, 5, 6, 7] = ...,
492 firstweekofyear: Literal[0, 1, 2, 3] = ...,
495 Gets a specified part of a date.
497 ``interval``: A string expression specifying the date interval.
499 ``date``: The date from which to extract a part.
501 ``firstdayofweek``: the starting day of a week. Defaults to 1.
503 ``firstweekofyear``: the starting week of a year. Defaults to 1.
505 The specified part of the date.
510 def DateValue(cls, string: str) -> datetime.datetime:
512 Computes a date value from a date string.
514 ``string``: A string expression that contains the date that you want to calculate.
515 The string passed to ``DateValue`` must be expressed in one of the date formats defined
516 by your locale setting or using the ISO date format "yyyy-mm-dd" (year, month and day
517 separated by hyphens).
524 def Format(cls, expression: Union[datetime.datetime, float, int], format: str = ...) -> str:
526 Converts a number to a string, and then formats it according to the format that you specify.
528 ``expression``: Numeric expression that you want to convert to a formatted string.
530 ``format``: the format to apply. Defaults to "".
537 def GetDefaultContext(cls) -> XComponentContext:
539 Gets the default context of the process service factory, if existent, else returns a None reference.
544 def GetGuiType(cls) -> int:
546 Gets a numerical value that specifies the graphical user interface.
548 The GetGuiType value, 1 for Windows, 4 for UNIX
553 def GetPathSeparator(cls) -> str:
555 Gets the operating system-dependent directory separator used to specify file paths.
557 The os path separator
562 def GetSystemTicks(cls) -> int:
564 Gets the number of system ticks provided by the operating system.
565 You can use this function to optimize certain processes.
566 Use this method to estimate time in milliseconds:
568 The actual number of system ticks.
572 class GlobalScope(metaclass = ...):
575 - ``GlobalScope.BasicLibraries``
576 - ``GlobalScope.DialogLibraries``
580 def BasicLibraries(cls) -> XLibraryContainer:
582 ``GlobalScope.BasicLibraries`` gets the UNO object containing all shared Basic libraries
583 and modules. This method is the Python equivalent to ``GlobalScope.BasicLibraries``
586 A ``XLibraryContainer`` UNO object.
591 def DialogLibraries(cls) -> XLibraryContainer:
593 ``GlobalScope.DialogLibraries`` gets the UNO object containing all shared dialog libraries.
595 A ``DialogLibraryContainer`` UNO object.
604 xpostwips: int = ...,
605 ypostwips: int = ...,
608 Displays an input box.
610 ``prompt``: String expression displayed as the message in the dialog box.
612 ``title``: String expression displayed in the title bar of the dialog box.
614 ``default``: String expression displayed in the text box as default if no other input is given.
616 ``xpostwips``: Integer expression that specifies the horizontal position of the dialog.
617 The position is an absolute coordinate and does not refer to the window of LibreOffice.
619 ``ypostwips``: Integer expression that specifies the vertical position of the dialog.
620 The position is an absolute coordinate and does not refer to the window of LibreOffice.
622 If ``xpostwips`` and ``ypostwips`` are omitted, the dialog is centered on the screen.
629 def MsgBox(cls, prompt: str, buttons: int = ..., title: str = ...) -> int:
631 Displays a dialogue box containing a message and returns an optional value.
633 MB_xx constants help specify the dialog type, the number and type of buttons to display,
634 plus the icon type. By adding their respective values they form bit patterns, that define the
635 MsgBox dialog appearance.
637 ``prompt``: String expression displayed as a message in the dialog box.
639 ``buttons``: Integer expression that specifies the dialog type, as well as the number
640 and type of buttons to display, and the icon type. ``buttons`` represents a combination of bit
641 patterns, that is, a combination of elements can be defined by adding their respective values.
644 ``title``: String expression displayed in the title bar of the dialog. Defaults to "".
651 def Now(cls) -> datetime.datetime:
653 Gets the current system date and time as a ``datetime.datetime`` Python native object.
658 def RGB(cls, red: int, green: int, blue: int) -> int:
660 Gets an integer color value consisting of red, green, and blue components.
662 ``red``: An integer expression that represents the red component (0-255) of the composite color.
664 ``green``: An integer expression that represents the green component (0-255) of the
667 ``blue``: An integer expression that represents the blue component (0-255) of the composite
670 An integer color value consisting of red, green, and blue components.
676 def Xray(cls, unoobject: UNO) -> None:
678 Inspect UNO objects or variables.
680 ``unoobject``: A variable or UNO object.
684 StarDesktop: XDesktop
685 """ Gets the desktop as a UNO object. """
686 ThisComponent: Optional[XComponent]
688 If the current component refers to a LibreOffice document, this method
689 returns the UNO object representing the document.
690 When the current component is the Basic IDE, the ThisComponent object returns in Basic the
691 component owning the currently run user script. This behaviour cannot be reproduced in Python.
693 The current component or None when not a document.
695 ThisDatabaseDocument: Optional[XOfficeDatabaseDocument]
697 If the script is being executed from a Base document or any of its subcomponents
698 this method returns the main component of the Base instance.
700 The current Base (main) component or None when not a Base document or one of its subcomponents.
703 # #########################################################################
704 # SF_Dictionary CLASS
705 # #########################################################################
706 class SF_Dictionary(SFServices, dict):
708 The service adds to a Python dict instance the interfaces for conversion to and from
709 a list of UNO PropertyValues
711 ``dico = dict(A = 1, B = 2, C = 3)``
713 ``myDict = CreateScriptService('Dictionary', dico) # Initialize myDict with the content of dico``
717 ``print(myDict) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}``
719 ``propval = myDict.ConvertToPropertyValues()``
721 ``dico = dict(A = 1, B = 2, C = 3)``
723 ``myDict = CreateScriptService('Dictionary') # Initialize myDict as an empty dict object``
725 ``myDict.update(dico) # Load the values of dico into myDict``
729 ``print(myDict) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}``
731 ``propval = myDict.ConvertToPropertyValues()``
734 def ConvertToPropertyValues(self) -> Tuple[PropertyValue]:
736 Store the content of the dictionary in an array of PropertyValues.
737 Each entry in the list is a ``com.sun.star.beans.PropertyValue``.
738 The key is stored in Name, the value is stored in ``Value``.
740 If one of the items has a type ``datetime``, it is converted to a ``com.sun.star.util.DateTime``
741 structure. If one of the items is an empty list, it is converted to ``None``.
743 A list of property values. The resulting list is empty when the dictionary is empty.
747 def ImportFromPropertyValues(self, propertyvalues: Sequence[PropertyValue], overwrite: bool = ...) -> bool:
749 Inserts the contents of an array of ``PropertyValue`` objects into the current dictionary.
750 ``PropertyValue`` Names are used as keys in the dictionary, whereas Values contain
751 the corresponding values. Date-type values are converted to ``datetime.datetime`` instances.
753 ``propertyvalues``: tuple containing ``com.sun.star.beans.PropertyValue`` objects.
755 ``overwrite``: When True, entries with same name may exist in the dictionary
756 and their values are overwritten. When ``False`` (default), repeated keys are not overwritten.
757 Defaults to ``False``.
759 True when successful.
763 # #########################################################################
765 # #########################################################################
766 class SF_Exception(SFServices, metaclass = ...):
768 The Exception service is a collection of methods for code debugging.
770 The ``Exception`` service console stores events, variable values and information about errors.
772 Use the console when the Python shell is not available, for example in ``Calc`` user defined functions (UDF)
773 or during events processing.
775 Use the ``DebugPrint()`` and ``DebugDisplay()`` methods to log any relevant information, events and data
776 of any type to the console.
778 Console entries can be dumped to a text file or visualized in a dialogue.
781 def Console(self, modal: bool = ...):
783 Displays the console messages in a modal or non-modal dialog. In both modes, all the past messages
784 issued by a ``DebugPrint()`` method or resulting from an exception are displayed. In non-modal mode,
785 subsequent entries are added automatically.
787 If the console is already open, when non-modal, it is brought to the front.
789 A modal console can only be closed by the user. A non-modal console can either be closed by the user
790 or upon script termination.
792 ``modal``: determine if the console window is modal (``True``) or non-modal (``False``).
793 Default value is ``True``.
797 def ConsoleClear(self, keep: int = ...):
799 Clears the console keeping an optional number of recent messages. If the console is activated in non-modal mode,
802 ``keep``: the number of recent messages to be kept. Default value is 0.
806 def ConsoleToFile(self, filename: FILE) -> bool:
808 Exports the contents of the console to a text file. If the file already exists and the console
809 is not empty, it will be overwritten without warning. Returns True if successful.
811 ``filename``: the name of the text file the console should be dumped into.
812 The name is expressed according to the current ``FileNaming`` property of the ``SF_FileSystem``
815 ``True`` when successful.
819 def DebugDisplay(self, *args)-> int:
821 Concatenates all the arguments into a single human-readable string and displays it in a MsgBox
822 with an Information icon and an OK button. The displayed string is also added to the Console.
824 ``*args``: any number of arguments of any type.
826 The result of the execution of the ``MsgBox()`` method.
830 def DebugPrint(self, *args):
832 Assembles all the given arguments into a single human-readable string and adds it as a new entry
835 ``*args``: any number of arguments of any type.
840 def PythonShell(cls, variables: dict = ...,
841 background: int = ...,
842 foreground: int = ...
845 Opens an APSO Python shell as a non-modal window.
846 The Python script keeps running after the shell is opened.
847 The output from ``print`` statements inside the script are shown in the shell.
849 ``variables``: a Python dictionary with variable names and values that will be
850 passed on to the APSO Python shell. By default, all local variables are passed using
851 Python's builtin ``locals()`` function.
853 ``background``: the background color of the window as an integer value. Usually given
854 as a hexadecimal value, like 0xFFFFFF, or as the output of the ``basic.RGB()`` method.
856 ``foreground``: the foreground color of the window as an integer value.
859 ``exc.PythonShell({**globals(), **locals()}, background = 0x0, foreground = 0xFFFFFF)``
863 # #########################################################################
864 # SF_FileSystem CLASS
865 # #########################################################################
866 class SF_FileSystem(SFServices, metaclass = ...):
868 The "FileSystem" service includes common file and folder handling routines.
873 Sets or returns the current files and folders notation, either ``'ANY', 'URL'`` or ``'SYS'``:
875 ``ANY``: (default) the methods of the ``FileSystem`` service accept both URL and current operating
876 system's notation for input arguments but always return URL strings.
878 ``URL``: the methods of the ``FileSystem`` service expect URL notation for input arguments and
881 ``SYS``: the methods of the ``FileSystem`` service expect current operating system's notation
882 for both input arguments and return strings.
884 Once set, the ``FileNaming`` property remains unchanged either until the end of the ``LibreOffice``
885 session or until it is set again.
888 """ Returns the configuration folder of ``LibreOffice``. """
889 ExtensionsFolder: FILE
890 """ Returns the folder where extensions are installed. """
892 """ Returns the user home folder. """
894 """ Returns the installation folder of ``LibreOffice``. """
895 TemplatesFolder: FILE
896 """ Returns the folder containing the system templates files. """
897 TemporaryFolder: FILE
898 """ Returns the temporary files folder defined in the ``LibreOffice`` path settings. """
899 UserTemplatesFolder: FILE
900 """ Returns the folder containing the user-defined template files. """
902 ForReading: Literal[1]
903 ForWriting: Literal[2]
904 ForAppending: Literal[8]
906 def BuildPath(self, foldername: FILE, name: str) -> str:
908 Joins a folder path and the name of a file and returns the full file name with a
909 valid path separator. The path separator is added only if necessary.
912 ``foldername``: the path with which name will be combined.
913 The specified path does not need to be an existing folder.
915 ``name``: the name of the file to be appended to foldername. This parameter uses
916 the notation of the current operating system.
919 The path concatenated with the file name after insertion of a path separator, if necessary.
923 def CompareFiles(self, filename1: FILE, filename2: FILE, comparecontents: bool = ...) -> bool:
925 Compare 2 files and return ``True`` if they seem identical.
926 Depending on the value of the ``comparecontents`` argument,
927 the comparison between both files can be either based only on
928 file attributes (such as the last modified date), or based on the file contents.
930 ``filename1``: the 1st file to compare.
932 ``filename2``: the 2nd file to compare.
934 ``comparecontents``: when ``True``, the contents of the files are compared.
935 Defaults to ``False``.
937 ``True`` when the files seem identical
941 def CopyFile(self, source: FILE, destination: FILE, overwrite: bool = ...) -> bool:
943 Copies one or more files from one location to another.
945 ``source``: ``FileName`` or ``NamePattern`` which can include wildcard characters,
946 for one or more files to be copied.
948 ``destination``: ``FileName`` where the single ``source`` file is to be copied
949 or ``FolderName`` where the multiple files from ``source`` are to be copied.
951 ``overwrite``: if ``True`` (default), files may be overwritten.
952 ``CopyFile`` will fail if Destination has the read-only attribute set,
953 regardless of the value of Overwrite.
955 ``True`` if at least one file has been copied. ``False`` if an error occurred.
956 An error also occurs if a source using wildcard characters doesn't match any files.
957 The method stops on the first error it encounters.
958 No attempt is made to roll back or undo any changes made before an error occurs.
960 - If ``destination`` does not exist, it is created.
961 - Wildcard characters are not allowed in ``destination``.
965 def CopyFolder(self, source: FILE, destination: FILE, overwrite: bool = ...) -> bool:
967 Copies one or more folders from one location to another.
969 ``source``: ``FolderName`` or ``NamePattern`` which can include wildcard characters,
970 for one or more folders to be copied.
972 ``destination``: ``FolderName`` where the single ``source`` folder is to be copied
973 or ``FolderName`` where the multiple folders from ``source`` are to be copied.
974 If ``FolderName`` does not exist, it is created.
976 ``overwrite``: if ``True`` (default), folders and their content may be overwritten.
977 Defaults to ``True``. ``CopyFile`` will fail if ``destination`` has the read-only
978 attribute set, regardless of the value of ``overwrite``.
980 ``True`` if at least one folder has been copied. ``False`` if an error occurred.
981 An error also occurs if a ``source`` using wildcard characters doesn't match any folders.
982 The method stops on the first error it encounters.
983 No attempt is made to roll back or undo any changes made before an error occurs.
985 - If ``destination`` does not exist, it is created.
986 - Wildcard characters are not allowed in ``destination``.
990 def CreateFolder(self, foldername: FILE) -> bool:
992 Creates the specified ``foldername``.
993 If the specified folder has a parent folder that does not exist, it is created.
995 foldername: a string representing the folder to create. It must not exist.
997 ``True`` if ``foldername`` is a valid folder name, does not exist and creation was successful.
998 ``False`` otherwise, including when ``foldername`` is a file.
1003 self, filename: FILE, overwrite: bool = ..., encoding: str = ...
1006 Creates a specified file and returns a ``TextStream`` service instance that can be used
1007 to write to the file.
1008 The method returns ``None`` if an error occurred.
1010 ``filename``: the name of the file to be created.
1012 ``overwrite``: determines if ``filename`` can be overwritten (default = ``True``).
1014 ``encoding``: the character set to be used. The default encoding is "UTF-8".
1018 def DeleteFile(self, filename: FILE) -> bool:
1020 Deletes one or more files.
1021 The files to be deleted must not be readonly.
1023 ``filename``: ``FileName`` or ``NamePattern`` which can include wildcard characters,
1024 for one or more files to be deleted.
1026 ``True`` if at least one file has been deleted. ``False`` if an error occurred.
1027 An error also occurs if ``fileName`` using wildcard characters doesn't match any files.
1028 The method stops on the first error it encounters.
1029 No attempt is made to roll back or undo any changes made before an error occurs.
1033 def DeleteFolder(self, foldername: FILE) -> bool:
1035 Deletes one or more folders.
1036 The folders to be deleted must not be readonly.
1038 ``foldername``: ``FolderName`` or ``NamePattern`` which can include wildcard characters,
1039 for one or more Folders to be deleted.
1041 ``True`` if at least one folder has been deleted. ``False`` if an error occurred.
1042 An error will also occur if the ``foldername`` parameter uses wildcard characters and
1043 does not match any folders.
1044 The method stops immediately after it encounters an error.
1045 The method does not roll back nor does it undo changes made before the error occurred.
1049 def ExtensionFolder(self, extension: str) -> str:
1051 Returns a string containing the folder where the specified extension package is installed.
1053 ``extension``: a string value with the ID of the extension.
1054 If the extension is not installed, an exception is raised.
1058 def FileExists(self, filename: FILE) -> bool:
1060 Return ``True`` if the given file exists.
1062 ``filename``: a string representing the file to be tested.
1064 ``True`` if ``filename`` is a valid File name and it exists.
1065 ``False`` otherwise, including when ``filename`` is a folder.
1069 def Files(self, foldername: FILE, filter: str = ..., includesubfolders: bool = ...) -> Tuple[str, ...]:
1071 Gets a tuple of the ``FileNames`` stored in the given folder.
1072 If the argument ``foldername`` specifies a folder that does not exist, an exception is raised.
1073 The resulting tuple may be filtered with wildcards.
1075 ``foldername``: the folder to explore.
1077 ``filter``: contains wildcards ("?" and "*") to limit the list to the relevant files
1080 ``includesubfolders``: set this argument to ``True`` to include the contents of
1081 subfolders (Default = ``False``).
1083 A tuple of strings, each entry is the ``FileName`` of an existing file.
1087 def FolderExists(self, foldername: FILE) -> bool:
1089 Returns ``True`` if the given folder name exists.
1091 ``foldername``: a string representing a folder.
1093 ``True`` if ``folderName`` is a valid folder name and it exists.
1094 ``False`` otherwise, including when ``foldername`` is a file.
1098 def GetBaseName(self, filename: FILE) -> str:
1100 Returns the ``BaseName`` (equal to the last component) of a file or folder name, without its extension.
1101 The method does not check for the existence of the specified file or folder.
1103 ``filename``: path and file name
1105 The ``BaseName`` of the given file name. It may be the empty string.
1109 def GetExtension(self, filename: FILE) -> str:
1111 Returns the extension part of a ``File-`` or ``FolderName``, without the dot (.).
1112 The method does not check for the existence of the specified file or folder.
1114 ``filename``: path and file name
1116 The extension without a leading dot. May be empty.
1120 def GetFileLen(self, filename: FILE) -> int:
1122 Returns the length of a file in bytes.
1124 ``filename``: a string representing an existing file.
1126 File size if ``filename`` exists.
1130 def GetFileModified(self, filename: FILE) -> datetime.datetime:
1132 Returns the last modified date for the given file.
1134 ``filename``: a string representing an existing file.
1136 The modification date and time.
1140 def GetName(self, filename: FILE) -> str:
1142 Returns the last component of a ``File-`` or ``FolderName``.
1143 The method does not check for the existence of the specified file or folder.
1145 ``filename``: path and file name
1147 The last component of the full file name in native operating system format.
1151 def GetParentFolderName(self, filename: FILE) -> FILE:
1153 Returns a string containing the name of the parent folder of the last component in a specified
1154 ``File-`` or ``FolderName``.
1155 The method does not check for the existence of the specified file or folder.
1157 ``filename``: path and file name.
1159 A folder name including its final path separator.
1163 def GetTempName(self, extension: str = ...) -> FILE:
1165 Returns a randomly generated temporary file name that is useful for performing
1166 operations that require a temporary file : the method does not create any file.
1168 ``extension``: the extension of the temporary file name (Default = "").
1170 A ``FileName`` as a string.
1171 By default, the returned file name does not have an extension (suffix).
1172 Use the extension parameter to specify the extension of the file name to be generated.
1173 The folder part of the returned string is the system's temporary folder.
1179 algorithm: Literal['MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512'],
1182 Gets a hexadecimal string representing a checksum of the given file.
1184 ``filename``: a string representing a file.
1186 ``algorithm``: the hashing algorithm to use.
1188 The requested checksum as a string. Hexadecimal digits are lower-cased.
1189 A zero-length string when an error occurred.
1191 The supported hashing algorithms are:
1201 def MoveFile(self, source: FILE, destination: FILE) -> bool:
1203 Moves one or more files from one location to another.
1204 Returns ``True`` if at least one file has been moved or ``False`` if an error occurred.
1205 An error will also occur if the source parameter uses wildcard characters and does not match any files.
1207 The method stops immediately after it encounters an error. The method does not
1208 roll back nor does it undo changes made before the error occurred.
1210 ``source``: ``FileName`` or ``NamePattern`` which can include wildcard characters,
1211 for one or more files to be moved.
1213 ``destination``: if ``source`` is an existing file name then ``destination`` indicates
1214 the new path and file name of the moved file. If the move operation involves multiple files,
1215 then ``destination`` must be a folder name. If it does not exist, it is created.
1216 If ``source`` and ``destination`` have the same parent folder, the method will rename
1218 Wildcard characters are not allowed in ``destination``.
1220 ``True`` if at least one file has been moved. ``False`` if an error occurred.
1224 def MoveFolder(self, source: FILE, destination: FILE) -> bool:
1226 Moves one or more folders from one location to another.
1227 Returns ``True`` if at least one folder has been moved or ``False`` if an error occurred.
1228 An error will also occur if the source parameter uses wildcard characters and does
1229 not match any folders.
1231 The method stops immediately after it encounters an error. The method does not roll
1232 back nor does it undo changes made before the error occurred.
1234 ``source``: ``FolderName`` or ``NamePattern`` which can include wildcard characters,
1235 for one or more folders to be moved.
1237 ``destination``: if the move operation involves a single folder, then ``destination``
1238 is the name and path of the moved folder. It must not exist.
1239 If multiple folders are being moved, then ``destination`` designates where the folders
1240 in ``source`` will be moved into. If ``destination`` does not exist, it is created.
1241 Wildcard characters are not allowed in ``destination``.
1243 ``True`` if at least one folder has been moved. ``False`` if an error occurred.
1247 def Normalize(self, filename: FILE) -> FILE:
1249 Returns a string containing the normalized path name by collapsing redundant separators and up-level
1250 references. For instance, the path names ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` are all
1251 normalized to ``A/B``.
1253 On Windows, forward slashes ``/`` are converted to backward slashes \\\.
1255 ``filename``: a string representing a valid path name.
1256 The file or directory represented by this argument may not exist.
1258 The normalized file name.
1262 def OpenTextFile(self,
1264 iomode: Literal[1, 2, 8] = ...,
1266 encoding: str = ...,
1269 Opens a specified file and returns a ``TextStream`` object that can be used to read from,
1270 write to, or append to the file.
1272 ``filename``: identifies the file to open.
1274 ``iomode``: indicates input/output mode. It can be one of three constants:
1275 ``filesystem.ForReading`` (default), ``filesystem.ForWriting``, or ``filesystem.ForAppending``.
1277 ``create``: boolean value that indicates whether a new file can be created if the specified
1278 filename doesn't exist. The value is ``True`` if a new file and its parent folders
1279 may be created. ``False`` if they aren't created. Defaults to ``False``.
1281 ``encoding``: the character set that should be used. Defaults to "UTF-8".
1283 A ``TEXTSTREAM`` instance representing the opened file or ``None`` if an error occurred.
1284 The method does not check if the file is really a text file. It doesn't check either
1285 if the given encoding is implemented in LibreOffice nor if it is the right one.
1290 defaultfile: FILE = ...,
1291 mode: Literal['OPEN', 'SAVE'] = ...,
1295 Opens a dialog box to open or save a file.
1297 If the ``SAVE`` mode is set and the picked file exists, a warning message will be displayed.
1299 ``defaultfile``: this argument is a string composed of a folder and file name.
1300 The folder part indicates the folder that will be shown when the dialog opens
1301 (default = the last selected folder). The file part designates the default file to open or save.
1303 ``mode``: a string value that can be either "OPEN" (for input files) or
1304 "SAVE" (for output files). The default value is "OPEN".
1306 ``filter``: the extension of the files displayed when the dialog is opened
1307 (default = no filter).
1309 The selected FileName in ``filesystem.FileNaming`` format or "" if the dialog was cancelled.
1313 def PickFolder(self, defaultfolder: FILE = ..., freetext: str = ...) -> FILE:
1315 Display a dialog box to select a folder.
1317 ``defaultfolder``: the folder from which to start. Default = the last selected folder.
1319 ``freetext``: text to display in the dialog. Defaults to "".
1321 The selected folder in ``filesystem.FileNaming`` notation.
1322 A zero-length string if the dialog was cancelled.
1325 def SubFolders(self,
1328 includesubfolders: bool = ...
1329 ) -> Tuple[str, ...]:
1331 Returns a tuple of strings corresponding to the folders stored
1332 in the given ``foldername``.
1333 The list may be filtered with wildcards.
1335 ``foldername``: a string representing a folder. The folder must exist. ``foldername`` must not
1338 ``filter``: a string containing wildcards ("?" and "*") that will be applied to the resulting
1339 list of folders (default = "").
1341 ``includesubfolders``: set this argument to ``True`` to include the contents of
1342 subfolders (Default = ``False``).
1346 # #########################################################################
1348 # #########################################################################
1349 class SF_L10N(SFServices):
1351 This service provides a number of methods related to the translation of strings
1352 with minimal impact on the program's source code.
1354 The methods provided by the L10N service can be used mainly to:
1355 - Create POT files that can be used as templates for translation of all strings in the program.
1356 - Get translated strings at runtime for the language defined in the Locale property.
1360 """ The folder containing the ``PO`` files """
1361 Languages: Tuple[str, ...]
1362 """ A list of all the base names (without the ``.po`` extensions found in the specified ``folder``. """
1364 """ The currently active ``language-COUNTRY`` combination. """
1366 def AddText(self, context: str = ..., msgid: str = ..., comment: str = ...) -> bool:
1368 Adds a new entry in the list of localizable strings. It must not exist yet.
1370 ``context``: the key to retrieve the translated string with the GetText method.
1371 This parameter has a default value of "".
1373 ``msgid``: the untranslated string, which is the text appearing in the program code. ``msgid``
1376 The ``msgid`` becomes the key to retrieve the translated string via
1377 the ``GetText()`` method when ``context`` is empty.
1378 The ``msgid`` string may contain any number of placeholders (%1 %2 %3 ...) for dynamically
1379 modifying the string at runtime.
1381 ``comment``: optional comment to be added alongside the string to help translators.
1383 ``True`` if successful.
1387 def AddTextsFromDialog(self, dialog: DIALOG) -> bool:
1389 Add all fixed text strings of a dialog to the list of localizable text strings.
1392 - The title of the dialog.
1393 - The caption associated with next control types: Button, CheckBox, FixedLine, FixedText, GroupBox and RadioButton.
1394 - The content of list- and combo boxes.
1395 - The tip- or help text displayed when the mouse is hovering the control.
1397 The current method has method ``SFDialogs.SF_Dialog.GetTextsFromL10N()`` as counterpart.
1398 The targeted dialog must not be open when the current method is run.
1400 ``dialog``: a SFDialogs.Dialog service instance
1402 ``True`` when successful.
1406 def ExportToPOTFile(self, filename: FILE, header: str = ..., encoding: str = ...) -> bool:
1408 Export a set of untranslated strings as a POT file.
1409 The set of strings has been built either by a succession of AddText() methods
1410 or by a successful invocation of the L10N service with the ``FolderName`` argument.
1411 The generated file should pass successfully the ``"msgfmt --check 'the pofile'"`` GNU command.
1413 ``filename``: the complete file name (in ``filesystem.FileNaming`` notation)
1414 to export to. If it exists, it is overwritten without warning.
1416 ``header``: comments that will appear on top of the generated file. Do not include
1417 any leading "#". If the string spans multiple lines, insert escape sequences (``\\n``) where
1418 relevant. A standard header will be added anyway. Defaults to "".
1420 ``encoding``: the character set that should be used. Defaults to "UTF-8".
1422 ``True`` if successful.
1426 def GetText(self, msgid: str, *args: Any) -> str:
1428 Gets the translated string corresponding to the given ``msgid`` argument.
1429 A list of arguments may be specified to replace the placeholders (%1, %2, ...) in the string.
1431 ``msgid``: the untranslated string, which is the text appearing in the program code.
1432 It must not be empty. It may contain any number of placeholders (%1 %2 %3 ...) that can be used
1433 to dynamically insert text at runtime.
1435 Besides using a single ``msgid`` string, this method also accepts the following formats:
1436 - the untranslated text (``msgid``)
1437 - the reference to the untranslated text (``context``)
1438 - both (``context|msgId``), use the pipe character as delimiter.
1440 ``args``: values to be inserted into the placeholders.
1441 Any variable type is allowed, however only strings, numbers and dates will be considered.
1443 The translated string. If no translated string is found, the method returns the untranslated
1444 string after replacing the placeholders with the specified arguments.
1448 # #########################################################################
1450 # #########################################################################
1451 class SF_Platform(SFServices, metaclass = ...):
1453 The ``Platform`` service implements a collection of properties about the actual execution environment
1454 and context, such as :
1455 - the hardware platform
1456 - the operating system
1457 - the LibreOffice version
1459 All its properties are read-only.
1463 """ The hardware bit architecture. Example: '32bit' or '64bit'. """
1465 """ The computer's network name. """
1467 """ The number of central processing units. """
1469 """ The name of the currently logged user. """
1470 Extensions: Tuple[str, ...]
1471 """ An array of strings containing the internal IDs of all installed extensions. """
1472 FilterNames: Tuple[str, ...]
1473 """ An array of strings containing the available document import and export filter names. """
1474 Fonts: Tuple[str, ...]
1475 """ An array of strings containing the names of all available fonts. """
1477 """ The locale used for numbers and dates as a string in the format "la-CO" (language-COUNTRY). """
1479 """ The locale of the operating system as a string in the format "la-CO" (language-COUNTRY).
1480 This is equivalent to the ``SystemLocale`` property. """
1482 """ The machine type. Examples are: 'i386' or 'x86_64'. """
1484 """ The locale of the user interface as a string in the format "la-CO" (language-COUNTRY). """
1486 """ The actual LibreOffice version expressed as ``LibreOffice w.x.y.z (The Document Foundation)``. """
1488 """ The operating system type. Example: 'Darwin, Linux' or 'Windows'. """
1490 """ A single string identifying the underlying platform with as much useful and human-readable information
1491 as possible. Example: ``Linux-5.8.0-44-generic-x86_64-with-glibc2.32``. """
1493 """ The operating system's release. Example: ``5.8.0-44-generic``. """
1495 """ The operating system's build or version. Example: ``#50-Ubuntu SMP Tue Feb 9 06:29:41 UTC 2021 `` """
1496 Printers: Tuple[str, ...]
1497 """ The list of available printers. The default printer is put in the first position of the list
1500 """ The real processor name. Example: ``amdk6``. This property may return the same value as the ``Machine``
1503 """ The version of the Python interpreter being used as a string in the format ``Python major.minor.patchlevel``
1504 (ex: ``Python 3.9.7``). """
1506 """ The locale of the operating system as a string in the format "la-CO" (language-COUNTRY).
1507 This is equivalent to the ``Locale`` property. """
1508 UserData: DICTIONARY
1509 """ Returns a ``Dictionary`` instance containing key-value pairs in relation with the
1510 ``Tools - Options - User Data`` dialog. """
1512 # #########################################################################
1514 # #########################################################################
1515 class SF_Region(SFServices, metaclass = ...):
1517 The "Region" service gathers a collection of functions about languages, countries and timezones
1520 - Numbers and dates formatting
1522 - Timezones conversions
1523 - Numbers transformed to text in any supported language
1526 def Country(self, region: str = ...) -> str:
1528 Gets the country name in English corresponding to a given region.
1530 ``region``: formatted as "la-CO" or "CO".
1534 def Currency(self, region: str = ...) -> str:
1536 Gets the ISO 4217 currency code of the specified region.
1538 ``region``: formatted as "la-CO" or "CO".
1542 def DatePatterns(self, region=...) -> Tuple[str, ...]:
1544 Gets an array of strings containing the date acceptance patterns for the specified region.
1546 ``region``: formatted as "la-CO".
1550 def DateSeparator(self, region: str = ...) -> str:
1552 Returns the date separator used in the given region.
1554 ``region``: formatted as "la-CO".
1558 def DayAbbrevNames(self, region: str = ...) -> Tuple[str, ...]:
1560 Gets an array of strings containing the list of abbreviated weekday names in the specified language.
1562 ``region``: formatted as "la-CO" or "la".
1566 def DayNames(self, region: str = ...) -> Tuple[str, ...]:
1568 Gets an array of strings containing the list of weekday names in the specified language.
1570 ``region``: formatted as "la-CO" or "la".
1574 def DayNarrowNames(self, region: str = ...) -> Tuple[str, ...]:
1576 Gets a zero-based array of strings containing the list of the initials of weekday names
1577 in the specified language.
1579 ``region``: formatted as "la-CO" or "la".
1583 def DecimalPoint(self, region: str = ...) -> str:
1585 Gets the decimal separator used in numbers in the specified region.
1587 ``region``: formatted as "la-CO".
1591 def Language(self, region: str = ...) -> str:
1593 Gets the name of the language, in English, of the specified region.
1595 ``region``: formatted as "la-CO" or "la".
1599 def ListSeparator(self, region: str = ...) -> str:
1601 Gets the list separator used in the specified region.
1603 ``region``: formatted as "la-CO".
1607 def MonthAbbrevNames(self, region: str = ...) -> Tuple[str, ...]:
1609 Gets a zero-based array of strings containing the list of abbreviated month names
1610 in the specified language.
1612 ``region``: formatted as "la-CO".
1616 def MonthNames(self, region: str = ...) -> Tuple[str, ...]:
1618 Gets an array of strings containing the list of month names in the specified language.
1620 ``region``: formatted as "la-CO" or "la".
1624 def MonthNarrowNames(self, region: str = ...) -> Tuple[str, ...]:
1626 Gets an array of strings containing the list of the initials of month names in the specified language.
1628 ``region``: formatted as "la-CO" or "la".
1632 def ThousandSeparator(self, region: str = ...) -> str:
1634 Gets the thousands separator used in numbers in the specified region.
1636 ``region``: formatted as "la-CO".
1640 def TimeSeparator(self, region: str = ...) -> str:
1642 Gets the separator used to format times in the specified region.
1644 ``region``: formatted as "la-CO".
1648 def DSTOffset(self, localdatetime: datetime.datetime, timezone: str, locale: str = ...) -> int:
1650 Computes the additional Daylight Saving Time (DST) offset, in minutes, that is applicable
1651 to a given region and timezone.
1653 ``localdatetime``: the local date and time to consider.
1655 ``timezone``: the timezone for which the offset will be calculated.
1657 ``locale``: the locale specifying the country for which the offset will be calculated,
1658 given either in "la-CO" or "CO" formats. The default value is the locale defined
1659 in the ``OfficeLocale`` property of the ``Platform`` service.
1663 def LocalDateTime(self, utcdatetime: datetime.datetime, timezone: str, locale: str = ...) -> datetime.datetime:
1665 Computes the local date and time from a UTC date and time.
1667 ``utcdatetime``: the UTC date and time, expressed using a date object.
1669 ``timezone``: the timezone for which the local time will be calculated.
1671 ``locale``: the locale specifying the country for which the offset will be calculated,
1672 given either in "la-CO" or "CO" formats. The default value is the locale defined
1673 in the ``OfficeLocale`` property of the ``Platform`` service.
1677 def Number2Text(self, number: Union[int, float, str], locale: str = ...) -> str:
1679 Converts numbers and monetary values into written text for any of the currently supported languages.
1681 ``number``: the number to be converted into written text.
1682 It can be provided either as a numeric type or as a string. When a string is provided,
1683 it can be preceded by a prefix informing how the numbers should be written.
1684 It is also possible to include ISO 4217 currency codes.
1686 ``locale``: the locale defining the language into which the number will be converted to,
1687 given either in "la-CO" or "la" formats.
1688 The default value is the locale defined in the ``OfficeLocale`` property of the ``Platform``
1691 The converted number or monetary value in letters.
1695 def TimeZoneOffset(self, timezone: str, locale: str = ...) -> int:
1697 Gets the offset between GMT and the given timezone and locale, in minutes.
1699 ``timezone``: the timezone for which the offset to the GMT will be calculated.
1701 ``locale``: the locale specifying the country for which the offset will be calculated,
1702 given either in "la-CO" or "CO" formats.
1703 The default value is the locale defined in the ``OfficeLocale`` property
1704 of the ``Platform`` service.
1708 def UTCDateTime(self, localdatetime: datetime.datetime, timezone: str, locale: str = ...) -> datetime.datetime:
1710 Gets the UTC date and time considering a given local date and time in a timezone.
1712 ``localdatetime``: the local date and time in a specific timezone, expressed as a date.
1714 ``timezone``: the timezone for which the ``localdatetime`` argument is given.
1716 ``locale``: the locale specifying the country for which the ``localdatetime`` argument is given,
1717 expressed either in "la-CO" or "CO" formats. The default value is the locale defined
1718 in the ``OfficeLocale`` property of the ``Platform`` service.
1722 def UTCNow(self, timezone: str, locale: str = ...) -> datetime.datetime:
1724 Gets the current UTC date and time, given a timezone and a locale.
1726 ``timezone``: the timezone for which the current UTC time will be calculated.
1728 ``locale``: the locale specifying the country for which the current UTC time will be calculated,
1729 expressed either in "la-CO" or "CO" formats. The default value is the locale defined
1730 in the ``OfficeLocale`` property of the ``Platform`` service.
1734 # #########################################################################
1736 # #########################################################################
1737 class SF_Session(SFServices, metaclass = ...):
1739 The Session service gathers various general-purpose methods about:
1741 - the invocation of external scripts or programs
1746 # Class constants Where to find an invoked library ?
1747 SCRIPTISEMBEDDED: Literal["document"]
1748 """ The invoked library is in the document (Basic + Python). """
1749 SCRIPTISAPPLICATION: Literal["application"]
1750 """ The invoked library is in any shared library (Basic). """
1751 SCRIPTISPERSONAL: Literal["user"]
1752 """ The invoked library is in My Macros (Python). """
1753 SCRIPTISPERSOXT: Literal["user:uno_packages"]
1754 """ The invoked library is in an extension installed for the current user (Python). """
1755 SCRIPTISSHARED: Literal["share"]
1756 """ The invoked library is in LibreOffice macros (Python). """
1757 SCRIPTISSHAROXT: Literal["share:uno_packages"]
1758 """ The invoked library is in an extension installed for all users (Python). """
1759 SCRIPTISOXT: Literal["uno_packages"]
1760 """ The invoked library is in an extension but the installation parameters are unknown (Python). """
1763 def ExecuteBasicScript(
1764 cls, scope: str = ..., script: str = ..., *args: Optional[Any]
1767 Execute the Basic script given its name and location and fetch its result if any.
1769 If the script returns nothing, which is the case of procedures defined with Sub,
1770 the returned value is ``None``.
1772 ``scope``: string specifying where the script is stored.
1774 ``script``: string specifying the script to be called in the format
1775 "library.module.method" as a case-sensitive string.
1777 ``args``: the arguments to be passed to the called script.
1779 Argument ``scope`` can be either:
1780 - "document" (= ``session.SCRIPTISEMBEDDED``)
1781 - "application" (= ``session.SCRIPTISAPPLICATION``).
1783 About argument ``script``:
1784 - The library is loaded in memory if necessary.
1785 - The module must not be a class module.
1786 - The method may be a ``Sub`` or a ``Function``.
1788 The value returned by the called script.
1793 def ExecuteCalcFunction(cls, calcfunction: str, *args: Any) -> Any:
1795 Execute a Calc function using its English name and based on the given arguments.
1796 If the arguments are arrays, the function is executed as an array formula.
1798 ``calcfunction``: the name of the Calc function to be called, in English.
1800 ``args``: the arguments to be passed to the called Calc function. Each argument may be either
1801 - a string, a numeric value, a bool or a datetime.datetime instance
1802 - a tuple or a tuple of tuples combining those types
1803 - a com.sun.star.table.XCellRange UNO object
1805 The value returned by the function as a scalar or a tuple of tuples.
1810 def ExecutePythonScript(cls, scope: str = ..., script: str = ..., *args: Any) -> Any:
1812 Execute the Python script given its location and name, fetch its result if any.
1813 Result can be a single value or an array of values.
1815 If the script is not found, or if it returns nothing, the returned value is ``None``.
1817 ``scope``: one of the applicable constants listed. See Notes.
1819 ``script``: either "library/module.py$method" or "module.py$method"
1820 or "myExtension.oxt|myScript|module.py$method" as a case-sensitive string.
1822 Arg ``scope`` can be either
1823 - "document" (= ``session.SCRIPTISEMBEDDED``)
1824 - "application" (= ``session.SCRIPTISAPPLICATION``)
1825 - "user" (= ``session.SCRIPTISPERSONAL``)
1826 - "user:uno_packages" (= ``session.SCRIPTISPERSOXT``)
1827 - "share" (= ``session.SCRIPTISSHARED``). Default value.
1828 - "share:uno_packages" (= ``session.SCRIPTISSHAROXT``)
1829 - "uno_packages" (= ``session.SCRIPTISOXT``)
1831 About argument ``script``:
1832 - ``library``: The folder path to the Python module.
1833 - ``myScript``: The folder containing the Python module.
1834 - ``module.py``: The Python module.
1835 - ``method``: The Python function.
1837 The value(s) returned by the call to the script. If > 1 values, enclosed in a tuple.
1841 def GetPDFExportOptions(self) -> DICTIONARY:
1843 Returns the current PDF export settings defined in the ``PDF Options`` dialog, which can be accessed
1844 by choosing ``File - Export as - Export as PDF``.
1846 A ``Dictionary`` object wherein each key represents an export option and the corresponding
1847 value is the current PDF export setting.
1851 def HasUnoMethod(self, unoobject: UNO, methodname: str) -> bool:
1853 Returns ``True`` if a UNO object contains the given method.
1855 ``unoobject``: the object to inspect.
1857 ``methodname``: the name of the method as a string. The search is case-sensitive.
1859 ``False`` when the method is not found or when an argument is invalid.
1863 def HasUnoProperty(self, unoobject: UNO, propertyname: str) -> bool:
1865 Returns ``True`` if a UNO object contains the given property.
1867 ``unoobject``: the object to inspect.
1869 ``propertyname``: the name of the property as a string. The search is case-sensitive.
1871 ``False`` when the property is not found or when an argument is invalid.
1876 def OpenURLInBrowser(cls, url: str) -> None:
1878 Opens a given URL in the default browser.
1880 ``url``: The URL to open in the browser.
1884 def RunApplication(self, command: str, parameters: str) -> bool:
1886 Executes an arbitrary system command.
1888 ``command``: the command to execute.
1889 This may be an executable file or a file which is registered with an application
1890 so that the system knows what application to launch for that file. A file must be
1891 expressed in the current ``filesystem.FileNaming`` notation.
1893 ``parameters``: a list of space separated parameters as a single string.
1894 The method does not validate the given parameters, but only passes them to the specified
1897 ``True`` if the command was launched successfully.
1906 filenames: str = ...,
1907 editmessage: bool = ...,
1910 Send a message (with or without attachments) to recipients from the user's mail client.
1911 The message may be edited by the user before sending or, alternatively, be sent immediately.
1913 ``recipient``: an email addresses (To recipient).
1915 ``cc``: a comma-delimited list of email addresses (carbon copy). Defaults to ''.
1917 ``bcc``: a comma-delimited list of email addresses (blind carbon copy). Defaults to ''.
1919 ``subject``: the header of the message. Defaults to ''.
1921 ``body``: the unformatted text of the message. Defaults to ''.
1923 ``filenames``: a comma-separated list of filenames to attach to the mail.
1924 ``filesystem.FileNaming`` naming conventions apply. Defaults to ''.
1926 ``editmessage``: when ``True`` (default) the message is editable before being sent.
1930 def SetPDFExportOptions(self, pdfoptions: DICTIONARY) -> bool:
1932 Modifies the PDF export settings defined in the ``PDF Options`` dialog, which can be accessed
1933 by choosing ``File - Export as - Export as PDF``.
1935 The new settings can be used by the ``ExportAsPDF()`` method from the ``Document`` service.
1937 ``pdfoptions``: a ``Dictionary`` object that defines the PDF export settings to be changed.
1938 Each key-value pair represents an export option and its new value.
1940 ``True`` when successful.
1944 def UnoMethods(self, unoobject: UNO) -> Tuple[str, ...]:
1946 Returns a tuple of the methods callable from an UNO object. The tuple may be empty.
1948 ``unoobject``: the object to inspect.
1952 def UnoObjectType(self, unoobject: UNO) -> str:
1954 Identify the UNO class of an UNO object.
1956 ``unoobject``: the object to inspect.
1958 ``com.sun.star. ...`` as a string or a zero-length string if the identification was not
1963 def UnoProperties(self, unoobject: UNO) -> Tuple[str, ...]:
1965 Returns a tuple of the properties callable from an UNO object. The tuple may be empty.
1967 ``unoobject``: the object to inspect.
1971 def WebService(self, uri: str) -> str:
1973 Get some web content from a URI.
1975 ``uri ``: text of the web service.
1977 The web page content of the URI.
1980 # #########################################################################
1982 # #########################################################################
1983 class SF_String(SFServices, metaclass = ...):
1985 Focus on string manipulation, regular expressions, encodings and hashing algorithms.
1986 The methods implemented in Basic that are redundant with Python builtin functions
1991 """ Carriage return (ASCII 13). """
1993 """ Carriage return + linefeed (ASCII 13 + 10). """
1995 """ Linefeed (ASCII 10). """
1997 """ Depending on the operating system, either Carriage return + Linefeed (ASCII 13 + 10)
1998 or Linefeed (ASCII 10). """
2000 """ Horizontal tabulation (ASCII 09). """
2005 algorithm: Literal['MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512'],
2008 Return a hexadecimal string representing a checksum of the given input string.
2010 ``inputstr``: the string to be hashed.
2012 ``algorithm``: the hashing algorithm to use.
2014 The requested checksum as a string. Hexadecimal digits are lower-cased.
2015 A zero-length string when an error occurred.
2017 The supported hashing algorithms are:
2029 dateformat: Literal['YYYY-MM-DD', 'DD-MM-YYYY', 'MM-DD-YYYY',
2030 'YYYY/MM/DD', 'DD/MM/YYYY', 'MM/DD/YYYY',
2031 'YYYY.MM.DD', 'DD.MM.YYYY', 'MM.DD.YYYY',
2032 'YYYY MM DD', 'DD MM YYYY', 'MM DD YYYY'] = ...,
2035 Return ``True`` if the string is a valid date respecting the given format.
2037 ``inputstr``: the input string.
2039 ``dateformat``: either ``YYYY-MM-DD`` (default), ``DD-MM-YYYY`` or ``MM-DD-YYYY``.
2040 The dash (-) may be replaced by a dot (.), a slash (/) or a space.
2042 ``True`` if the string contains a valid date and there is at least one character.
2043 ``False`` otherwise or if the date format is invalid.
2047 def IsEmail(self, inputstr: str) -> bool:
2049 Return ``True`` if the string is a valid email address.
2051 ``inputstr``: the input string.
2053 ``True`` if the string contains an email address and there is at least one character,
2054 ``False`` otherwise.
2058 def IsFileName(self, inputstr: str, osname: Literal['WINDOWS', 'LINUX', 'MACOS', 'SOLARIS'] = ...) -> bool:
2060 Return ``True`` if the string is a valid filename in a given operating system.
2062 ``inputstr``: the input string.
2064 ``osname``: the default is the current operating system on which the script is run.
2066 ``True`` if the string contains a valid filename and there is at least one character,
2071 def IsIBAN(self, inputstr: str) -> bool:
2073 Returns ``True`` if the input string is a valid International Bank Account Number.
2075 ``inputstr``: the input string.
2077 ``True`` if the string contains a valid IBAN number. The comparison is not case-sensitive.
2081 def IsIPv4(self, inputstr: str) -> bool:
2083 Return ``True`` if the string is a valid IPv4 address.
2085 ``inputstr``: the input string.
2087 ``True`` if the string contains a valid IPv4 address and there is at least one character,
2088 ``False`` otherwise.
2092 def IsLike(self, inputstr: str, pattern: str, casesensitive: bool = ...) -> bool:
2094 Returns True if the whole input string matches a given pattern containing wildcards.
2096 ``inputstr``: the input string.
2098 ``pattern``: the pattern as a string. The ``?`` represents any single character.
2099 The ``*`` represents zero, one, or multiple characters.
2101 ``casesensitive``: defaults to ``False``.
2103 ``True`` if a match is found. Zero-length input or pattern strings always return ``False``.
2107 def IsSheetName(self, inputstr: str) -> bool:
2109 Return ``True`` if the input string can serve as a valid Calc sheet name.
2111 The sheet name must not contain the characters ``[ ] * ? : / \\``
2112 or the character ``'`` (apostrophe) as first or last character.
2114 ``inputstr``: the input string.
2116 ``True`` if the string is validated as a potential Calc sheet name, ``False`` otherwise.
2120 def IsUrl(self, inputstr: str) -> bool:
2122 Return ``True`` if the string is a valid absolute URL (Uniform Resource Locator).
2124 ``inputstr``: the input string.
2126 ``True`` if the string contains a URL and there is at least one character, ``False`` otherwise.
2130 def SplitNotQuoted(self,
2132 delimiter: str = ...,
2133 occurrences: int = ...,
2134 quotechar: Literal["'", '"'] = ...,
2135 ) -> Tuple[str, ...]:
2137 Split a string on ``delimiter`` into an array. If ``delimiter`` is part of a quoted (sub)string,
2138 it is ignored. Use case: parsing of csv-like records containing quoted strings.
2140 ``inputstr``: the input string.
2142 ``delimiter``: a string of one or more characters that is used to delimit the input string.
2143 Defaults to ' ' (space).
2145 ``occurrences``: the maximum number of substrings to return (Default = 0, meaning no limit).
2147 ``quotechar``: the quoting character, either ``"`` (default) or ``'``.
2149 A tuple whose items are chunks of the input string, The ``delimiter`` is not included.
2153 def Wrap(self, inputstr: str, width: int = ..., tabsize: int = ...) -> Tuple[str, ...]:
2155 Wraps every single paragraph in text (a string) so every line is at most ``width`` characters long.
2157 ``inputstr``: the input string.
2159 ``width``: the maximum number of characters in each line. Defaults to 70.
2161 ``tabsize``: before wrapping the text, the existing TAB (ASCII 09) characters are replaced with
2162 spaces. ``TabSize`` defines the TAB positions at
2163 ``TabSize + 1, 2 * TabSize + 1 , ... N * TabSize + 1``. Defaults to 8.
2165 A tuple of output lines, without final newlines except the pre-existing line-breaks.
2166 Tabs are expanded. Symbolic line breaks are replaced by their hard equivalents.
2167 If the wrapped output has no content, the returned tuple is empty.
2171 # #########################################################################
2172 # SF_TextStream CLASS
2173 # #########################################################################
2174 class SF_TextStream(SFServices):
2176 The ``TextStream`` service is used to sequentially read from and write to files opened or created
2177 using the ScriptForge.FileSystem service.
2181 """ Used in read mode. A ``True`` value indicates that the end of the file has been reached.
2182 A test using this property should precede calls to the ``ReadLine()`` method. """
2184 """ The character set to be used. The default encoding is "UTF-8". """
2186 """ Returns the name of the current file either in URL format or in the native operating system's format,
2187 depending on the current value of the ``FileNaming`` property of the ``filesystem`` service. """
2188 IOMode: Literal['READ', 'WRITE', 'APPEND']
2189 """ The input/output mode. """
2191 """ The number of lines read or written so far. """
2193 """ Sets or returns the current delimiter to be inserted between two successive written lines.
2194 The default value is the native line delimiter in the current operating system. """
2196 def CloseFile(self) -> bool:
2198 Empties the output buffer if relevant. Closes the actual input or output stream.
2200 ``True`` if the closure was successful.
2204 def ReadAll(self) -> str:
2206 Returns all the remaining lines in the text stream as one string. Line breaks are NOT removed.
2207 The resulting string can be split in lines either by using the usual ``split()`` builtin function.
2209 The read lines. The string may be empty.
2211 The ``Line`` property is incremented only by 1.
2215 def ReadLine(self) -> str:
2217 Returns the next line in the text stream as a string. Line breaks are removed.
2219 The read line. The string may be empty.
2223 def SkipLine(self) -> None:
2225 Skips the next line when reading a ``TextStream`` file. This method can result in ``AtEndOfStream``
2226 being set to ``True``.
2230 def WriteBlankLines(self, lines: int) -> None:
2232 Writes a number of empty lines in the output stream.
2234 ``lines``: the number of lines to write.
2238 def WriteLine(self, line: str) -> None:
2240 Writes the given line to the output stream. A newline is inserted if relevant.
2242 ``line``: the line to write, may be the empty string.
2246 # #########################################################################
2248 # #########################################################################
2249 class SF_Timer(SFServices):
2251 The ``Timer`` service measures the amount of time it takes to run user scripts.
2253 A ``Timer`` measures durations. It can be:
2254 - Started, to indicate when to start measuring time.
2255 - Suspended, to pause measuring running time.
2256 - Resumed, to continue tracking running time after the Timer has been suspended.
2257 - Restarted, which will cancel previous measurements and start the Timer at zero.
2261 """ The actual running time elapsed since start or between start and stop (not considering suspended time). """
2263 """ ``True`` when timer is started or suspended. """
2265 """ ``True`` when timer is started and suspended. """
2266 SuspendDuration: float
2267 """ The actual time elapsed while suspended since start or between start and stop. """
2268 TotalDuration: float
2269 """ The actual time elapsed since start or between start and stop (including suspensions and running time).
2270 ``TotalDuration = Duration + SuspendDuration``. """
2272 def Continue(self) -> bool:
2274 Continue/Resume a suspended timer.
2276 ``True`` except if the timer is not in suspended state.
2280 def Restart(self) -> bool:
2282 Terminate the timer and restart a new clean timer.
2284 ``True`` except if the timer is inactive.
2288 def Start(self) -> bool:
2290 Start a new clean timer.
2292 ``True`` except if the timer is already started.
2296 def Suspend(self) -> bool:
2298 Suspend a running timer.
2300 ``True`` except if the timer is not started or already suspended.
2304 def Terminate(self) -> bool:
2306 Terminate a running timer.
2308 ``True`` except if the timer is neither started nor suspended.
2312 # #########################################################################
2314 # #########################################################################
2315 class SF_UI(SFServices, metaclass = ...):
2317 Class for the identification and the manipulation of the different windows composing the whole
2318 ``LibreOffice`` application:
2320 - Windows moving and resizing
2321 - Statusbar settings
2322 - Creation of new windows
2323 - Access to the underlying "documents"
2325 Windows can be designated using different ``WindowNames``:
2326 - a full path and file name
2327 - the last component of the full file name or even only the last component without its suffix
2328 - the title of the window
2329 - for new documents, something like "Untitled 1"
2330 - one of the special windows ``BASICIDE`` and ``WELCOMESCREEN``
2331 A ``WindowName`` is case-sensitive.
2334 MACROEXECALWAYS: Literal[2]
2335 """ Macros are always executed. """
2336 MACROEXECNEVER: Literal[1]
2337 """ Macros are never executed. """
2338 MACROEXECNORMAL: Literal[0]
2339 """ Macro execution depends on user settings. """
2342 """ A valid and unique WindowName for the currently active window. When the window cannot be identified,
2343 a zero-length string is returned. """
2346 """ The height of the active window in pixels. """
2348 """ The width of the active window in pixels. """
2351 """ The X coordinate of the active window, which is the distance to the left edge of the screen in pixels. """
2354 """ The Y coordinate of the active window, which is the distance to the top edge of the screen in pixels.
2355 This value does not consider window decorations added by your operating system, so even when the window
2356 is maximized this value may not be zero. """
2358 def Activate(self, windowname: str = ...) -> bool:
2360 Make the specified window active.
2362 ``windowname``: see definitions at ``SF_UI`` class level.
2364 ``True`` if the given window is found and can be activated.
2365 There is no change in the actual user interface if no window matches the selection.
2369 def CreateBaseDocument(self,
2371 embeddeddatabase: Literal['HSQLDB', 'FIREBIRD', 'CALC'] = ...,
2372 registrationname: str = ...,
2373 calcfilename: str = ...,
2376 Create a new LibreOffice Base document embedding an empty database of the given type.
2378 ``filename``: identifies the file to create. It must follow the ``FileSystem.FileNaming``
2379 notation. If the file already exists, it is overwritten without warning.
2381 ``embeddeddatabase``: either ``HSQLDB`` or ``FIREBIRD`` or ``CALC``. Defaults to ``HSQLDB``.
2383 ``registrationname``: the name used to store the new database in the databases register.
2384 If "" (default), no registration takes place. If the name already exists it is overwritten
2387 ``calcfilename``: only when ``embeddeddatabase`` = ``CALC``, the name of the file containing
2388 the tables as Calc sheets. The name of the file must be given in ``FileSystem.FileNaming``
2389 notation. The file must exist.
2391 A ``Base`` service instance.
2395 def CreateDocument(self,
2396 documenttype: Literal['', 'calc', 'draw', 'impress', 'math', 'writer',
2397 'Calc', 'Draw', 'Impress', 'Math', 'Writer',
2398 'CALC', 'DRAW', 'IMPRESS', 'MATH', 'WRITER'] = ...,
2399 templatefile: FILE = ...,
2401 ) -> Union[DOCUMENT, CALC, WRITER]:
2403 Create a new ``LibreOffice`` document of a given type or based on a given template.
2405 ``documenttype``: Calc, Writer, etc. If absent, a ``templatefile`` must be given.
2407 ``templatefile``: the full ``FileName`` of the template to build the new document on.
2408 If the file does not exist, the argument is ignored.
2409 The ``FileSystem`` service provides the ``TemplatesFolder`` and ``UserTemplatesFolder``
2410 properties to help to build the argument. Defaults to ''.
2412 ``hidden``: if ``True``, open in the background. Defaults to ``False``.
2413 To use with caution: activation or closure can only happen programmatically.
2415 A ``Document`` object or one of its subclasses.
2417 Use the ``CreateBaseDocument()`` method to create a new ``Base`` document.
2421 def Documents(self) -> Tuple[str, ...]:
2423 Returns the list of the currently open documents. Special windows are ignored.
2425 An array either of file names (in ``FileSystem.FileNaming`` notation) or of window titles
2426 for unsaved documents.
2432 windowname: Union[str, XComponent, XOfficeDatabaseDocument] = ...
2433 ) -> Union[BASE, CALC, DOCUMENT, FORMDOCUMENT, WRITER]:
2435 Returns a ``Document`` object referring to the active window or the given window.
2437 ``windowname``: when a string, see definitions in ``SF_UI``. If absent the active window is
2438 considered. When an object, must be a UNO object of types ``XComponent``
2439 or ``XOfficeDatabaseDocument``.
2441 A ``Document`` object or one of its subclasses.
2446 def Maximize(self, windowname: str = ...) -> None:
2448 Maximizes the active window or the given window.
2450 ``windowname``: see definitions in ``SF_UI``. If absent the active window is considered.
2454 def Minimize(self, windowname: str = ...) -> None:
2456 Minimizes the active window or the given window.
2458 ``windowname``: see definitions in ``SF_UI``. If absent the active window is considered.
2462 def OpenBaseDocument(self,
2463 filename: FILE = ...,
2464 registrationname: str = ...,
2465 macroexecution: Literal[0, 1, 2] = ...,
2468 Open an existing LibreOffice Base document and return a SFDocuments.Base object.
2470 ``filename``: identifies the file to open.
2471 It must follow the ``FileSystem.FileNaming`` notation. Defaults to ''.
2473 ``registrationname``: the name of a registered database.
2474 It is ignored if FileName <> "". Defaults to ''.
2476 ``macroexecution``: one of the MACROEXECxxx constants. Defaults to ``MACROEXECNORMAL``.
2482 def OpenDocument(self,
2484 password: str = ...,
2485 readonly: bool = ...,
2487 macroexecution: Literal[0, 1, 2] = ...,
2488 filtername: str = ...,
2489 filteroptions: str = ...,
2490 ) -> Union[DOCUMENT, CALC, WRITER]:
2492 Open an existing LibreOffice document with the given options.
2494 ``filename``: identifies the file to open. It must follow the ``FileSystem.FileNaming``
2497 ``password``: to use when the document is protected. If wrong or absent while the document
2498 is protected, the user will be prompted to enter a password.
2500 ``readonly``: defaults to ``False``.
2502 ``hidden``: if ``True``, open in the background. Defaults to ``False``.
2503 ``True`` to use with caution: activation or closure can only happen programmatically.
2505 ``macroexecution``: one of the MACROEXECxxx constants. Defaults to ``MACROEXECNORMAL``.
2507 ``filtername``: the name of a filter that should be used for loading the document.
2508 If present, the filter must exist. Defaults to ''.
2510 ``filteroptions``: an optional string of options associated with the filter.
2512 A ``Document`` object or one of its subclasses, or
2513 None if the opening failed, including when due to a user decision.
2517 def Resize(self, left: int = ..., top: int = ..., width: int = ..., height: int = ...) -> None:
2519 Resizes and/or moves the active window. Negative or absent arguments are ignored.
2520 If the window was minimized or without arguments, it is restored.
2522 ``left``: distance from left edge of screen.
2524 ``top``: distance from top of screen.
2526 ``width``: width of the window.
2528 ``height``: height of the window.
2532 def RunCommand(self, command: str, *args: Any, **kwargs: Any) -> None:
2534 Runs a UNO command on the current window. Commands can be run with or without arguments.
2535 Arguments are not validated before running the command. If the command or its arguments are invalid,
2536 then nothing will happen.
2538 ``command``: case-sensitive string containing the UNO command name.
2539 The inclusion of the prefix ".uno:" in the command is optional.
2540 The command itself is not checked for correctness.
2542 ``args, kwargs``: use either pairs of ("name", value) positional arguments
2543 or pairs of name = value keyword arguments.
2547 def SetStatusbar(self, text: str = ..., percentage: Union[int, float] = ...) -> None:
2549 Display a text and a progressbar in the status bar of the active window.
2550 Any subsequent calls in the same macro run refer to the same status bar of the same window,
2551 even if the window is not active anymore.
2552 A call without arguments resets the status bar to its normal state.
2554 ``text``: the optional text to be displayed before the progress bar. Defaults to ''.
2556 ``percentage``: the optional degree of progress between 0 and 100.
2559 def ShowProgressBar(self, title: str = ..., text: str = ..., percentage: Union[int, float] = ...) -> None:
2561 Display a non-modal dialog box. Specify its title, an explicatory text and the progress
2562 on a progressbar. A call without arguments erases the progress bar dialog.
2563 The box will anyway vanish at the end of the macro run.
2565 ``title``: the title appearing on top of the dialog box (Default = ``ScriptForge``).
2567 ``text``: the optional text to be displayed above the progress bar. Defaults to ''.
2569 ``percentage``: the degree of progress between 0 and 100.
2573 def WindowExists(self, windowname: str) -> bool:
2575 Returns ``True`` if the specified window exists.
2577 ``windowname``: see the definitions in ``SF_UI``.
2579 ``True`` if the given window is found.
2584 # #####################################################################################################################
2585 # SFDatabases CLASS (alias of SFDatabases Basic library) ###
2586 # #####################################################################################################################
2589 The SFDatabases class manages databases embedded in or connected to Base documents.
2590 The associated services include the ``Database``, ``Dataset`` and ``Datasheet`` services.
2593 # #########################################################################
2595 # #########################################################################
2596 class SF_Database(SFServices):
2598 Each instance of the current class represents a single database, stored in or connected
2599 to a ``Base`` document, with essentially its tables, queries and data.
2601 The exchanges with the database are done in SQL only.
2602 To make them more readable, use optionally square brackets to surround table/query/field names
2603 instead of the (RDBMS-dependent) normal surrounding character.
2605 ``SQL`` statements may be run in direct or indirect modes. In direct mode the statement is transferred
2606 literally without syntax checking nor review to the database engine.
2609 Queries: Tuple[str, ...]
2610 """ The list of stored queries. """
2611 Tables: Tuple[str, ...]
2612 """ The list of stored tables. """
2614 """ The ``UNO`` object representing the current connection (``com.sun.star.sdbc.XConnection``). """
2616 """ The ``UNO`` object representing the metadata describing the database system attributes
2617 (``com.sun.star.sdbc.XDatabaseMetaData``). """
2619 def CloseDatabase(self) -> None:
2621 Close the current database connection.
2625 def Commit(self) -> None:
2627 Commits all updates done since the previous ``Commit`` or ``Rollback`` call.
2628 This method is ignored if commits are done automatically after each SQL statement,
2629 i.e. the database is set to the default auto-commit mode.
2633 def CreateDataset(self, sqlcommand: SQL_SELECT, directsql: bool = ..., filter: str = ..., orderby: str = ...
2634 ) -> Optional[DATASET]:
2636 Creates a Dataset service instance based on a table, query or ``SQL SELECT`` statement.
2638 ``sqlcommand``: a table name, a query name or a valid ``SQL SELECT`` statement.
2639 Identifiers may be enclosed with square brackets. This argument is case-sensitive.
2641 ``directsql``: set this argument to ``True`` to send the statement directly to the database
2642 engine without preprocessing by LibreOffice (Default = ``False``).
2644 ``filter``: specifies the condition that records must match to be included in the returned
2645 dataset. This argument is expressed as a ``SQL WHERE`` statement without the ``WHERE`` keyword.
2647 ``orderby``: specifies the ordering of the dataset as a ``SQL ORDER BY`` statement
2648 without the ``ORDER BY`` keyword.
2650 A ``Dataset`` service instance.
2654 def DAvg(self, expression: str, tablename: str, criteria: str = ...) -> Optional[Union[float, int]]:
2656 Compute the aggregate function ``AVG()`` on a field or expression belonging to a table
2657 filtered by a ``WHERE``-clause.
2659 ``expression``: an ``SQL`` expression.
2661 ``tablename``: the name of a table.
2663 ``criteria``: an optional ``WHERE`` clause without the word ``WHERE``.
2669 def DCount(self, expression: str, tablename: str, criteria: str = ...) -> Optional[int]:
2671 Compute the aggregate function ``COUNT()`` on a field or expression belonging to a table
2672 filtered by a ``WHERE``-clause.
2674 ``expression``: an ``SQL`` expression.
2676 ``tablename``: the name of a table.
2678 ``criteria``: an optional ``WHERE`` clause without the word ``WHERE``.
2684 def DLookup(self, expression: str, tablename: str, criteria: str = ..., orderclause: str = ...) -> Any:
2686 Compute a ``SQL`` expression on a single record returned by a ``WHERE`` clause defined by the
2687 ``criteria`` parameter.
2689 If the query returns multiple records, only the first one is considered.
2690 Use the ``orderclause`` parameter to determine how query results are sorted.
2692 ``expression``: an ``SQL`` expression in which the field names are surrounded with
2695 ``tablename``: the name of a table (without square brackets).
2697 ``criteria``: an optional ``WHERE`` clause without the word ``WHERE``, in which field names
2698 are surrounded with square brackets.
2700 ``orderclause``: an optional ``ORDER BY`` clause without the ``ORDER BY`` keywords.
2701 Field names should be surrounded with square brackets.
2703 The found value or None.
2707 def DMax(self, expression: str, tablename: str, criteria: str = ...) \
2708 -> Optional[Union[float, int, str, datetime.datetime]]:
2710 Compute the aggregate function ``MAX()`` on a field or expression belonging to a table
2711 filtered by a ``WHERE``-clause.
2713 ``expression``: an ``SQL`` expression.
2715 ``tablename``: the name of a table.
2717 ``criteria``: an optional ``WHERE`` clause without the word ``WHERE``.
2723 def DMin(self, expression: str, tablename: str, criteria: str = ...) \
2724 -> Optional[Union[float, int, str, datetime.datetime]]:
2726 Compute the aggregate function ``MIN()`` on a field or expression belonging to a table
2727 filtered by a ``WHERE``-clause.
2729 ``expression``: an ``SQL`` expression.
2731 ``tablename``: the name of a table.
2733 ``criteria``: an optional ``WHERE`` clause without the word ``WHERE``.
2739 def DSum(self, expression: str, tablename: str, criteria: str = ...) -> Optional[Union[float, int]]:
2741 Compute the aggregate function ``SUM()`` on a field or expression belonging to a table
2742 filtered by a ``WHERE``-clause.
2744 ``expression``: an ``SQL`` expression.
2746 ``tablename``: the name of a table.
2748 ``criteria``: an optional ``WHERE`` clause without the word ``WHERE``.
2755 sqlcommand: SQL_SELECT,
2756 directsql: bool = ...,
2761 Return the content of a table, a query or a ``SELECT SQL`` statement as a list of lists.
2762 The first index corresponds to the individual records and the second index refers to the record fields.
2764 ``sqlcommand``: a table name, a query name or a ``SELECT SQL`` statement.
2766 ``directsql``: when ``True``, no syntax conversion is done by LibreOffice.
2767 Ignored when ``sqlcommand`` is a table or a query name. Defaults to ``False``.
2769 ``header``: when ``True``, a header row is inserted on the top of the list with the
2770 column names. Defaults to ``False``.
2772 ``maxrows``: the maximum number of returned rows. If absent, all records are returned.
2774 The returned list will be empty if no rows are returned and the column headers are not required.
2778 def OpenFormDocument(self, formdocument: str) -> Optional[FORMDOCUMENT]:
2780 Open the ``FormDocument`` given by its hierarchical name in normal mode.
2781 If the form document is already open, the form document is made active.
2783 ``formdocument``: a valid form document name as a case-sensitive string.
2784 When hierarchical, the hierarchy must be rendered with forward slashes ("/").
2786 A ``FormDocument`` instance or ``None``.
2790 def OpenQuery(self, queryname: str) -> Optional[DATASHEET]:
2792 Opens the Data View window of the specified query.
2794 ``queryname``: the name of an existing query as a case-sensitive string.
2796 An instance of the ``Datasheet`` service.
2797 If the query could not be opened, then ``None`` is returned.
2801 def OpenSql(self, sql: SQL_SELECT, directsql: bool = ...) -> Optional[DATASHEET]:
2803 Runs a ``SQL SELECT`` command, opens a Data View window with the results.
2805 sql: a string containing a valid ``SQL SELECT`` statement.
2806 Identifiers may be enclosed by square brackets.
2808 directsql: when ``True``, the ``SQL`` command is sent to the database engine
2809 without pre-analysis. Defaults to ``False``.
2811 An instance of the ``Datasheet`` service.
2812 If the query could not be opened, then ``None`` is returned.
2816 def OpenTable(self, tablename: str) -> Optional[DATASHEET]:
2818 Opens the Data View window of the specified table.
2820 ``tablename``: the name of an existing table as a case-sensitive string.
2822 An instance of the ``Datasheet`` service.
2823 If the table could not be opened, then ``None`` is returned.
2827 def Rollback(self) -> None:
2829 Cancels all updates made to the database since the previous ``Commit`` or ``Rollback`` call.
2830 This method is ignored if commits are done automatically after each SQL statement,
2831 i.e. if the database is set to the default auto-commit mode.
2835 def RunSql(self, sqlcommand: SQL_ACTION, directsql: bool = ...) -> bool:
2837 Execute an action query (table creation, record insertion, ...) or ``SQL`` statement on
2838 the current database.
2840 ``sqlcommand``: a query name (without square brackets) or an ``SQL`` statement.
2842 ``directsql``: when ``True``, no syntax conversion is done by LibreOffice.
2843 Ignored when ``sqlcommand`` is a query name. Defaults to ``False``.
2845 ``True`` when the command ran successfully.
2849 def SetTransactionMode(self, transactionmode: Literal[0, 1, 2, 4, 8] = ...) -> bool:
2851 Defines the level of isolation in database transactions.
2853 By default, databases manage transactions in auto-commit mode, which means that a ``Commit()``
2854 is automatically performed after every SQL statement.
2856 Use this method to manually determine the isolation level of transactions.
2857 When a transaction mode other than ``NONE (0)`` is set, the script has to explicitly
2858 call the ``Commit()`` method to apply the changes to the database.
2861 ``transactionmode``: specifies the transaction mode.
2862 This argument must be one of the constants defined in ``com.sun.star.sdbc.TransactionIsolation``
2863 (Default = ``NONE``)
2865 ``True`` when successful.
2869 # #########################################################################
2871 # #########################################################################
2872 class SF_Dataset(SFServices):
2874 A dataset represents a set of tabular data produced by a database.
2876 In the user interface of LibreOffice a dataset corresponds with the data
2877 displayed in a form or a data sheet (table, query).
2879 To use datasets, the database instance must exist but the Base document may not be open.
2881 With this service it is possible to:
2882 - Navigate through and access the data in a dataset.
2883 - Update, insert and remove records in a dataset.
2887 """ Returns ``True`` if the current record position is before the first record in the dataset,
2888 otherwise returns ``False``. Set this property to ``True`` to move the cursor to the beginning of the dataset.
2889 Setting this property to ``False`` is ignored. """
2891 """ Returns a ``dict`` with the default values used for each field in the dataset.
2892 The fields or columns in the dataset are the keys in the dictionary. The database field types are converted
2893 to their corresponding Python data types. When the field type is undefined, the default value is None. """
2895 """ Returns ``True`` if the current record position is after the last record in the dataset,
2896 otherwise returns ``False``. Set this property to ``True`` to move the cursor to the end of the dataset.
2897 Setting this property to ``False`` is ignored. """
2898 Fields: Tuple[str, ...]
2899 """ Returns a list containing the names of all fields in the dataset. """
2901 """ Returns the filter applied in addition to the eventual ``WHERE`` clause(s) in the initial ``SQL`` statement.
2902 This property is expressed as a ``WHERE`` clause without the ``WHERE`` keyword. """
2904 """ Returns the ordering clause that replaces the eventual ``ORDER BY`` clause present in the initial
2905 ``SQL`` statement. This property is expressed as a ``ORDER BY`` clause without the ``ORDER BY`` keywords. """
2906 ParentDatabase: DATABASE
2907 """ Returns the ``Database`` instance corresponding to the parent database of the current dataset. """
2909 """ Returns the exact number of records in the dataset. Note that the evaluation of this property
2910 implies browsing the whole dataset, which may be costly depending on the dataset size. """
2912 """ Returns the number of the current record starting at 1. Returns 0 if this property is unknown. """
2914 """ Returns the source of the dataset. It can be either a table name, a query name or a ``SQL`` statement. """
2916 """ Returns the source of the dataset. It can be one of the following string values:
2917 ``TABLE``, ``QUERY`` or ``SQL``. """
2918 UpdatableFields: List
2919 """ Returns a ``list`` containing the names of all fields in the dataset that are updatable. """
2921 """ Returns a ``dict`` containing the pairs (field name: value) of the current record in the dataset. """
2923 """ Returns the ``com.sun.star.sdb.RowSet`` ``UNO`` object representing the dataset. """
2925 def CloseDataset(self) -> bool:
2927 Closes the current Dataset.
2929 ``True`` when successful.
2933 def CreateDataset(self, filter:str = ..., orderby: str = ...) -> DATASET:
2935 Returns a ``Dataset`` service instance derived from the actual dataset by applying
2936 the specified ``filter`` and ``orderby`` arguments.
2938 ``filter``: specifies the condition that records must match to be included in the
2939 returned dataset. This argument is expressed as a ``SQL WHERE`` clause
2940 without the ``WHERE`` keyword. If this argument is not specified, then the filter
2941 used in the current dataset is applied, otherwise the current filter is replaced
2944 ``orderby``: specifies the ordering of the dataset as a ``SQL ORDER BY`` clause
2945 without the ``ORDER BY`` keywords. If this argument is not specified, then
2946 the sorting order used in the current dataset is applied, otherwise
2947 the current sorting order is replaced by this argument.
2949 A new ``Dataset`` service instance.
2953 def Delete(self) -> bool:
2955 Deletes the current record from the dataset.
2957 After this operation the cursor is positioned at the record immediately after the deleted record.
2958 When the deleted record is the last in the dataset, then the cursor is positioned after it
2959 and the property ``EOF`` returns ``True``.
2961 ``True`` when successful.
2965 def ExportValueToFile(self, fieldname: str, filename: FILE, overwrite: bool = ...) -> bool:
2967 Exports the value of a binary field of the current record to the specified file.
2968 If the specified field is not binary or if it contains no data, then the output file is not created.
2970 ``fieldname``: the name of the binary field to be exported, as a case-sensitive string.
2972 ``filename``: the complete path to the file to be created using the notation defined
2973 in the ``FileSystem.FileNaming`` property.
2975 ``overwrite``: set this argument to ``True`` to allow the destination file
2976 to be overwritten (Default = ``False``).
2978 ``True`` when successful.
2982 def GetRows(self, header: bool = ..., maxrows: int = ...) -> Optional[MATRIX]:
2984 Return the content of the dataset as a list of lists.
2985 The first index corresponds to the individual records and the second index refers to the record fields.
2987 ``header``: when ``True``, a header row is inserted on the top of the list with the
2988 column names. Defaults to ``False``.
2990 ``maxrows``: the maximum number of returned rows. If absent, all records are returned.
2992 The returned list will be empty if no rows are returned and the column headers are not required.
2996 def GetValue(self, fieldname: str) -> Any:
2998 Returns the value of the specified field from the current record of the dataset.
3000 ``fieldname``: the name of the field to be returned, as a case-sensitive string.
3002 If the specified field is binary, then its length is returned.
3006 def Insert(self, *args, **kwargs: Dict) -> int:
3008 Inserts a new record at the end of the dataset and initialize its fields with the specified values.
3009 Updatable fields with unspecified values are initialized with their default values.
3011 Next variants are allowed:
3012 - ``newid = dataset.Insert({"Name": "John", "Age": 50, "City": "Chicago"})``
3013 - ``newid = dataset.Insert("Name", "John", "Age", 50, "City", "Chicago")``
3014 - ``newid = dataset.Insert(Name = "John", Age = 50, City = "Chicago")``
3016 If the primary key of the dataset is an ``auto value``, then this method returns
3017 the primary key value of the new record. Otherwise, the method will return 0 (when successful)
3018 or -1 (when not successful).
3022 def MoveFirst(self) -> bool:
3024 Moves the dataset cursor to the first record. Deleted records are ignored by this method.
3026 ``True`` when successful.
3030 def MoveLast(self) -> bool:
3032 Moves the dataset cursor to the last record. Deleted records are ignored by this method.
3034 ``True`` when successful.
3038 def MoveNext(self, offset: int = ...) -> bool:
3040 Moves the dataset cursor forward by a given number of records.
3041 Deleted records are ignored by this method.
3043 ``offset``: the number of records by which the cursor shall be moved forward.
3044 This argument may be a negative value (Default = +1).
3046 ``True`` when successful.
3050 def MovePrevious(self, offset: int = 1) -> bool:
3052 Moves the dataset cursor backward by a given number of records.
3053 Deleted records are ignored by this method.
3055 ``offset``: the number of records by which the cursor shall be moved backward.
3056 This argument may be a negative value (Default = +1).
3058 ``True`` when successful.
3062 def Reload(self, filter: str = ..., orderby: str = ...) -> bool:
3064 Reloads the dataset from the database. The properties ``Filter`` and ``OrderBy`` may be defined
3065 when calling this method.
3067 Reloading the dataset is useful when records have been inserted to or deleted from the database.
3068 Note that the methods ``CreateDataset`` and ``Reload`` perform similar functions,
3069 however ``Reload`` reuses the same Dataset class instance.
3071 ``filter``: specifies the condition that records must match to be included in the
3072 returned dataset. This argument is expressed as a ``SQL WHERE`` clause
3073 without the ``WHERE`` keyword. If this argument is not specified, then the filter
3074 used in the current dataset is applied, otherwise the current filter is replaced
3077 ``orderby``: specifies the ordering of the dataset as a ``SQL ORDER BY`` clause
3078 without the ``ORDER BY`` keywords. If this argument is not specified, then
3079 the sorting order used in the current dataset is applied, otherwise
3080 the current sorting order is replaced by this argument.
3082 ``True`` when successful.
3086 def Update(self, *args, **kwargs) -> bool:
3088 Updates the values of the specified fields in the current record.
3090 Next variants are allowed:
3091 - ``newid = dataset.Update({"Age": 51, "City": "New York"})``
3092 - ``newid = dataset.Update("Age", 51, "City", "New York")``
3093 - ``newid = dataset.Update(Age = 51, City = "New York")``
3095 ``True`` when successful.
3099 # #########################################################################
3100 # SF_Datasheet CLASS
3101 # #########################################################################
3102 class SF_Datasheet(SFServices):
3104 The Datasheet service allows to visualize the contents of database tables as well as the results
3105 of queries and ``SQL`` statements using ``Base's Data View``.
3107 Additionally, this service allows to:
3108 - add custom menus to the data view
3109 - access values in specific positions of the data view
3110 - position the cursor in a specific cell of the data view
3112 The ``Base`` document owning the data may or may not be opened.
3115 ColumnHeaders: Tuple[str, ...]
3116 """ Returns a list with the names of the column headers in the datasheet. """
3118 """ Returns the currently selected column name. """
3120 """ Returns the number of the currently selected row, starting at 1. """
3121 DatabaseFileName: FILE
3122 """ Returns the file name of the ``Base`` file in ``SF_FileSystem.FileNaming`` format. """
3124 """ Specifies a filter to be applied to the datasheet expressed as the ``WHERE`` clause of a ``SQL`` query
3125 without the ``WHERE`` keyword. If an empty string is specified then the active Filter is removed. """
3127 """ Returns True when the datasheet component has not been closed by the user. """
3129 """ Returns the number of rows in the datasheet. """
3131 """ Specifies the order in which records are shown expressed as the ``ORDER BY`` clause of a ``SQL`` query
3132 without the ``ORDER BY`` keyword. If an empty string is specified then the active ``OrderBy`` is removed. """
3133 ParentDatabase: DATABASE
3134 """ Returns the ``Database`` instance corresponding to the parent database of the current datasheet. """
3136 """ Returns the source of the datasheet. It can be either a table name, a query name
3137 or a ``SQL`` statement. """
3139 """ Returns the type of the data source of the datasheet. It can be one of the following string values:
3140 ``TABLE``, ``QUERY`` or ``SQL``. """
3143 """ Returns the ``com.sun.star.lang.XComponent`` ``UNO`` object representing the datasheet. """
3146 """ Returns the ``com.sun.star.awt.XControl`` ``UNO`` object representing the datasheet. """
3148 XTabControllerModel: UNO
3149 """ Returns the ``com.sun.star.awt.XTabControllerModel `` ``UNO`` object representing the datasheet. """
3151 def Activate(self) -> None:
3153 Brings to front the data view window referred to by the ``Datasheet`` instance.
3157 def CloseDatasheet(self) -> None:
3159 Closes the data view window referred to by the ``Datasheet`` instance.
3163 def CreateMenu(self, menuheader: str, before: Union[str, int] = ..., submenuchar: str = ...) -> object:
3165 Creates a new menu entry in the data view window and returns a ``SFWidgets.Menu`` service instance,
3166 with which menu items can be programmatically added.
3168 ``menuheader``: the name of the new menu.
3169 ``before``: this argument can be either the name of an existing menu entry before
3170 which the new menu will be placed or a number expressing the position of the new menu.
3171 If this argument is left blank the new menu is placed as the last entry.
3173 ``submenuchar``: the delimiter used in menu trees . Defaults to ``">"``.
3175 A ``Menu`` service instance.
3177 Menus added using the ``CreateMenu`` method are lost as soon as the data view window is closed.
3181 def GetText(self, column: Union[str, int] = ...) -> str:
3183 Returns the text in a given column of the current row.
3185 ``column``: the name of the column as a string or the column position (starting at ``1``).
3186 If a position greater than the number of columns is given, the last column is returned.
3188 This method does not change the position of the cursor in the data view window.
3194 def GetValue(self, column: Union[str, int]) -> Optional[Union[str, int, float, datetime.datetime]]:
3196 Returns the value in a given column of the current row as a valid Python type.
3198 ``column``: the name of the column as a string or the column position (starting at ``1``).
3199 If a position greater than the number of columns is given, the last column is returned.
3201 The targeted column value.
3202 Binary types are returned as a ``int`` value indicating the length of the binary field.
3206 def GoToCell(self, row: int = ..., column: Union[int, str] = ...) -> None:
3208 Moves the cursor to the specified row and column.
3210 ``row``: the row number as a numeric value starting at ``1``.
3211 If the requested row exceeds the number of existing rows, the cursor is moved to the last row.
3212 If this argument is not specified, then the row is not changed.
3214 ``column``: the name of the column as a string or the column position (starting at ``1``).
3215 If the requested column exceeds the number of existing columns, the cursor is moved
3216 to the last column. If this argument is not specified, then the column is not changed.
3220 def RemoveMenu(self, menuheader: str) -> bool:
3222 Removes a menu entry from the data view menubar by its name.
3224 ``menuheader``: the case-sensitive name of the menu to be removed.
3225 The name must not include the tilde (``~``) character.
3227 ``True`` when successful.
3229 This method can remove menus that belong to the standard user interface
3230 as well as menus that were programmatically added with the CreateMenu method.
3231 The removal of standard menus is not permanent, and they will reappear
3232 after the window is closed and reopened.
3236 def Toolbars(self, toolbarname: str = ...) -> Union[TOOLBAR, Tuple[str, ...]]:
3238 Returns either a list of the available toolbar names in the actual datasheet or a ``Toolbar``
3241 ``toolbarname``: the usual name of one of the available toolbars.
3243 A zero-based array of toolbar names when the argument is absent,
3244 or a new ``Toolbar`` object instance from the ``SF_Widgets`` class.
3248 # #####################################################################################################################
3249 # SFDialogs CLASS (alias of SFDialogs Basic library) ###
3250 # #####################################################################################################################
3253 Management of dialogs. They may be defined with the Basic IDE or built from scratch.
3256 # #########################################################################
3258 # #########################################################################
3259 class SF_Dialog(SFServices):
3261 The ``Dialog`` service contributes to the management of dialogs created with the Basic Dialog Editor
3262 or dialogs created on-the-fly. Each instance of the ``Dialog`` class represents a single dialog box
3263 displayed to the user.
3265 A dialog box can be displayed in modal or in non-modal modes.
3268 the box is displayed and the execution of the macro process is suspended
3269 until one of the ``OK`` or ``Cancel`` buttons is pressed. In the meantime, user actions executed
3270 on the box can trigger specific actions.
3273 the dialog box is "floating" on the user desktop and the execution
3274 of the macro process continues normally. A non-modal dialog closes when it is terminated
3275 with the Terminate() method or when the LibreOffice session ends.
3276 The window close button is inactive in non-modal dialogs.
3278 A dialog box disappears from memory after its explicit termination.
3281 OKBUTTON: Literal[1]
3282 """ ``OK`` button has been pressed. """
3283 CANCELBUTTON: Literal[0]
3284 """ ``Cancel`` button has been pressed. """
3287 """ Specify the title of the dialog. """
3289 """ Specify the height of the dialog. """
3291 """ Returns True when the dialog is not terminated due to a user intervention. """
3293 """ Specifies if the dialog box is currently in execution in modal mode. """
3295 """ The name of the dialog. """
3297 """ A dialog may have several pages that can be traversed by the user step by step.
3298 The Page property of the Dialog object defines which page of the dialog is active. """
3300 """ Specify if the dialog box is visible on the desktop.
3301 By default it is not visible until the ``Execute()`` method is run and visible afterwards. """
3303 """ The UNO representation (``com.sun.star.awt.XControlModel``) of the dialog model. """
3305 """ The UNO representation (``com.sun.star.awt.XControl``) of the dialog view. """
3307 """ Specify the width of the dialog. """
3309 OnFocusGained: SCRIPT_URI
3310 """ Get/set the macro triggered by the ``When receiving focus`` event."""
3311 OnFocusLost: SCRIPT_URI
3312 """ Get/set the macro triggered by the ``When losing focus`` event."""
3313 OnKeyPressed: SCRIPT_URI
3314 """ Get/set the macro triggered by the ``Key pressed`` event."""
3315 OnKeyReleased: SCRIPT_URI
3316 """ Get/set the macro triggered by the ``Key released`` event."""
3317 OnMouseDragged: SCRIPT_URI
3318 """ Get/set the macro triggered by the ``Mouse moved while button pressed`` event."""
3319 OnMouseEntered: SCRIPT_URI
3320 """ Get/set the macro triggered by the ``Mouse inside`` event."""
3321 OnMouseExited: SCRIPT_URI
3322 """ Get/set the macro triggered by the ``Mouse outside`` event."""
3323 OnMouseMoved: SCRIPT_URI
3324 """ Get/set the macro triggered by the ``Mouse moved`` event."""
3325 OnMousePressed: SCRIPT_URI
3326 """ Get/set the macro triggered by the ``Mouse button pressed`` event."""
3327 OnMouseReleased: SCRIPT_URI
3328 """ Get/set the macro triggered by the ``Mouse button released`` event."""
3330 def Activate(self) -> bool:
3332 Set the focus on the current dialog instance.
3333 Probably called from after an event occurrence or to focus on a non-modal dialog.
3335 ``True`` if focusing is successful.
3339 def Center(self, parent: Union[DIALOG, BASE, DOCUMENT, CALC, WRITER, FORMDOCUMENT, DATASHEET] = ...) -> bool:
3341 Centres the current dialogue box instance in the middle of a parent window.
3342 Without arguments, the method centres the dialogue box in the middle of the current window.
3344 ``parent``: an optional object that can be either,
3345 - a ScriptForge dialog object,
3346 - a ScriptForge document (Calc, Base, ...) object.
3348 ``True`` when successful.
3352 self, sourcename: str, controlname: str, left: int = ..., top: int = ...) -> Optional[DIALOGCONTROL]:
3354 Duplicate an existing control of any type in the actual dialog.
3355 The duplicated control is left unchanged. The new control can be relocated.
3357 ``sourcename``: the name of the control to duplicate.
3359 ``controlname``: the name of the new control. It must not exist yet.
3361 ``left``: the left coordinate of the new control expressed in "``Map AppFont``" units.
3363 ``top``: the top coordinate of the new control expressed in "``Map AppFont``" units.
3365 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3369 def Controls(self, controlname: str = ...) -> Union[DIALOGCONTROL, Tuple[str, ...]]:
3371 Returns the list of the controls contained in the dialog or a dialog control object based on its name.
3373 ``controlname``: a valid control name as a case-sensitive string.
3374 If absent the list is returned.
3376 The list of available control names as strings when ``controlname`` is absent.
3377 Otherwise, if ``controlname`` exists, an instance of the ``SFDialogs.SF_DialogControl`` class.
3381 def CreateButton(self,
3383 place: Union[UNO, Tuple[int, int, int, int]],
3385 push: Literal["", "OK", "CANCEL"] = ...,
3386 ) -> Optional[DIALOGCONTROL]:
3388 Create a new control of type ``Button`` in the actual dialog.
3390 ``controlname``: the name of the new control. It must not exist yet.
3392 ``place``: the size and position expressed in "``APPFONT units``". Either:
3393 - a tuple (X, Y, Width, Height).
3394 - a ``com.sun.star.awt.Rectangle`` structure.
3396 ``toggle``: when ``True`` a toggle button is created. Default = ``False``.
3398 ``push``: button type "OK", "CANCEL" or empty string (default).
3400 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3404 def CreateCheckBox(self,
3406 place: Union[UNO, Tuple[int, int, int, int]],
3407 multiline: bool = ...,
3408 ) -> Optional[DIALOGCONTROL]:
3410 Create a new control of type ``ComboBox`` in the actual dialog.
3412 ``controlname``: the name of the new control. It must not exist yet.
3414 ``place``: the size and position expressed in "``APPFONT units``". Either:
3415 - a tuple (X, Y, Width, Height).
3416 - a ``com.sun.star.awt.Rectangle`` structure.
3418 ``multiline``: when ``True`` the caption may be displayed on more than one line.
3419 Default = ``False``.
3421 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3425 def CreateComboBox(self,
3427 place: Union[UNO, Tuple[int, int, int, int]],
3428 border: Literal["3D", "FLAT", "NONE"] = ...,
3429 dropdown: bool = ...,
3430 linecount: int = ...
3431 ) -> Optional[DIALOGCONTROL]:
3433 Create a new control of type ``ComboBox`` in the actual dialog.
3435 ``controlname``: the name of the new control. It must not exist yet.
3437 ``place``: the size and position expressed in "``APPFONT units``". Either:
3438 - a tuple (X, Y, Width, Height).
3439 - a ``com.sun.star.awt.Rectangle`` structure.
3441 ``border``: "3D" (default), "FLAT" or "NONE".
3443 ``dropdown``: when ``True`` (default), a drop-down button is displayed.
3445 ``linecount``: the maximum line count displayed in the drop-down (default = 5).
3447 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3451 def CreateCurrencyField(self,
3453 place: Union[UNO, Tuple[int, int, int, int]],
3454 border: Literal["3D", "FLAT", "NONE"] = ...,
3455 spinbutton: bool = ...,
3456 minvalue: Union[int, float] = ...,
3457 maxvalue: Union[int, float] = ...,
3458 increment: int = ...,
3460 ) -> Optional[DIALOGCONTROL]:
3462 Create a new control of type ``CurrencyField`` in the actual dialog.
3464 ``controlname``: the name of the new control. It must not exist yet.
3466 ``place``: the size and position expressed in "``APPFONT units``". Either:
3467 - a tuple (X, Y, Width, Height).
3468 - a ``com.sun.star.awt.Rectangle`` structure.
3470 ``border``: "3D" (default), "FLAT" or "NONE".
3472 ``spinbutton``: when ``True`` a spin button is present. Default = ``False``.
3474 ``minvalue``: the smallest value that can be entered in the control. Default = -1000000.
3476 ``maxvalue``: the largest value that can be entered in the control. Default = +1000000.
3478 ``increment``: the step when the spin button is pressed. Default = 1.
3480 ``accuracy``: the decimal accuracy. Default = 2 decimal digits.
3482 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3486 def CreateDateField(self,
3488 place: Union[UNO, Tuple[int, int, int, int]],
3489 border: Literal["3D", "FLAT", "NONE"] = ...,
3490 dropdown: bool = ...,
3491 mindate: datetime.datetime = ...,
3492 maxdate: datetime.datetime = ...,
3493 ) -> Optional[DIALOGCONTROL]:
3495 Create a new control of type ``DateField`` in the actual dialog.
3497 ``controlname``: the name of the new control. It must not exist yet.
3499 ``place``: the size and position expressed in "``APPFONT units``". Either:
3500 - a tuple (X, Y, Width, Height).
3501 - a ``com.sun.star.awt.Rectangle`` structure.
3503 ``border``: "3D" (default), "FLAT" or "NONE".
3505 ``dropdown``: when ``True`` a dropdown button is shown. Default = ``False``.
3507 ``mindate``: the smallest date that can be entered in the control. Default = 1900-01-01.
3509 ``maxdate``: the largest date that can be entered in the control. Default = 2200-12-31.
3511 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3515 def CreateFileControl(self,
3517 place: Union[UNO, Tuple[int, int, int, int]],
3518 border: Literal["3D", "FLAT", "NONE"] = ...,
3519 ) -> Optional[DIALOGCONTROL]:
3521 Create a new control of type ``FileControl`` in the actual dialog.
3523 ``controlname``: the name of the new control. It must not exist yet.
3525 ``place``: the size and position expressed in "``APPFONT units``". Either:
3526 - a tuple (X, Y, Width, Height).
3527 - a ``com.sun.star.awt.Rectangle`` structure.
3529 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3533 def CreateFixedLine(self,
3535 place: Union[UNO, Tuple[int, int, int, int]],
3536 orientation: Literal["H", "Horizontal", "V", "Vertical"],
3537 ) -> Optional[DIALOGCONTROL]:
3539 Create a new control of type ``FixedLine`` in the actual dialog.
3541 ``controlname``: the name of the new control. It must not exist yet.
3543 ``place``: the size and position expressed in "``APPFONT units``". Either:
3544 - a tuple (X, Y, Width, Height).
3545 - a ``com.sun.star.awt.Rectangle`` structure.
3547 ``orientation``: for horizontal orientation use "H" or "Horizontal",
3548 for vertical orientation use "V" or "Vertical".
3550 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3554 def CreateFixedText(self,
3556 place: Union[UNO, Tuple[int, int, int, int]],
3557 border: Literal["3D", "FLAT", "NONE"] = ...,
3558 multiline: bool = ...,
3559 align: Literal["LEFT", "CENTER", "RIGHT"] = ...,
3560 verticalalign: Literal["TOP", "MIDDLE", "BOTTOM"] = ...,
3561 ) -> Optional[DIALOGCONTROL]:
3563 Create a new control of type ``FixedText`` in the actual dialog.
3565 ``controlname``: the name of the new control. It must not exist yet.
3567 ``place``: the size and position expressed in "``APPFONT units``". Either:
3568 - a tuple (X, Y, Width, Height).
3569 - a ``com.sun.star.awt.Rectangle`` structure.
3571 ``border``: border kind, "3D" or "FLAT" or "NONE". Default is ``NONE``.
3573 ``multiline``: when ``True`` the caption may be displayed on more than one line.
3576 ``align``: horizontal alignment, "LEFT" (default) or "CENTER" or "RIGHT".
3578 ``verticalalign``: vertical alignment, "TOP" (default) or "MIDDLE" or "BOTTOM".
3580 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3584 def CreateFormattedField(self,
3586 place: Union[UNO, Tuple[int, int, int, int]],
3587 border: Literal["3D", "FLAT", "NONE"] = ...,
3588 spinbutton: bool = ...,
3589 minvalue: Union[int, float] = ...,
3590 maxvalue: Union[int, float] = ...,
3591 ) -> Optional[DIALOGCONTROL]:
3593 Create a new control of type ``FormattedField`` in the actual dialog.
3595 ``controlname``: the name of the new control. It must not exist yet.
3597 ``place``: the size and position expressed in "``APPFONT units``". Either:
3598 - a tuple (X, Y, Width, Height).
3599 - a ``com.sun.star.awt.Rectangle`` structure.
3601 ``border``: "3D" (default), "FLAT" or "NONE".
3603 ``spinbutton``: when ``True`` a spin button is present. Default = ``False``.
3605 ``minvalue``: the smallest value that can be entered in the control. Default = -1000000.
3607 ``maxvalue``: the largest value that can be entered in the control. Default = +1000000.
3609 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3613 def CreateGroupBox(self,
3615 place: Union[UNO, Tuple[int, int, int, int]],
3616 ) -> Optional[DIALOGCONTROL]:
3618 Create a new control of type ``GroupBox`` in the actual dialog.
3620 ``controlname``: the name of the new control. It must not exist yet.
3622 ``place``: the size and position expressed in "``APPFONT units``". Either:
3623 - a tuple (X, Y, Width, Height).
3624 - a ``com.sun.star.awt.Rectangle`` structure.
3626 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3630 def CreateHyperlink(self,
3632 place: Union[UNO, Tuple[int, int, int, int]],
3633 border: Literal["3D", "FLAT", "NONE"] = ...,
3634 multiline: bool = ...,
3635 align: Literal["LEFT", "CENTER", "RIGHT"] = ...,
3636 verticalalign: Literal["TOP", "MIDDLE", "BOTTOM"] = ...,
3637 ) -> Optional[DIALOGCONTROL]:
3639 Create a new control of type ``Hyperlink`` in the actual dialog.
3641 ``controlname``: the name of the new control. It must not exist yet.
3643 ``place``: the size and position expressed in "``APPFONT units``". Either:
3644 - a tuple (X, Y, Width, Height).
3645 - a ``com.sun.star.awt.Rectangle`` structure.
3647 ``border``: border kind, "3D" or "FLAT" or "NONE". Default is ``NONE``.
3649 ``multiline``: when ``True`` the caption may be displayed on more than one line.
3652 ``align``: horizontal alignment, "LEFT" (default) or "CENTER" or "RIGHT".
3654 ``verticalalign``: vertical alignment, "TOP" (default) or "MIDDLE" or "BOTTOM".
3656 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3660 def CreateImageControl(self,
3662 place: Union[UNO, Tuple[int, int, int, int]],
3663 border: Literal["3D", "FLAT", "NONE"] = ...,
3664 scale: Literal["FITTOSIZE", "KEEPRATIO", "NO"] = ...,
3665 ) -> Optional[DIALOGCONTROL]:
3667 Create a new control of type ``ImageControl`` in the actual dialog.
3669 ``controlname``: the name of the new control. It must not exist yet.
3671 ``place``: the size and position expressed in "``APPFONT units``". Either:
3672 - a tuple (X, Y, Width, Height).
3673 - a ``com.sun.star.awt.Rectangle`` structure.
3675 ``border``: border kind, "3D" or "FLAT" or "NONE". Default is ``NONE``.
3677 ``scale``: one of next values, "FITTOSIZE" (default) or "KEEPRATIO" or "NO".
3679 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3683 def CreateListBox(self,
3685 place: Union[UNO, Tuple[int, int, int, int]],
3686 border: Literal["3D", "FLAT", "NONE"] = ...,
3687 dropdown: bool = ...,
3688 linecount: int = ...,
3689 multiselect: bool = ...
3690 ) -> Optional[DIALOGCONTROL]:
3692 Create a new control of type ``ListBox`` in the actual dialog.
3694 ``controlname``: the name of the new control. It must not exist yet.
3696 ``place``: the size and position expressed in "``APPFONT units``". Either:
3697 - a tuple (X, Y, Width, Height).
3698 - a ``com.sun.star.awt.Rectangle`` structure.
3700 ``border``: "3D" (default), "FLAT" or "NONE".
3702 ``dropdown``: When ``True`` (default), a drop-down button is displayed.
3704 ``linecount``: the maximum line count displayed in the drop-down (default = 5).
3706 ``multiselect``: when ``True``, more than 1 entry may be selected. Default = ``False``.
3708 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3712 def CreateNumericField(self,
3714 place: Union[UNO, Tuple[int, int, int, int]],
3715 border: Literal["3D", "FLAT", "NONE"] = ...,
3716 spinbutton: bool = ...,
3717 minvalue: Union[int, float] = ...,
3718 maxvalue: Union[int, float] = ...,
3719 increment: int = ...,
3721 ) -> Optional[DIALOGCONTROL]:
3723 Create a new control of type ``NumericField`` in the actual dialog.
3725 ``controlname``: the name of the new control. It must not exist yet.
3727 ``place``: the size and position expressed in "``APPFONT units``". Either:
3728 - a tuple (X, Y, Width, Height).
3729 - a ``com.sun.star.awt.Rectangle`` structure.
3731 ``border``: "3D" (default), "FLAT" or "NONE".
3733 ``spinbutton``: when ``True`` a spin button is present. Default = ``False``.
3735 ``minvalue``: the smallest value that can be entered in the control. Default = -1000000.
3737 ``maxvalue``: the largest value that can be entered in the control. Default = +1000000.
3739 ``increment``: the step when the spin button is pressed. Default = 1.
3741 ``accuracy``: the decimal accuracy. Default = 2 decimal digits.
3743 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3747 def CreatePatternField(self,
3749 place: Union[UNO, Tuple[int, int, int, int]],
3750 border: Literal["3D", "FLAT", "NONE"] = ...,
3751 editmask: str = ...,
3752 literalmask: str = ...,
3753 ) -> Optional[DIALOGCONTROL]:
3755 Create a new control of type ``PatternField`` in the actual dialog.
3757 ``controlname``: the name of the new control. It must not exist yet.
3759 ``place``: the size and position expressed in "``APPFONT units``". Either:
3760 - a tuple (X, Y, Width, Height).
3761 - a ``com.sun.star.awt.Rectangle`` structure.
3763 ``border``: "3D" (default), "FLAT" or "NONE".
3765 ``editmask``: a character code that determines what the user may enter. More info on
3766 https://wiki.documentfoundation.org/Documentation/DevGuide/Graphical_User_Interfaces#Pattern_Field.
3768 ``literalmask``: contains the initial values that are displayed in the pattern field.
3770 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3774 def CreateProgressBar(self,
3776 place: Union[UNO, Tuple[int, int, int, int]],
3777 border: Literal["3D", "FLAT", "NONE"] = ...,
3778 minvalue: Union[int, float] = ...,
3779 maxvalue: Union[int, float] = ...,
3780 ) -> Optional[DIALOGCONTROL]:
3782 Create a new control of type ``ProgressBar`` in the actual dialog.
3784 ``controlname``: the name of the new control. It must not exist yet.
3786 ``place``: the size and position expressed in "``APPFONT units``". Either:
3787 - a tuple (X, Y, Width, Height).
3788 - a ``com.sun.star.awt.Rectangle`` structure.
3790 ``border``: "3D" (default), "FLAT" or "NONE".
3792 ``minvalue``: the smallest value that can be entered in the control. Default = 0.
3794 ``maxvalue``: the largest value that can be entered in the control. Default = 100.
3796 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3800 def CreateRadioButton(self,
3802 place: Union[UNO, Tuple[int, int, int, int]],
3803 border: Literal["3D", "FLAT", "NONE"] = ...,
3804 multiline: bool = ...,
3805 ) -> Optional[DIALOGCONTROL]:
3807 Create a new control of type ``RadioButton`` in the actual dialog.
3809 ``controlname``: the name of the new control. It must not exist yet.
3811 ``place``: the size and position expressed in "``APPFONT units``". Either:
3812 - a tuple (X, Y, Width, Height).
3813 - a ``com.sun.star.awt.Rectangle`` structure.
3815 ``multiline``: when ``True`` the caption may be displayed on more than one line.
3816 Default is ``False``.
3818 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3822 def CreateScrollBar(self,
3824 place: Union[UNO, Tuple[int, int, int, int]],
3825 orientation: Literal["H", "Horizontal", "V", "Vertical"],
3826 border: Literal["3D", "FLAT", "NONE"] = ...,
3827 minvalue: Union[int, float] = ...,
3828 maxvalue: Union[int, float] = ...,
3829 ) -> Optional[DIALOGCONTROL]:
3831 Create a new control of type ``ScrollBar`` in the actual dialog.
3833 ``controlname``: the name of the new control. It must not exist yet.
3835 ``place``: the size and position expressed in "``APPFONT units``". Either:
3836 - a tuple (X, Y, Width, Height).
3837 - a ``com.sun.star.awt.Rectangle`` structure.
3839 ``orientation``: for horizontal orientation use "H" or "Horizontal",
3840 for vertical orientation use "V" or "Vertical".
3842 ``border``: "3D" (default), "FLAT" or "NONE".
3844 ``minvalue``: the smallest value that can be entered in the control. Default = 0.
3846 ``maxvalue``: the largest value that can be entered in the control. Default = 100.
3848 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3852 def CreateTableControl(self,
3854 place: Union[UNO, Tuple[int, int, int, int]],
3855 border: Literal["3D", "FLAT", "NONE"] = ...,
3856 rowheaders: bool = ...,
3857 columnheaders: bool = ...,
3858 scrollbars: Literal["H", "Horizontal", "V", "Vertical", "B", "Both", "N", "None"] = ...,
3859 gridlines: bool = ...,
3860 ) -> Optional[DIALOGCONTROL]:
3862 Create a new control of type ``TableControl`` in the actual dialog.
3864 ``controlname``: the name of the new control. It must not exist yet.
3866 ``place``: the size and position expressed in "``APPFONT units``". Either:
3867 - a tuple (X, Y, Width, Height).
3868 - a ``com.sun.star.awt.Rectangle`` structure.
3870 ``border``: "3D" (default), "FLAT" or "NONE".
3872 ``rowheaders``: when ``True`` (default), the row headers are shown.
3874 ``columnheaders``: when ``True`` (default), the column headers are shown.
3876 ``scrollbars``: H[orizontal] or V[ertical] or B[oth] or N[one] (default).
3878 ``gridlines``: when ``True`` horizontal and vertical lines are painted between the grid cells.
3879 Default is ``False``.
3881 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3885 def CreateTextField(self,
3887 place: Union[UNO, Tuple[int, int, int, int]],
3888 border: Literal["3D", "FLAT", "NONE"] = ...,
3889 multiline: bool = ...,
3890 maximumlength: int = ...,
3891 passwordcharacter: str = ...
3892 ) -> Optional[DIALOGCONTROL]:
3894 Create a new control of type ``TextField`` in the actual dialog.
3896 ``controlname``: the name of the new control. It must not exist yet.
3898 ``place``: the size and position expressed in "``APPFONT units``". Either:
3899 - a tuple (X, Y, Width, Height).
3900 - a ``com.sun.star.awt.Rectangle`` structure.
3902 ``border``: border kind, "3D" or "FLAT" or "NONE". Default is ``NONE``.
3904 ``multiline``: when ``True`` the caption may be displayed on more than one line.
3907 ``maximumlength``: the maximum character count (default = 0 meaning unlimited).
3909 ``passwordcharacter``: a single character specifying the echo for a password text field
3912 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3916 def CreateTimeField(self,
3918 place: Union[UNO, Tuple[int, int, int, int]],
3919 border: Literal["3D", "FLAT", "NONE"] = ...,
3920 mintime: datetime.datetime = ...,
3921 maxtime: datetime.datetime = ...
3922 ) -> Optional[DIALOGCONTROL]:
3924 Create a new control of type ``TimeField`` in the actual dialog.
3926 ``controlname``: the name of the new control. It must not exist yet.
3928 ``place``: the size and position expressed in "``APPFONT units``". Either:
3929 - a tuple (X, Y, Width, Height).
3930 - a ``com.sun.star.awt.Rectangle`` structure.
3932 ``border``: "3D" (default), "FLAT" or "NONE".
3934 ``mintime``: the smallest time that can be entered in the control. Default = 0h.
3936 ``maxtime``: the largest time that can be entered in the control. Default = 24h.
3938 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3942 def CreateTreeControl(self,
3944 place: Union[UNO, Tuple[int, int, int, int]],
3945 border: Literal["3D", "FLAT", "NONE"] = ...,
3946 ) -> Optional[DIALOGCONTROL]:
3948 Create a new control of type ``TreeControl`` in the actual dialog.
3950 ``controlname``: the name of the new control. It must not exist yet.
3952 ``place``: the size and position expressed in "``APPFONT units``". Either:
3953 - a tuple (X, Y, Width, Height).
3954 - a ``com.sun.star.awt.Rectangle`` structure.
3956 ``border``: "3D" (default), "FLAT" or "NONE".
3958 A ``SFDialogs.SF_DialogControl`` instance or ``None``.
3962 def EndExecute(self, returnvalue: int) -> None:
3964 Ends the display of a modal dialog and gives back the argument
3965 as return value for the current Execute() action.
3967 ``EndExecute()`` is usually contained in the processing of a macro
3968 triggered by a dialog or control event.
3970 ``returnvalue``: The value passed to the running ``Execute()`` method.
3974 def Execute(self, modal: bool = ...) -> int:
3976 Display the dialog. In modal mode, the process is suspended until its closure by the user.
3978 ``modal``: ``False`` when non-modal dialog. Defaults to ``True``.
3980 0 = Cancel button pressed. 1 = OK button pressed. Otherwise: the dialog stopped
3981 with an ``EndExecute()`` statement executed from a dialog or control event.
3985 def GetTextsFromL10N(self, l10n: L10N) -> bool:
3987 Replace all fixed text strings of a dialog by their localized version.
3989 - the title of the dialog
3990 - the caption associated with next control types: ``Button, CheckBox, FixedLine, FixedText, GroupBox`` and ``RadioButton``
3991 - the content of list- and comboboxes
3992 - the tip- or helptext displayed when the mouse is hovering a control.
3993 The current method has a twin method ``ScriptForge.SF_L10N.AddTextsFromDialog``.
3994 The current method is probably run before the ``Execute()`` method.
3996 ``l10n``: A "L10N" service instance created with CreateScriptService("L10N").
3998 ``True`` when successful.
4002 def OrderTabs(self, tabslist: Sequence[str], start: int = ..., increment: int = ...) -> bool:
4004 Set the tabulation index of a series of controls.
4006 The sequence of controls is given as a list or tuple of control names from the first to the last.
4008 Next controls will not be accessible (anymore ?) via the TAB key if >=1 of next conditions is met:
4009 - if they are not in the given list
4010 - if their type is ``FixedLine``, ``GroupBox`` or ``ProgressBar``
4011 - if the control is disabled
4013 ``tabslist``: a list or tuple of valid control names in the order of tabulation.
4015 ``start``: the tab index to be assigned to the 1st control in the list. Default is ``1``.
4017 ``increment``: the difference between ``2`` successive tab indexes. Default is ``1``.
4019 ``True`` when successful.
4023 def Resize(self, left: int = ..., top: int = ..., width: int = ..., height: int = ...) -> bool:
4025 Moves the topleft corner of a dialog to new coordinates and/or modify its dimensions.
4026 All distances are expressed in ``Map AppFont`` units.
4027 Without arguments, the method resets the initial position and dimensions.
4029 ``left``: the horizontal distance from the top-left corner.
4031 ``top``: the vertical distance from the top-left corner.
4033 ``width``: the width of the rectangle containing the dialog.
4035 ``height``: the height of the rectangle containing the dialogue box.
4037 ``True`` if the resize was successful.
4041 def SetPageManager(self,
4042 pilotcontrols: str = ...,
4043 tabcontrols: str = ...,
4044 wizardcontrols: str = ...,
4045 lastpage: int = ...,
4048 Defines which controls in a dialog are responsible for switching pages, making it easier
4049 to orchestrate the ``Page`` property of a dialog and its controls.
4051 Dialogs may have multiple pages and the currently visible page is defined by the ``Page``dialog property.
4052 If the ``Page`` property is left unchanged, the default visible page is equal to ``0`` (zero), meaning
4053 that no particular page is defined and all visible controls are displayed regardless of the value set in
4054 their own ``Page`` property.
4056 When the ``Page`` property of a dialog is changed to some other value such as ``1``, ``2``, ``3``
4057 and so forth, then only the controls whose ``Page`` property match the current dialog page will
4060 By using the SetPageManager method it is possible to define four types of page managers:
4061 - List box or combo box: in this case, each entry in the list box or combo box corresponds to a page. The first item refers to Page 1, the second items refers to Page 2 and so on.
4062 - Group of radio buttons: defines a group of radio buttons that will control which page is visible.
4063 - Sequence of buttons: defines a set of buttons, each of which corresponding to a dialog page. This can be used to emulate a tabbed interface by placing buttons side by side in the dialog.
4064 - Previous/Next buttons: defines which buttons in the dialog that will be used to navigate to the Previous/Next page in the dialog.
4066 This method is supposed to be called just once before calling the ``Execute()`` method.
4067 Subsequent calls are ignored.
4069 ``pilotcontrols``: a comma-separated list of ``ListBox``, ``ComboBox`` or ``RadioButton``
4070 control names used as page managers.
4071 For ``RadioButton`` controls, specify the name of the first control in the group to be used.
4073 ``tabcontrols``: a comma-separated list of button names that will be used as page managers.
4074 The order in which they are specified in this argument corresponds to the page number
4075 they are associated with.
4077 ``wizardcontrols``: a comma-separated list with the names of two buttons that will be used
4078 s the ``Previous/Next`` buttons.
4080 ``lastpage``: the number of the last available page.
4081 It is recommended to specify this value when using the ``Previous/Next`` page manager.
4083 ``True`` on success.
4085 It is possible to use more than one page management mechanism at the same time.
4089 def Terminate(self) -> bool:
4091 Terminate the dialog service for the current dialog instance.
4092 After termination any action on the current instance will be ignored.
4094 ``True`` if termination is successful.
4098 # #########################################################################
4099 # SF_DialogControl CLASS
4100 # #########################################################################
4101 class SF_DialogControl(SFServices):
4103 Each instance of the current class represents a single control within a dialog box.
4104 The focus is clearly set on getting and setting the values displayed by the controls of the dialog box,
4105 not on their formatting.
4106 A special attention is given to controls with type ``TreeControl``.
4109 Border: Literal["3D", "FLAT", "NONE"]
4110 """ Get the surrounding of the control. """
4112 """ Get/set whether a command button has or not the behaviour of a Cancel button.
4113 Applicable to ``Button`` controls. """
4115 """ Get/set the text associated with the control. Applicable to ``Button, CheckBox, FixedLine,
4116 FixedText, GroupBox, Hyperlink, RadioButton`` controls. """
4118 """ get the type of control as a string. """
4120 """ Get/set the currently upmost node selected in the tree control, as a
4121 ``com.sun.star.awt.tree.XMutableTreeNode`` object. Applicable to ``TreeControl`` controls. """
4123 """ Get/set whether a command button is the default (OK) button.
4124 Applicable to ``Button`` controls. """
4126 """ Specifies if the control is accessible with the cursor. """
4127 Format: Literal["Standard (short)", "Standard (short YY)", "Standard (short YYYY)", "Standard (long)",
4128 "DD/MM/YY", "MM/DD/YY", "YY/MM/DD", "DD/MM/YYYY", "MM/DD/YYYY", "YYYY/MM/DD", "YY-MM-DD", "YYYY-MM-DD",
4129 "24h short", "24h long", "12h short", "12h long"]
4130 """ Get/set the format used to display dates and times. Applicable to ``DateField, TimeField, FormattedField``
4133 """ Get/set the height of the control. """
4135 """ Get the number of rows in the control. Applicable to ``ComboBox, ListBox, TableControl`` controls. """
4137 """ Get/set which item is selected in the control. Applicable to ``ComboBox, ListBox, TableControl``
4140 """ Get/set if the control is read-only.. Applicable to ``ComboBox, CurrencyField, DateField, FileControl,
4141 FormattedField, ListBox, NumericField, PatternField, TextField, TimeField`` controls. """
4143 """ Get/set whether a user can make multiple selections in a ``listbox``. """
4145 """ The name of the control. """
4147 OnActionPerformed: SCRIPT_URI
4148 """ Get/set the macro triggered by the ``Execute action`` event. """
4149 OnAdjustmentValueChanged: SCRIPT_URI
4150 """ Get/set the macro triggered by the ``While adjusting`` event. """
4151 OnFocusGained: SCRIPT_URI
4152 """ Get/set the macro triggered by the ``When receiving focus`` event."""
4153 OnFocusLost: SCRIPT_URI
4154 """ Get/set the macro triggered by the ``When losing focus`` event."""
4155 OnItemStatusChanged: SCRIPT_URI
4156 """ Get/set the macro triggered by the ``Item status changed`` event. """
4157 OnKeyPressed: SCRIPT_URI
4158 """ Get/set the macro triggered by the ``Key pressed`` event."""
4159 OnKeyReleased: SCRIPT_URI
4160 """ Get/set the macro triggered by the ``Key released`` event."""
4161 OnMouseDragged: SCRIPT_URI
4162 """ Get/set the macro triggered by the ``Mouse moved while button pressed`` event."""
4163 OnMouseEntered: SCRIPT_URI
4164 """ Get/set the macro triggered by the ``Mouse inside`` event."""
4165 OnMouseExited: SCRIPT_URI
4166 """ Get/set the macro triggered by the ``Mouse outside`` event."""
4167 OnMouseMoved: SCRIPT_URI
4168 """ Get/set the macro triggered by the ``Mouse moved`` event."""
4169 OnMousePressed: SCRIPT_URI
4170 """ Get/set the macro triggered by the ``Mouse button pressed`` event."""
4171 OnMouseReleased: SCRIPT_URI
4172 """ Get/set the macro triggered by the ``Mouse button released`` event."""
4173 OnNodeExpanded: SCRIPT_URI
4174 """ Get/set the macro triggered by the ``Expansion button is pressed on a node in a tree control`` event. """
4175 OnNodeSelected: SCRIPT_URI
4176 """ Get/set the macro triggered by the ``Node in a tree control is selected`` event."""
4179 """ A dialog may have several pages that can be traversed by the user step by step.
4180 The Page property of the Dialog object defines which page of the dialog is active.
4181 The`` ``Page property of a control defines the page of the dialog on which the control is visible. """
4183 """ The parent ``DIALOG`` class object instance. """
4185 """ Get/se the file name (in ``FileSystem.FileNaming`` notation) containing a bitmap or other type of graphic
4186 to be displayed on the specified control. """
4188 """ Get the lowest root node (usually there is only one such root node), as a
4189 ``com.sun.star.awt.tree.XMutableTreeNode`` object. Applicable to ``TreeControl`` controls. """
4190 RowSource: Sequence[str]
4191 """ Get/set the data contained in a ``combobox`` or a ``listbox``. """
4193 """ Specifies a control's place in the tab order in the dialog. """
4195 """ Get the text being displayed by the control. Applicable to ``ComboBox, FileControl, FormattedField,
4196 PatternField, TextField`` controls. """
4198 """ Get/set whether the ``checkbox`` control may appear dimmed (grayed). """
4200 """ Get/set the URL to open when clicking the ``hyperlink`` control. """
4203 Get/set the content of the control:
4205 - ``Button``: bool - For toggle buttons only.
4206 - ``CheckBox``: bool, int - 0, ``False``: not checked, 1, ``True``: checked, 2: grayed, don't know.
4207 - ``ComboBox``: str - The selected value. The ``ListIndex`` property is an alternate option.
4208 - ``CurrencyField``: int, float.
4209 - ``DateField``: datetime.datetime.
4210 - ``FileControl``: FILE.
4211 - ``FormattedField``: str, int, float.
4212 - ``ListBox``: List(str), str - The selected row(s) as a scalar or as an array depending on the ``MultiSelect`` attribute.
4213 - ``NumericField``: int, float.
4214 - ``PatternField``: str.
4215 - ``ProgressBar``: int - Must be within the predefined bounds.
4216 - ``RadioButton``: bool - Each button has its own name. They are linked together if their TAB positions are contiguous. If a radiobutton is set to ``True``, the other related buttons are automatically set to ``False``.
4217 - ``ScrollBar``: int - Must be within the predefined bounds.
4218 - ``TableControl``: List[Any] - The data of the currently selected row.
4219 - ``TextField``: str - The text appearing in the control.
4220 - ``TimeField``: datetime.datetime.
4221 Not applicable to ``FixedLine, FixedText, GroupBox, Hyperlink, ImageControl`` and ``TreeControl`` dialog controls.
4224 """ Get/set if the dialog control is hidden or visible. """
4226 """ Get/set the width of the control. """
4228 """ X coordinate of the top-left corner of the control. """
4230 """ Y coordinate of the top-left corner of the control. """
4233 """ The UNO representation (``com.sun.star.awt.XControlModel``) of the control model. """
4235 """ The UNO representation (``com.sun.star.awt.XControl``) of the control view. """
4236 XGridColumnModel: UNO
4237 """ The UNO representation (``com.sun.star.awt.grid.XGridColumnModel``) of a ``tablecontrol`` column model. """
4239 """ The UNO representation (``com.sun.star.awt.grid.XGridDataModel``) of a ``tablecontrol`` data model. """
4241 """ The UNO representation (``com.sun.star.awt.tree.MutableTreeDataModel``) of a ``treecontrol`` data model. """
4243 def AddSubNode(self,
4244 parentnode: XMutableTreeNode,
4246 datavalue: Any = ...,
4247 ) -> XMutableTreeNode:
4249 Return a new node of the tree control subordinate to a parent node.
4251 ``parentnode``: a node UNO object, of type ``com.sun.star.awt.tree.XMutableTreeNode``.
4253 ``displayvalue``: the text appearing in the control box.
4255 ``datavalue``: any value associated with the new node.
4257 The new node UNO object: ``com.sun.star.awt.tree.XMutableTreeNode``.
4261 def AddSubTree(self,
4262 parentnode: XMutableTreeNode,
4264 withdatavalue: bool = ...,
4267 Return ``True`` when a subtree, subordinate to a parent node, could be inserted successfully
4268 in a tree control. If the parent node had already child nodes before calling this method,
4269 the child nodes are erased.
4271 ``parentnode``: a node UNO object, of type ``com.sun.star.awt.tree.XMutableTreeNode``.
4273 ``flattree``: a list of lists sorted on the columns containing the ``DisplayValues``.
4275 ``withdatavalue``: when ``False`` (default), every column of ``FlatTree`` contains the
4276 text to be displayed in the tree control. When ``True``, the texts to be displayed
4277 (``DisplayValue``) are in columns 0, 2, 4, ... while the ``DataValues`` are in columns
4280 Typically, such an array can be issued by the GetRows() method applied on
4281 the ``SFDatabases.Database`` service.
4285 def CreateRoot(self, displayvalue: str, datavalue: Any = ...) -> XMutableTreeNode:
4287 Return a new root node of the tree control.
4288 The new tree root is inserted below pre-existing root nodes.
4290 ``displayvalue``: the text appearing in the control box.
4292 ``datavalue``: any value associated with the root node.
4294 The new root node as a UNO object of type ``com.sun.star.awt.tree.XMutableTreeNode``.
4299 displayvalue: str = ...,
4300 datavalue: Any = ...,
4301 casesensitive: bool = ...,
4302 ) -> Optional[XMutableTreeNode]:
4304 Traverses the tree and find recursively, starting from the root, a node meeting some criteria.
4305 Either (1 match is enough) having its ``DisplayValue`` like ``displayValue`` or
4306 having its ``DataValue`` = ``datavalue``.
4308 Comparisons may be or not case-sensitive.
4310 The first matching occurrence is returned.
4312 ``displayvalue``: the pattern to be matched. It may contain wildcards(? and *).
4314 ``datavalue``: a string, a numeric value or a date.
4316 ``casesensitive``: Defaults to ``False``.
4318 The found node of type ``com.sun.star.awt.tree.XMutableTreeNode`` or ``None`` if not found.
4322 def Resize(self, left: int = ..., top: int = ..., width: int = ..., height: int = ...) -> bool:
4324 Move the top-left corner of the control to new coordinates and/or modify its dimensions.
4325 Without arguments, the method resets the initial dimensions and position.
4326 All distances are expressed in ``Map AppFont`` units and are measured from the top-left corner
4327 of the parent dialog.
4329 ``left``: the horizontal distance from the top-left corner. It may be negative.
4331 ``top``: the vertical distance from the top-left corner. It may be negative.
4333 ``width``: the horizontal width of the rectangle containing the control. It must be positive.
4335 ``height``: the vertical height of the rectangle containing the control. It must be positive.
4337 ``True`` when successful.
4341 def SetFocus(self) -> bool:
4343 Set the focus on the current Control instance.
4344 Probably called from after an event occurrence.
4346 ``True`` if focusing is successful.
4350 def SetTableData(self,
4352 widths: Sequence[Union[int, float]] = ...,
4353 alignments: str = ...,
4354 rowheaderwidth: int = ...,
4357 Fill a table control with the given data. Preexisting data is erased.
4359 The Basic IDE allows to define if the control has a row and/or a column header.
4360 When it is the case, the array in argument should contain those headers resp. in the first
4361 column and/or in the first row.
4363 A column in the control shall be sortable when the data (headers excluded) in that column
4364 is homogeneously filled either with numbers or with strings.
4366 Columns containing strings will by default be left-aligned, those with numbers will be right-aligned.
4368 ``dataarray``: the set of data to display in the table control, including optional
4371 ``widths``: tuple or list containing the relative widths of each column.
4372 In other words, widths = (1, 2) means that the second column is twice as wide as
4373 the first one. If the number of values in the tuple is smaller than the number of
4374 columns in the table, then the last value in the tuple is used to define the width
4375 of the remaining columns.
4377 ``alignments``: the column's horizontal alignment as a string with length = number of columns.
4378 Possible characters are: L(eft), C(enter), R(ight) or space (default behavior).
4380 ``rowheaderwidth``: width of the row header column expressed in ``Map AppFont`` units.
4381 Defaults to ``10``. The argument is ignored when the table control has no row header.
4383 ``True`` when successful.
4387 def WriteLine(self, line: str = ...) -> bool:
4389 Add a new line to a multiline ``TextField`` control.
4391 ``line``: the line to insert at the end of the text box.
4392 A newline character will be inserted before the line, if relevant. Defaults to an empty line.
4394 ``True`` if insertion is successful.
4399 # #####################################################################################################################
4400 # SFDocuments CLASS (alias of SFDocuments Basic library) ###
4401 # #####################################################################################################################
4404 The SFDocuments class gathers a number of classes, methods and properties making easy
4405 managing and manipulating LibreOffice documents.
4408 # #########################################################################
4410 # #########################################################################
4411 class SF_Document(SFServices):
4413 The methods and properties are generic for all types of documents: they are combined in the
4414 current SF_Document class
4415 - saving, exporting, closing documents
4416 - accessing their standard or custom properties
4417 - styles and menubar management
4419 Specific properties and methods are implemented in the concerned subclass(es) SF_Calc, SF_Base, ...
4422 CustomProperties: DICTIONARY
4423 """ Returns a ``ScriptForge.Dictionary`` object instance. After update, can be passed again to the property
4424 for updating the document. Individual items of the dictionary may be either strings, numbers,
4425 ``datetime.datetime`` or ``com.sun.star.util.Duration`` items.
4426 This property is not applicable to ``Base`` documents. """
4428 """ Get/set the ``Description`` property of the document (also known as "``Comments``").
4429 This property is not applicable to ``Base`` documents. """
4430 DocumentProperties: DICTIONARY
4431 """ Returns a ``ScriptForge.Dictionary`` object instance containing all the entries. Document statistics
4432 are included. Note that they are specific to the type of document. As an example, a ``Calc`` document
4433 includes a "``CellCount``" entry. Other documents do not.
4434 This property is not applicable to ``Base`` documents. """
4436 """ String value with the document type (``Base``, ``Calc``, ``Writer``, etc) """
4437 ExportFilters: Tuple[str, ...]
4438 """ Returns a tuple of strings with the export filter names applicable to the current document.
4439 Filters used for both import/export are also returned.
4440 This property is not applicable to ``Base`` documents. """
4442 """ Returns a string with the URL path to the root of the virtual file system of the document.
4443 Use the ``FileSystem`` service to view its contents, as well as to create, open and read files stored in it. """
4444 ImportFilters: Tuple[str, ...]
4445 """ Returns a tuple of strings with the import filter names applicable to the current document.
4446 Filters used for both import/export are also returned.
4447 This property is not applicable to ``Base`` documents. """
4449 """ Returns True when the document component has not been closed by the user. """
4451 """ ``True`` when type of document = ``Base``. """
4453 """ ``True`` when type of document = ``Calc``. """
4455 """ ``True`` when type of document = ``Draw``. """
4456 IsFormDocument: bool
4457 """ ``True`` when type of document = ``FormDocument``. """
4459 """ ``True`` when type of document = ``Impress``. """
4461 """ ``True`` when type of document = ``Math``. """
4463 """ ``True`` when type of document = ``Writer``. """
4465 """ Get/set the ``Keywords`` property of the document as a comma-separated list of keywords.
4466 This property is not applicable to ``Base`` documents. """
4468 """ ``True`` if the document is actually in read-only mode.
4469 This property is not applicable to ``Base`` documents. """
4470 StyleFamilies: Tuple[str, ...]
4471 """ Get the list of available style families.
4472 This property is not applicable to ``Base`` documents. """
4474 """ Get/set the ``Subject`` property of the document.
4475 This property is not applicable to ``Base`` documents. """
4477 """ Get/set the ``Title`` property of the document.
4478 This property is not applicable to ``Base`` documents. """
4481 """ A ``com.sun.star.lang.XComponent`` or ``com.sun.star.comp.dba.ODatabaseDocument`` UNO object representing
4483 XDocumentSettings: UNO
4484 """ A ``com.sun.star.XXX.DocumentSettings`` UNO object, where XXX is either ``sheet, text, drawing`` or
4485 ``presentation``. This object gives access to the internal UNO properties that are specific
4486 to the document's type.
4487 This property is not applicable to ``Base`` documents. """
4489 def Activate(self) -> bool:
4491 Make the current document active.
4493 ``True`` if the document could be activated.
4494 Otherwise, there is no change in the actual user interface.
4498 def CloseDocument(self, saveask: bool = ...) -> bool:
4500 Close the document. Does nothing if the document is already closed
4501 regardless of how the document was closed, manually or by program.
4503 ``saveask``: if ``True`` (default), the user is invited to confirm or not the writing
4504 of the changes on disk. No effect if the document was not modified.
4506 ``False`` if the user declined to close.
4510 def ContextMenus(self, contextmenuname: str = ..., submenuchar: str = ...
4511 ) -> Union[CONTEXTMENU, Tuple[str, ...]]:
4513 Returns either a list of the available ContextMenu names in the actual document
4514 or a ``SFWidgets.SF_ContextMenu`` object instance.
4516 ``contextmenuname``: the usual name of one of the available context menus.
4518 ``submenuchar``: the delimiter used to create menu trees when calling
4519 the ``AddItem()`` method from the ``ContextMenu`` service. The default value is ">".
4521 The list of available context menu names as a tuple of strings when ``contextmenuname``
4522 is absent, a ``ContextMenu`` class instance otherwise.
4526 def CreateMenu(self, menuheader: str, before: Union[str, int] = ..., submenuchar: str = ...
4529 Creates a new menu entry in the menubar of a given document window.
4531 The created menu is only available during the current LibreOffice session and is not saved neither
4532 in the document nor in the global application settings.
4533 Hence, closing the document window will make the menu disappear.
4534 It will only reappear when the macro that creates the menu is executed again.
4536 ``menuheader``: the toplevel name of the new menu.
4538 ``before``: the name (as a string) or position (as an integer starting at 1) of
4539 an existing menu before which the new menu will be placed.
4540 If no value is defined for this argument, the menu will be created at the last position
4543 ``submenuchar``: the delimiter used to create menu trees when calling
4544 methods as ``AddItem()`` from the Menu service. The default value is ">".
4546 A ``SFWidgets.SF_Menu`` class instance or ``None``.
4550 def DeleteStyles(self, family: str, styleslist: Union[str, Sequence[str]]) -> None:
4552 Suppresses a single style or a list of styles given by their names within a specific styles family.
4553 Only user-defined styles may be deleted, built-in styles are ignored.
4554 It applies to all document types except ``Base`` and ``FormDocument``.
4556 ``family``: one of the style families present in the actual document, as a case-sensitive
4557 string. Valid family names can be retrieved using the ``StyleFamilies`` property.
4559 ``styleslist``: a single style name as a string or a list/tuple of style names.
4560 The style names may be localized or not. The styles list is typically the output of the
4561 execution of a ``Styles()`` method.
4566 def Echo(self, echoon: bool = ..., hourglass: bool = ...) -> None:
4568 While a script is executed any display update resulting from that execution
4569 is done immediately.
4571 For performance reasons it might be an advantage to differ the display updates
4572 up to the end of the script. This is where pairs of Echo() methods to set and reset the removal of the
4573 immediate updates may be beneficial.
4575 Optionally the actual mouse pointer can be modified to the image of an hourglass.
4578 ``echoon``: when ``False``, the display updates are suspended. Default is ``True``.
4580 ``hourglass``: when ``True``, the mouse pointer is changed to an hourglass. Default is ``False``.
4584 def ExportAsPDF(self,
4586 overwrite: bool = ...,
4588 password: str = ...,
4589 watermark: str = ...,
4592 Store the document to the given file location in PDF format.
4593 This method is not applicable to ``Base`` documents.
4595 ``filename``: identifies the file where to save.
4596 It must follow the ``SF_FileSystem.FileNaming`` notation.
4598 ``overwrite``: ``True`` if the destination file may be overwritten. Defaults to ``False``.
4600 ``pages``: the pages to print as a string, like in the user interface. Example: "1-4;10;15-18".
4602 ``password``: password to open the document.
4604 ``watermark``: the text for a watermark to be drawn on every page of the exported PDF file.
4606 ``False`` if the document could not be saved.
4610 def PrintOut(self, pages: str = ..., copies: int = ...) -> bool:
4612 Send the content of the document to the printer.
4613 The printer might be defined previously by default, by the user or by the ``SetPrinter()`` method.
4614 This method is not applicable to ``Base`` documents.
4616 ``pages``: the pages to print as a string, like in the user interface. Example: "1-4;10;15-18".
4617 Default is all pages.
4619 ``copies``: the number of copies. Defaults to 1.
4621 ``True`` when successful.
4625 def RemoveMenu(self, menuheader: str) -> bool:
4627 Removes a toplevel menu from the menubar of a given document window.
4629 ``menuheader``: the toplevel name of the menu to be removed.
4631 ``True`` if the specified menu existed and could be removed.
4633 This method can be used to remove any menu entry from the document window, including
4634 default menus. However, none of these changes in the menubar are saved to the document
4635 or to the application settings. To restore the menubar to the default settings,
4636 simply close and reopen the document.
4640 def RunCommand(self, command: str, *args, **kwargs) -> None:
4642 Runs a UNO command on the document window associated with the service instance.
4644 The document itself does not need to be active to be able to run commands.
4646 Commands can be run with or without arguments. Arguments are not validated before running the command.
4647 If the command or its arguments are invalid, then nothing will happen.
4649 ``command``: case-sensitive string containing the UNO command name.
4650 The inclusion of the prefix ``.uno:`` in the command is optional.
4651 The command itself is not checked for correctness.
4653 ``kwargs``: the command arguments as keyword arguments.
4657 def Save(self) -> bool:
4659 Store the document to the file location from which it was loaded.
4660 The method is ignored if the document was not modified.
4662 ``False`` if the document could not be saved.
4668 overwrite: bool = ...,
4669 password: str = ...,
4670 filtername: str = ...,
4671 filteroptions: str = ...,
4674 Store the document to the given file location.
4675 The new location becomes the new file name on which simple ``Save()`` method calls will be applied.
4677 ``filename``: identifies the file where to save. It must follow the ``SF_FileSystem.FileNaming``
4680 ``overwrite``: ``True`` if the destination file may be overwritten. Defaults to ``False``.
4682 ``password``: a non-space string to protect the document.
4684 ``filtername``: the name of a filter that should be used for saving the document.
4685 If present, the filter must exist.
4687 ``filteroptions``: a string of options associated with the filter.
4689 ``False`` if the document could not be saved.
4693 def SaveCopyAs(self,
4695 overwrite: bool = ...,
4696 password: str = ...,
4697 filtername: str = ...,
4698 filteroptions: str = ...,
4701 Store the document to the given file location.
4702 The actual location is unchanged
4704 ``filename``: identifies the file where to save. It must follow the ``SF_FileSystem.FileNaming``
4707 ``overwrite``: ``True`` if the destination file may be overwritten. Defaults to ``False``.
4709 ``password``: a non-space string to protect the document.
4711 ``filtername``: the name of a filter that should be used for saving the document.
4712 If present, the filter must exist.
4714 ``filteroptions``: a string of options associated with the filter.
4716 ``False`` if the document could not be saved.
4720 def SetPrinter(self,
4722 orientation: Literal['PORTRAIT', 'LANDSCAPE'] = ...,
4723 paperformat: Literal['A3', 'A4', 'A5', 'LETTER', 'LEGAL', 'TABLOID'] = ...
4726 Define the printer options for the document.
4727 This method is not applicable to ``Base`` documents.
4729 ``printer``: the name of the printer queue where to print to.
4730 When absent or space, the default printer is set.
4732 ``orientation``: either ``PORTRAIT`` or ``LANDSCAPE``. Left unchanged when absent.
4734 ``paperformat``: paper format. Left unchanged when absent.
4736 ``True`` when successful.
4742 namepattern: str = ...,
4743 parentstyle: str = ...,
4745 userdefined: bool = ...,
4746 category: Literal['TEXT', 'CHAPTER', 'LIST', 'INDEX', 'EXTRA', 'HTML'] = ...,
4747 ) -> Tuple[str, ...]:
4749 Retrieves a list of styles matching an optional compound criteria, the returned list may be empty.
4750 This method is not applicable to ``Base`` documents.
4752 ``family``: one of the style families present in the actual document, as a case-sensitive
4753 string. Valid family names can be retrieved using the ``StyleFamilies`` property.
4755 ``namepattern``: a filter on the style names, as a case-sensitive string pattern.
4756 The names include the internal and localized names. Admitted wildcards are "?" and "*".
4758 ``parentstyle``: when present, only the children of the given, localized or not, parent style
4761 ``used``: when ``True``, the style must be used in the document, when absent the argument
4764 ``userdefined``: when ``True``, the style must have been added by the user, either in the
4765 document or its template, when absent, the argument is ignored.
4767 ``category``: a sub-category of the ``ParagraphStyles`` family.
4769 A list of style names.
4773 def Toolbars(self, toolbarname: str = ...) -> Union[TOOLBAR, Tuple[str, ...]]:
4775 Returns either a list of the available toolbar names in the actual document
4776 or a ``SFWidgets.SF_Toolbar`` object instance.
4778 ``toolbarname``: the optional usual name of one of the available toolbars.
4780 A list of toolbar names when the argument is absent, or a new ``Toolbar`` object instance
4781 from the ``SF_Widgets`` library.
4785 def XStyle(self, family: str, stylename: str) -> UNO:
4787 This method returns the UNO representation of a given style.
4788 It is applicable to all document types except ``Base`` documents.
4790 ``family``: one of the style families present in the actual document, as a case-sensitive
4791 string. Valid family names can be retrieved using ``StyleFamilies`` property.
4793 ``stylename``: one of the styles present in the given family, as a case-sensitive string.
4794 The ``stylename`` argument may be localized or not.
4796 A ``com.sun.star.style.XStyle`` UNO object or one of its descendants,
4797 like ``com.sun.star.style.CellStyle`` or ``com.sun.star.style.ParagraphStyle``, etc.
4798 ``None`` is returned when the ``stylename`` does not exist in the given ``family``.
4802 # #########################################################################
4804 # #########################################################################
4805 class SF_Base(SF_Document, SFServices):
4807 The ``Base`` service provides a number of methods and properties to facilitate the management
4808 and handling of ``LibreOffice Base`` documents.
4810 The ``Base`` service extends the ``Document`` service and provides additional methods that are
4811 specific for ``Base`` documents, enabling users to:
4812 - get access to the database contained in a ``Base`` document
4813 - open form documents, tables and queries stored in a ``Base`` document
4814 - check if a form document from a Base document is currently loaded
4818 def CloseFormDocument(self, formdocument: str) -> bool:
4820 Close the given form document.
4821 Nothing happens if the form document is not open.
4823 The method is deprecated. Use the ``SF_FormDocument.CloseDocument()`` method instead.
4826 ``formdocument``: a valid hierarchical form name as a case-sensitive string.
4828 ``True`` if closure is successful.
4832 def FormDocuments(self) -> Tuple[str, ...]:
4834 Return the list of the form documents contained in the ``Base`` document.
4836 A tuple of strings. Each entry is the full path name of a form document.
4837 The path separator is the slash ("/").
4841 def Forms(self, formdocument: str, form: Union[str, int] = ...) -> Union[FORM, Tuple[str, ...]]:
4843 Depending on the parameters provided this method will return:
4844 - a tuple with the names of all the forms contained in a form document (if the ``form`` argument is absent)
4845 - a ``SFDocuments.Form`` object representing the form specified in the ``form`` argument.
4847 The method is deprecated. Use the ``SF_FormDocument.Forms()`` method instead.
4849 ``formdocument``: the hierarchical name of an open form document.
4851 ``form``: the name or index number of the form stored in the form document.
4852 If this argument is absent, the method will return a list with the names of all forms
4853 available in the form document.
4855 Either a tuple of strings. Each entry is a form name stored in the form document,
4856 or a ``SFDocuments.Form`` class instance.
4860 def GetDatabase(self, user: str = ..., password: str = ...) -> Optional[DATABASE]:
4862 Returns a ``SFDatabases.Database`` class instance giving access
4863 to the execution of SQL commands on the database defined and/or stored in
4864 the actual ``Base`` document.
4866 ``user``, ``password``: the Login parameters as strings.
4867 The default value for both parameters is the empty string.
4869 A ``SFDatabases.SF_Database`` class instance or ``None``
4873 def IsLoaded(self, formdocument: str) -> bool:
4875 Return ``True`` if the given form Document is currently open.
4877 ``formdocument``: A valid hierarchical form document name as a case-sensitive string.
4881 def OpenFormDocument(self, formdocument: str, designmode: bool = ...) -> FORMDOCUMENT:
4883 Open the form document given by its hierarchical name either in normal or in design mode.
4884 If the form document is already open, the form document is made active without changing its mode.
4886 ``formdocument``: a valid hierarchical form document name as a case-sensitive string.
4888 ``designmode``: when ``True`` the form document is opened in design mode. Defaults to ``False``.
4890 The ``SFDocuments.SF_FormDocument`` class instance corresponding with the opened form document.
4894 def OpenQuery(self, queryname: str, designmode: bool = ...) -> DATASHEET:
4896 Opens the Data View window of the specified query and returns an instance of the
4897 ``SFDatabases.SF_Datasheet`` service.
4899 The query can be opened in normal or design mode.
4901 If the query is already open, its Data View window will be made active.
4903 ``queryname``: the name of an existing SELECT query as a case-sensitive String.
4905 ``designmode``: when ``True``, the query is opened in design mode.
4906 Otherwise, it is opened in normal mode (default).
4908 the ``SFDatabases.SF_Datasheet`` service instance corresponding with the query.
4910 Closing the Base document will cause the Data View window to be closed as well.
4914 def OpenTable(self, tablename: str, designmode: bool = ...) -> DATASHEET:
4916 Opens the Data View window of the specified table and returns an instance of the
4917 ``SFDatabases.SF_Datasheet`` service.
4919 The table can be opened in normal or design mode.
4921 If the table is already open, its Data View window will be made active.
4923 ``tablename``: the name of an existing table or view as a case-sensitive String.
4925 ``designmode``: when ``True``, the table is opened in design mode.
4926 Otherwise, it is opened in normal mode (default).
4928 the ``SFDatabases.SF_Datasheet`` service instance corresponding with the table.
4930 Closing the Base document will cause the Data View window to be closed as well.
4934 # pylint: disable=arguments-renamed
4935 def PrintOut(self, formdocument: str, pages: str = ..., copies: int = ...) -> bool:
4937 Send the content of the form document to the printer.
4938 The printer might be defined previously by default, by the user or by the ``SetPrinter()`` method.
4940 The method is deprecated. Use the ``SF_FormDocument.PrintOut()`` method instead.
4943 ``formdocument``: a valid form document name as a case-sensitive string.
4944 The form document must be open. It is activated by the method.
4946 ``pages``: the pages to print as a string, like in the user interface. Example: "1-4;10;15-18".
4947 Default is all pages.
4949 ``copies``: the number of copies. Defaults to 1.
4951 ``True`` when successful.
4955 def SetPrinter(self,
4956 formdocument: str = ...,
4958 orientation: Literal['PORTRAIT', 'LANDSCAPE'] = ...,
4959 paperformat: Literal['A3', 'A4', 'A5', 'LETTER', 'LEGAL', 'TABLOID'] = ...
4962 Define the printer options for the form document.
4964 The method is deprecated. Use the ``SF_FormDocument.SetPrinter()`` method instead.
4967 ``formdocument``: a valid form document name as a case-sensitive string.
4969 ``printer``: the name of the printer queue where to print to.
4970 When absent or space, the default printer is set.
4972 ``orientation``: either ``PORTRAIT`` or ``LANDSCAPE``. Left unchanged when absent.
4974 ``paperformat``: paper format. Left unchanged when absent.
4976 ``True`` when successful.
4980 # #########################################################################
4982 # #########################################################################
4983 class SF_Calc(SF_Document, SFServices):
4985 The ``SF_Calc`` class is focused on :
4986 - management (copy, insert, move, ...) of sheets within a ``Calc`` document
4987 - exchange of data between Python data structures and ``Calc`` ranges of values
4988 - copying and importing massive amounts of data
4990 All methods and properties defined for the ``Document`` service can also be accessed using a ``Calc``
4994 CurrentSelection: Union[RANGE, Tuple[RANGE, ...]]
4995 """ Get/set the single selected range as a string or the list of selected ranges as a tuple of strings. """
4997 def FirstCell(self, rangename: RANGE) -> RANGE:
4999 Returns the First used cell in a given range or sheet. When the argument is a sheet it will always
5000 return the "sheet.$A$1" cell. """
5002 def FirstColumn(self, rangename: RANGE) -> int:
5003 """ Returns the leftmost column number in a given range. """
5005 def FirstRow(self, rangename: RANGE) -> int:
5006 """ Returns the First used column in a given range. """
5008 def Height(self, rangename: RANGE) -> int:
5009 """ Returns the height in # of rows of the given range. """
5011 def LastCell(self, rangename: RANGE) -> RANGE:
5012 """ Returns the last used cell in a given sheet or range. """
5014 def LastColumn(self, rangename: RANGE) -> int:
5015 """ Returns the last used column in a given range or sheet. """
5017 def LastRow(self, rangename: RANGE) -> int:
5018 """ The last used row in a given range or sheet. """
5020 def Range(self, rangename: RANGE) -> CALCREFERENCE:
5021 """ Returns a (internal) range object """
5023 def Region(self, rangename: RANGE) -> RANGE:
5025 Returns the address of the smallest area that contains the specified range
5026 so that the area is surrounded by empty cells or sheet edges.
5027 This is equivalent to applying the ``Ctrl + *`` shortcut to the given range.
5030 def Sheet(self, sheetname: SHEETNAME) -> CALCREFERENCE:
5032 Returns a sheet reference that can be used as argument of methods like ``CopySheet()``. """
5034 def SheetName(self, rangename: RANGE) -> str:
5035 """ Returns the sheet name part of a range address. """
5037 def Width(self, rangename: RANGE) -> int:
5038 """ The number of columns (>= 1) in the given range. """
5040 def XCellRange(self, rangename: RANGE) -> XCellRange:
5041 """ A ``com.sun.star.Table.XCellRange`` UNO object. """
5043 def XSheetCellCursor(self, rangename: str) -> XSheetCellCursor:
5044 """ A ``com.sun.star.sheet.XSheetCellCursor`` UNO object. """
5046 def XSpreadsheet(self, sheetname: SHEETNAME) -> XSpreadsheet:
5047 """ A ``com.sun.star.sheet.XSpreadsheet`` UNO object. """
5050 def A1Style(self, row1: int, column1: int, row2: int = ..., column2: int = ..., sheetname: SHEETNAME = ...,
5053 Returns a range address as a string based on sheet coordinates, i.e. row and column numbers.
5055 If only a pair of coordinates is given, then an address to a single cell is returned.
5056 Additional arguments can specify the bottom-right cell of a rectangular range.
5058 Row and column numbers start at 1.
5061 ``row1``: specify the row number of the top cell in the range to be considered.
5063 ``column1``: specify the column number of the left cell in the range to be considered.
5065 ``row2``: specify the row number of the bottom cell in the range to be considered.
5066 If this argument is not provided, or if ``row2 < row1``,
5067 then the address of the single cell range represented by ``row1`` and ``column1`` is returned.
5069 ``column2``: specify the column number of the right cell in the range to be considered.
5070 If these arguments are not provided, or if ``column2 < rcolumn1``,
5071 then the address of the single cell range represented by ``row1`` and ``column1`` is returned.
5073 ``sheetname``: the name of the sheet to be prepended to the returned range address.
5074 The sheet must exist. The default value is ``"~"`` corresponding to the currently active sheet.
5076 A range address as a string.
5080 def Activate(self, sheetname: SHEETNAME = ...) -> bool:
5082 If the argument ``sheetname`` is provided, the given sheet is activated and becomes the currently
5083 selected sheet. If the argument is absent, then the document window is activated.
5085 ``sheetname``: the name of the sheet to be activated in the document.
5087 ``True`` if the document or the sheet could be made active. Otherwise, there is no change
5088 in the actual user interface.
5092 def Charts(self, sheetname: SHEETNAME, chartname: str = ...) -> Union[Tuple[str, ...], CHART]:
5094 Returns either the list with the names of all chart objects in a given sheet
5095 or a single Chart service instance.
5096 - If only ``sheetname`` is specified, a tuple containing the names of all charts is returned.
5097 - If a ``chartname`` is provided, then a single object corresponding to the desired chart is returned. The specified chart must exist.
5100 ``sheetname``: the name of the sheet from which the list of charts
5101 is to be retrieved or where the specified chart is located.
5103 ``chartname``: the user-defined name of the chart object to be returned.
5104 If the chart does not have a user-defined name, then the internal object name can be used.
5105 If this argument is absent, then the list of chart names in the specified sheet is returned.
5107 Either the list with the names of all chart objects in a given sheet or a
5108 single ``Chart`` service instance.
5114 filterformula: str = ...,
5115 filterscope: Literal['CELL', 'ROW', 'COLUMN'] = ...,
5118 Clears all the contents and formats of the given range.
5119 A filter formula can be specified to determine which cells shall be affected.
5121 ``range``: the range to be cleared, as a string.
5123 ``filterformula``: a ``Calc`` formula that shall be applied to the given range
5124 to determine which cells will be affected. The specified formula must return ``True``
5125 or ``False``. If this argument is not specified, then all cells in the range are affected.
5126 Express the formula in terms of (examples assume a range = ``"A1:J10"``):
5127 - the top-left cell of the range when ``filterscope`` = "CELL" e.g. ``"=(A1>100)"``
5128 - the topmost row of the range when ``filterscope`` = "ROW" e.g. ``"=(SUM($A1:$J1)<1000)"``
5129 - the leftmost column of the range when ``filterscope`` = "COLUMN" e.g. ``"=(A$10=SUM(A$1:A$9))"``
5131 ``filterscope``: determines how ``filterformula`` is expanded to the given range.
5132 The argument is mandatory if a ``filterformula`` is specified.
5136 def ClearFormats(self,
5138 filterformula: str = ...,
5139 filterscope: Literal['CELL', 'ROW', 'COLUMN'] = ...,
5142 Clears the formats of the given range.
5143 A filter formula can be specified to determine which cells shall be affected.
5145 ``range``: the range to be cleared, as a string.
5147 ``filterformula``: a ``Calc`` formula that shall be applied to the given range
5148 to determine which cells will be affected. The specified formula must return ``True``
5149 or ``False``. If this argument is not specified, then all cells in the range are affected.
5150 Express the formula in terms of (examples assume a range = ``"A1:J10"``):
5151 - the top-left cell of the range when ``filterscope`` = "CELL" e.g. ``"=(A1>100)"``
5152 - the topmost row of the range when ``filterscope`` = "ROW" e.g. ``"=(SUM($A1:$J1)<1000)"``
5153 - the leftmost column of the range when ``filterscope`` = "COLUMN" e.g. ``"=(A$10=SUM(A$1:A$9))"``
5155 ``filterscope``: determines how ``filterformula`` is expanded to the given range.
5156 The argument is mandatory if a ``filterformula`` is specified.
5160 def ClearValues(self,
5162 filterformula: str = ...,
5163 filterscope: Literal['CELL', 'ROW', 'COLUMN'] = ...,
5166 Clears the values and formulas in the given range.
5167 A filter formula can be specified to determine which cells shall be affected.
5169 ``range``: the range to be cleared, as a string.
5171 ``filterformula``: a ``Calc`` formula that shall be applied to the given range
5172 to determine which cells will be affected. The specified formula must return ``True``
5173 or ``False``. If this argument is not specified, then all cells in the range are affected.
5174 Express the formula in terms of (examples assume a range = ``"A1:J10"``):
5175 - the top-left cell of the range when ``filterscope`` = "CELL" e.g. ``"=(A1>100)"``
5176 - the topmost row of the range when ``filterscope`` = "ROW" e.g. ``"=(SUM($A1:$J1)<1000)"``
5177 - the leftmost column of the range when ``filterscope`` = "COLUMN" e.g. ``"=(A$10=SUM(A$1:A$9))"``
5179 ``filterscope``: determines how ``filterformula`` is expanded to the given range.
5180 The argument is mandatory if a ``filterformula`` is specified.
5183 def CompactLeft(self, range: RANGE, wholecolumn: bool = ..., filterformula: str = ...) -> RANGE:
5185 Deletes the columns of a specified range that match a filter expressed as a ``Calc`` formula.
5186 The filter is applied to each column to decide whether it will be deleted or not.
5188 The deleted column can be limited to the height of the specified range or span to the
5189 height of the entire sheet, thus deleting whole columns.
5191 ``range``: the range from which columns will be deleted, as a string.
5193 ``wholecolumn``: if this option is set to ``True`` the entire column will be deleted
5194 from the sheet. The default value is ``False``, which means that the deleted column
5195 will be limited to the height of the specified range.
5197 ``filterformula``: the filter to be applied to each column to determine whether it will
5198 be deleted. The filter is expressed as a ``Calc`` formula that should be applied
5199 to the first column. When the formula returns ``True`` for a column, that column will be
5200 deleted. The default filter deletes all empty columns.
5201 For example, suppose range ``"A1:J200"`` is selected (height = 200), so the default formula
5202 is ``"=(COUNTBLANK(A1:A200)=200)"``. This means that if all 200 cells are empty in the first
5203 column (Column A), then the column is deleted.
5205 String with the range address of the compacted range.
5206 If all columns are deleted, then an empty string is returned.
5212 wholerow: bool = ...,
5213 filterformula: str = ...
5216 Deletes the rows of a specified range that match a filter expressed as a ``Calc`` formula.
5217 The filter is applied to each row to decide whether it will be deleted or not.
5219 The deleted row can be limited to the width of the specified range or span to the
5220 width of the entire sheet, thus deleting whole rows.
5222 ``range``: the range from which rows will be deleted, as a string.
5224 ``wholerow``: if this option is set to ``True`` the entire row will be deleted
5225 from the sheet. The default value is ``False``, which means that the deleted row
5226 will be limited to the width of the specified range.
5228 ``filterformula``: the filter to be applied to each row to determine whether it will
5229 be deleted. The filter is expressed as a ``Calc`` formula that should be applied
5230 to the first row. When the formula returns ``True`` for a row, that row will be
5231 deleted. The default filter deletes all empty rows.
5232 For example, suppose range ``"A1:J200"`` is selected (width = 10), so the default formula
5233 is ``"=(COUNTBLANK(A1:J1)=10)"``. This means that if all 10 cells are empty in the first
5234 row (Row 1), then the row is deleted.
5236 String with the range address of the compacted range.
5237 If all rows are deleted, then an empty string is returned.
5242 sheetname: Union[SHEETNAME, CALCREFERENCE],
5244 beforesheet: Union[int, SHEETNAME]) -> bool:
5246 Copies a specified sheet before an existing sheet or at the end of the list of sheets.
5247 The sheet to be copied may be contained inside any open ``Calc`` document.
5249 ``sheetname``: the name of the sheet to be copied as a string,
5250 or a reference to a sheet as a ``CALCREFERENCE`` class instance.
5251 A ``CALCREFERENCE`` is produced by the ``Sheet`` property of the ``Calc`` class.
5253 ``newname``: the name of the sheet to insert. The name must not be in use in the document.
5255 ``beforesheet``: the name (string) or index (numeric, starting from 1) of the sheet
5256 before which to insert the copied sheet. The default behavior is to add the copied sheet
5257 at the last position.
5259 ``True`` if the sheet could be copied successfully.
5263 def CopySheetFromFile(self,
5265 sheetname: SHEETNAME,
5267 beforesheet: Union[int, SHEETNAME] = ...,
5270 Copies a specified sheet from a closed Calc document and pastes it before an existing
5271 sheet or at the end of the list of sheets.
5273 If the file does not exist, an error is raised. If the file is not a valid ``Calc`` file,
5274 a blank sheet is inserted. If the source sheet does not exist in the input file,
5275 an error message is inserted at the top of the newly pasted sheet.
5277 ``filename``: identifies the source file. It must follow the ``SF_FileSystem.FileNaming``
5278 notation. The file must not be protected with a password.
5280 ``sheetname``: the name of the sheet to be copied as a string.
5282 ``newname``: the name of the copied sheet to be inserted in the document.
5283 The name must not be in use in the document.
5285 ``beforesheet``: the name (string) or index (numeric, starting from 1)
5286 of the sheet before which to insert the copied sheet.
5287 The default behavior is to add the copied sheet at the last position.
5289 ``True`` if the sheet could be created.
5293 def CopyToCell(self,
5294 sourcerange: Union[RANGE, CALCREFERENCE],
5295 destinationcell: RANGE
5298 Copies a specified source range (values, formulas and formats) to a destination range or cell.
5299 The method reproduces the behavior of a Copy/Paste operation from a range to a single cell.
5301 The source range may belong to another open ``Calc`` document.
5304 ``sourcerange``: the source range as a string when it belongs to the same document
5305 or as a reference when it belongs to another open ``Calc`` document.
5307 ``destinationcell``: the destination cell where the copied range of cells will be pasted,
5308 as a string. If a range is given, only its top-left cell is considered.
5310 A string representing the modified range of cells.
5311 The modified area depends on the size of the source area.
5315 def CopyToRange(self,
5316 sourcerange: Union[RANGE, CALCREFERENCE],
5317 destinationrange: RANGE
5320 Copies downwards and/or rightwards a specified source range (values, formulas and formats)
5321 to a destination range. The method imitates the behavior of a Copy/Paste operation from
5322 a source range to a larger destination range.
5324 - If the height (or width) of the destination area is > 1 row (or column) then the height (or width) of the source must be <= the height (or width) of the destination. Otherwise, nothing happens.
5325 - If the height (or width) of the destination is = 1 then the destination is expanded downwards (or rightwards) up to the height (or width) of the source range.
5327 The source range may belong to another open ``Calc`` document.
5330 ``sourcerange``: the source range as a string when it belongs to the same document
5331 or as a reference when it belongs to another open ``Calc`` document.
5333 ``destinationrange``: the destination of the copied range of cells, as a string.
5335 A string representing the modified range of cells.
5339 def CreateChart(self,
5341 sheetname: SHEETNAME,
5343 columnheader: bool = ...,
5344 rowheader: bool = ...,
5347 Creates a new chart object showing the data in the specified range.
5348 The returned chart object can be further manipulated using the ``Chart service``.
5350 ``chartname``: the user-defined name of the chart to be created.
5351 The name must be unique in the same sheet.
5353 ``sheetname``: the name of the sheet where the chart will be placed.
5355 ``range``: the range to be used as the data source for the chart. The range may refer to
5356 any sheet of the ``Calc`` document.
5358 ``columnheader``: when ``True``, the topmost row of the range is used as labels
5359 for the category axis or the legend. Defaults to ``False``.
5361 ``rowheader``: when ``True``, the leftmost column of the range is used as labels
5362 for the category axis or the legend. Defaults to ``False``.
5364 A new chart service instance.
5368 def CreatePivotTable(self,
5369 pivottablename: str,
5372 datafields: Union[Sequence[str], str] = ...,
5373 rowfields: Union[Sequence[str], str] = ...,
5374 columnfields: Union[Sequence[str], str] = ...,
5375 filterbutton: bool = ...,
5376 rowtotals: bool = ...,
5377 columntotals: bool = ...,
5380 Creates a new pivot table with the properties defined by the arguments passed to the method.
5382 A name must be provided for the pivot table.
5383 If a pivot table with the same name already exists in the targeted sheet,
5384 it will be replaced without warning.
5387 ``pivottablename``: the user-defined name of the new pivot table.
5389 ``sourcerange``: the range containing the raw data, as a string.
5390 It is assumed that the first row contains the field names that are used by the pivot table.
5392 ``targetcell``: the top-left cell where the new pivot table will be placed.
5393 If a range is specified, only its top-left cell is considered.
5395 ``datafields``: it can be either a single string or a list of strings
5396 that define field names and functions to be applied.
5397 When a list is specified, it must follow the syntax ["FieldName[;Function]", ...].
5398 The allowed functions are: ``Sum, Count, Average, Max, Min, Product, CountNums, StDev, StDevP, Var, VarP`` and ``Median``.
5399 Function names must be provided in English.
5400 When all values are numerical, ``Sum`` is the default function, otherwise
5401 the default function is ``Count``.
5403 ``rowfields``: a single string or a list with the field names that will be used as the pivot
5406 ``columnfields``: a single string or a list with the field names that will be used
5407 as the pivot table columns.
5409 ``filterbutton``: determines whether a filter button will be displayed above the pivot
5410 table (Default = ``True``).
5412 ``rowtotals``: specifies if a separate column for row totals will be added to the pivot
5413 table (Default = ``True``).
5415 ``columntotals``: specifies if a separate row for column totals will be added to the pivot
5416 table (Default = ``True``)
5418 A string containing the range where the new pivot table was placed.
5422 def DAvg(self, range: RANGE) -> float:
5424 Get the number of the numeric values stored in the given range, excluding values from filtered
5425 and hidden rows and hidden columns, the same as for the status bar functions.
5427 ``range``: the range as a string where to get the values from.
5431 def DCount(self, range: RANGE) -> int:
5433 Get the number of numeric values stored in the given range, excluding values from filtered
5434 and hidden rows and hidden columns, the same as for the status bar functions.
5436 ``range``: the range as a string where to get the values from.
5440 def DMax(self, range: RANGE) -> float:
5442 Get the greatest of the numeric values stored in the given range, excluding values from filtered
5443 and hidden rows and hidden columns, the same as for the status bar functions.
5445 ``range``: the range as a string where to get the values from.
5449 def DMin(self, range: RANGE) -> float:
5451 Get the smallest of the numeric values stored in the given range, excluding values from filtered
5452 and hidden rows and hidden columns, the same as for the status bar functions.
5454 ``range``: the range as a string where to get the values from.
5458 def DSum(self, range: RANGE) -> float:
5460 Get the sum of the numeric values stored in the given range, excluding values from filtered
5461 and hidden rows and hidden columns, the same as for the status bar functions.
5463 ``range``: the range as a string where to get the values from.
5467 def ExportRangeToFile(self,
5470 imagetype: Literal['pdf', 'jpeg', 'png'] = ...,
5471 overwrite: bool = ...,
5474 Exports the specified range as an image or PDF file.
5476 ``range``: a sheet name or a cell range to be exported, as a string.
5478 ``filename``: the name of the file to be saved. It must follow the
5479 ``SF_FileSystem. FileNaming`` notation.
5481 ``imagetype``: identifies the destination file type. Possible values are ``jpeg, pdf``
5482 and ``png``. Defaults to ``pdf``.
5484 ``overwrite``: when set to ``True``, the destination file may be overwritten.
5485 Defaults to ``False``.
5487 ``True`` if the destination file was successfully saved.
5491 def Forms(self, sheetname: SHEETNAME, form: Union[int, str] = ...) -> Union[FORM, Tuple[str, ...]]:
5493 Depending on the parameters provided this method will return:
5495 - A tuple with the names of all the forms contained in a given sheet (if the form argument is absent)
5496 - A ``SFDocuments.Form`` service instance representing the form specified as argument.
5499 ``sheetname``: the name of the sheet, as a string, from which the form will be retrieved.
5501 ``form``: the name or index corresponding to a form stored in the specified sheet.
5502 If this argument is absent, the method will return a list with the names of all forms available
5507 def GetColumnName(self, columnnumber: int) -> str:
5509 Converts a column number ranging between 1 and 16384 into its corresponding
5510 letter (column 'A', 'B', ..., 'XFD'). If the given column number is outside
5511 the allowed range, a zero-length string is returned.
5513 ``columnnumber``: the column number as an integer value in the interval 1 ... 16384.
5517 def GetFormula(self, range: RANGE) -> Union[str, Tuple[str, ...], Tuple[Tuple[str, ...]]]:
5519 Get the formula(s) stored in the given range of cells as a single string, a tuple of strings,
5520 or a tuple of tuples of strings.
5522 ``range``: the range where to get the formulas from, as a string.
5524 The names of ``Calc`` functions used in the returned formulas are expressed in English.
5530 ) -> Union[str, Tuple[Union[str, float], ...], Tuple[Tuple[Union[str, float], ...]], ...]:
5532 Get the value(s) stored in the given range of cells as a single value, a tuple or a tuple of tuples.
5533 All returned values are either doubles or strings.
5535 ``range``: the range where to get the values from, as a string.
5537 If a cell contains a date, the number corresponding to that date will be returned.
5538 To convert numeric values to dates, use the ``CDate()`` function from the
5539 ``SFScriptForge.SF_Basic`` service.
5543 def ImportFromCSVFile(self,
5545 destinationcell: RANGE,
5546 filteroptions: str = ...
5549 Imports the contents of a CSV-formatted text file and places it on a given destination cell.
5550 The destination area is cleared of all contents and formats before inserting the contents
5553 ``filename``: identifies the file to open. It must follow the ``SF_FileSystem.FileNaming``
5556 ``destinationcell``: the destination cell to insert the imported data, as a string.
5557 If instead a range is given, only its top-left cell is considered.
5559 ``filteroptions``: the arguments for the CSV input filter.
5561 A string representing the modified range of cells.
5562 The modified area depends only on the content of the source file.
5564 Default ``filteroptions`` make the following assumptions:
5565 - The input file encoding is UTF8.
5566 - The field separator is a comma, a semicolon or a Tab character.
5567 - The string delimiter is the double quote (").
5568 - All lines are included.
5569 - Quoted strings are formatted as text.
5570 - Special numbers are detected.
5571 - All columns are presumed to be texts, except if recognized as valid numbers.
5572 - The language is English/US, which implies that the decimal separator is "." and the thousands separator is ",".
5576 def ImportFromDatabase(self,
5577 filename: FILE = ...,
5578 registrationname: str = ...,
5579 destinationcell: RANGE = ...,
5580 sqlcommand: SQL_SELECT = ...,
5581 directsql: bool = ...,
5584 Imports the contents of a database table, query or resultset, i.e. the result of a
5585 SELECT SQL command, inserting it on a destination cell.
5587 The destination area is cleared of all contents and formats before inserting the
5588 imported contents. The size of the modified area is fully determined by the contents in
5591 ``filename``: identifies the file to open. It must follow the ``SF_FileSystem.FileNaming``
5594 ``registrationname``: the name to use to find the database in the databases register.
5595 This argument is ignored if a filename is provided.
5597 ``destinationcell``: the destination of the imported data, as a string.
5598 If a range is given, only its top-left cell is considered.
5600 ``sqlcommand``: a table or query name (without surrounding quotes or square brackets)
5601 or a SELECT SQL statement in which table and field names may be surrounded by square brackets
5602 or quotes to improve its readability.
5604 ``directsql``: when ``True``, the SQL command is sent to the database engine without
5605 pre-analysis. Default is ``False``. The argument is ignored for tables.For queries,
5606 the applied option is the one set when the query was defined.
5610 def ImportStylesFromFile(self,
5612 families: Union[str, Sequence[str]] = ...,
5613 overwrite: bool = ...
5616 This method loads all the styles belonging to one or more style families from a closed
5617 file into the actual ``Calc`` document.
5619 Are always imported together:
5620 - ``ParagraphStyles`` and ``CharacterStyles``
5621 - ``NumberingStyles`` and ``ListStyles``
5624 ``filename``: the file from which to load the styles in the ``SFScriptForge.FileSystem``
5625 notation. The file is presumed to be a ``Calc`` document.
5627 ``families``: one of the style families present in the actual document,
5628 as a case-sensitive string or a tuple of such strings.
5629 Leave this argument blank to import all families.
5631 ``overwrite``: when ``True``, the actual styles may be overwritten. Default is ``False``.
5633 ``True`` if styles were successfully imported.
5638 def InsertSheet(self, sheetname: SHEETNAME, beforesheet: Union[SHEETNAME, int] = ...) -> bool:
5640 Inserts a new empty sheet before an existing sheet or at the end of the list of sheets.
5642 ``sheetname``: the name of the new sheet.
5644 ``beforesheet``: the name (string) or index (numeric, starting from 1) of the sheet
5645 before which to insert the new sheet. This argument is optional and the default behavior
5646 is to insert the sheet at the last position.
5648 ``True`` if the sheet could be inserted successfully.
5652 def MoveRange(self, source: RANGE, destination: RANGE) -> RANGE:
5654 Moves a specified source range to a destination cell.
5656 ``source``: the source range of cells, as a string.
5658 ``destination``: the destination cell, as a string. If a range is given,
5659 its top-left cell is considered as the destination.
5661 A string representing the modified range of cells.
5662 The modified area depends only on the size of the source area.
5667 sheetname: SHEETNAME,
5668 beforesheet: Union[SHEETNAME, int] = ...
5671 Moves an existing sheet and places it before a specified sheet or at the end of the list of sheets.
5673 ``sheetname``: the name of the sheet to move. The sheet must exist or an exception is raised.
5675 ``beforesheet``: The name (string) or index (numeric, starting from 1) of the sheet
5676 before which the original sheet will be placed. This argument is optional and
5677 the default behavior is to move the sheet to the last position.
5679 ``True`` if the sheet could be moved successfully.
5691 Returns a new range (as a string) offset and/or resized by a certain number of rows and columns
5694 This method has the same behavior as the homonymous Calc's ``Offset()`` built-in function.
5697 ``range``: the range, as a string, that the method will use as reference to perform
5698 the offset operation.
5700 ``rows``: the number of rows by which the initial range is offset upwards (negative value)
5701 or downwards (positive value). Use 0 (default) to stay in the same row.
5703 ``columns``: the number of columns by which the initial range is offset to the left
5704 (negative value) or to the right (positive value). Use 0 (default) to stay in the same column.
5706 ``height``: the vertical height for an area that starts at the new range position.
5707 Omit this argument when no vertical resizing is needed.
5709 ``width``: the horizontal width for an area that starts at the new range position.
5710 Omit this argument when no horizontal resizing is needed.
5714 - Arguments ``rows`` and ``columns`` must not lead to zero or negative start row or column.
5715 - Arguments ``height`` and ``width`` must not lead to zero or negative count of rows or columns.
5719 def OpenRangeSelector(self,
5721 selection: RANGE = ...,
5722 singlecell: bool = ...,
5723 closeafterselect: bool = ...,
5726 Opens a non-modal dialog that can be used to select a range in the document and returns a string
5727 containing the selected range.
5729 ``title``: the title of the dialog, as a string.
5731 ``selection``: an initial range that is selected when the dialog is displayed.
5733 ``singlecell``: when ``True`` (default) only single-cell selection is allowed.
5734 When ``False`` range selection is allowed.
5736 ``closeafterselect``: when ``True`` (default) the dialog is closed immediately after
5737 the selection is made. When ``False`` the user can change the selection as many times
5738 as needed. Dialog closure is manual.
5740 The selected range as a string, or the empty string when the user cancelled the request.
5742 This method opens the same dialog that is used by ``LibreOffice`` when the ``Shrink``
5743 button is pressed. For example, the ``Tools + Goal Seek`` dialog has a ``Shrink`` button
5744 to the right of the ``Formula`` cell field.
5751 tokencharacter: str = ...
5754 Returns the input string after substituting its tokens by their values in a given range.
5756 This method can be used to quickly extract specific parts of a range name, such as the sheet name
5757 or the first cell column and row, and use them to compose a new range address or a formula.
5760 ``inputstr``: the string containing the tokens that will be replaced by the corresponding
5761 values in ``range``.
5763 ``range``: the range from which values will be extracted. If it contains a sheet name,
5764 the sheet must exist.
5766 ``tokencharacter``: the character used to identify tokens. Defaults to "%".
5769 - ``%S`` - the sheet name containing the range, including single quotes when necessary.
5770 - ``%R1`` - the row number of the top left cell of the range.
5771 - ``%C1`` - the column letter of the top left cell of the range.
5772 - ``%R2`` - the row number of the bottom right cell of the range.
5773 - ``%C2`` - the column letter of the bottom right cell of the range.
5775 The input string after substitution of the contained tokens.
5780 sheetname: SHEETNAME = ...,
5782 copies: int = ...) -> bool:
5784 Send the content of the given sheet to the printer.
5785 The printer might be defined previously by default, by the user or by the ``SF_Document.SetPrinter()``
5788 ``sheetname``: the sheet to print, default is the active sheet.
5790 ``pages``: the pages to print as a string, like in the user interface. Example: "1-4;10;15-18".
5791 Default is all pages.
5793 ``copies``: the number of copies. Defaults to 1.
5795 ``True`` when successful.
5799 def RemoveDuplicates(self,
5801 columns: Union[int, Sequence[int]],
5803 casesensitive: bool = ...,
5804 mode: Literal["CLEAR", "COMPACT"] = ...,
5807 Removes duplicate rows from a specified range.
5808 The comparison to determine if a given row is a duplicate is done based on a subset
5809 of the columns in the range.
5811 The resulting range replaces the input range, in which, either:
5813 - all duplicate rows are cleared from their content
5814 - all duplicate rows are suppressed and rows below are pushed upwards.
5816 Anyway, the first copy of each set of duplicates is kept and the initial sequence is preserved.
5819 ``range``: the range, as a string, from which the duplicate rows should be removed.
5821 ``columns``: a single integer or a tuple of integers containing column numbers,
5822 indicating which columns will be considered to determine if a row is a duplicate or not.
5823 If this argument is left blank, then only the first column is used.
5824 Column numbers must be in the interval between ``1`` and the range width.
5826 ``header``: when ``True``, the first row is a header row. Default is ``False``.
5828 ``casesensitive``: for string comparisons. Default is ``False``.
5830 ``mode``: either ``"CLEAR"`` or ``"COMPACT"`` (default).
5831 For large ranges, the ``"COMPACT"`` mode is probably significantly slower.
5833 The resulting range as a string.
5837 def RemoveSheet(self, sheetname: SHEETNAME) -> bool:
5839 Removes an existing sheet from the document.
5841 ``sheetname``: the name of the sheet to remove.
5843 ``True`` if the sheet could be removed successfully.
5847 def RenameSheet(self, sheetname: SHEETNAME, newname: SHEETNAME) -> bool:
5849 Renames the given sheet.
5851 ``sheetname``: the name of the sheet to rename.
5853 ``newname``: the new name of the sheet. It must not exist yet.
5855 ``True`` if successful.
5861 value: Union[SCALAR, VECTOR, MATRIX]
5864 Stores the given value starting from a specified target cell. The updated area expands
5865 itself from the target cell or from the top-left corner of the given range to accommodate
5866 the size of the input value argument. Vectors are always expanded vertically.
5868 ``targetcell``: the cell or a range as a string from where to start to store the given value.
5870 ``value``: a scalar, a vector or an array with the new values to be stored from the target
5871 cell or from the top-left corner of the range if targetcell is a range.
5872 The new values must be strings, numeric values or dates. Other types will cause the
5873 corresponding cells to be emptied.
5875 A string representing the modified area as a range of cells.
5877 To dump the full contents of an array in a sheet, use ``SetArray()``. To dump the contents
5878 of an array only within the boundaries of the targeted range of cells, use ``SetValue()``.
5882 def SetCellStyle(self,
5885 filterformula: str = ...,
5886 filterscope: Literal['CELL', 'ROW', 'COLUMN'] = ...,
5889 Applies the specified cell style to the given target range.
5890 The range is updated and the remainder of the sheet is left untouched.
5891 Either the full range is updated or a selection based on a ``filterformula``.
5892 If the cell style does not exist, an error is raised.
5894 ``targetrange``: the range to which the style will be applied, as a string.
5896 ``style``: the name of the cell style to apply.
5898 ``filterformula``: a ``Calc`` formula that shall be applied to the given range
5899 to determine which cells will be affected. The specified formula must return ``True``
5900 or ``False``. If this argument is not specified, then all cells in the range are affected.
5902 Express the formula in terms of (examples assume a range = ``"A1:J10"``):
5903 - the top-left cell of the range when ``filterscope`` = "CELL" e.g. ``"=(A1>100)"``
5904 - the topmost row of the range when ``filterscope`` = "ROW" e.g. ``"=(SUM($A1:$J1)<1000)"``
5905 - the leftmost column of the range when ``filterscope`` = "COLUMN" e.g. ``"=(A$10=SUM(A$1:A$9))"``
5907 ``filterscope``: determines how ``filterformula`` is expanded to the given range.
5908 Tuple The argument is mandatory if a ``filterformula`` is specified.
5910 A string representing the modified area as a range of cells.
5914 def SetFormula(self,
5916 formula: Union[str, Sequence[str], Sequence[Sequence[str]]]
5919 Inserts the given (list of) formula(s) in the specified range.
5920 The size of the modified area is equal to the size of the range.
5922 ``targetrange``: the range to insert the formulas, as a string.
5924 ``formula``: a string, a tuple or a tuple of tuples of strings with the new
5925 formulas for each cell in the target range.
5927 A string representing the modified area as a range of cells.
5929 The full range is updated and the remainder of the sheet is left unchanged.
5931 If the given ``formula`` is a string, the unique formula is pasted along the
5932 whole range with adjustment of the relative references.
5934 If the size of ``formula`` is smaller than the size of ``targetrange``, then the
5935 remaining cells are emptied.
5937 If the size of ``formula`` is larger than the size of ``targetrange``, then the
5938 formulas are only partially copied until they fill the size of ``targetrange``.
5940 Vectors are always expanded vertically, except if ``targetrange`` has a height
5947 value: Union[SCALAR, VECTOR, MATRIX]
5950 Stores the given value(s) in the specified range. The size of the modified area
5951 is equal to the size of the target range.
5953 ``targetrange``: the range where to store the given value, as a string.
5955 ``value``: a scalar, a vector or an array with the new values for each
5956 cell of the range. The new values must be strings, numeric values or
5957 dates. Other types will cause the corresponding cells to be emptied.
5959 A string representing the modified area as a range of cells.
5962 def ShiftDown(self, range: RANGE, wholerow: bool = ..., rows: int = ...) -> RANGE:
5964 Moves a given range of cells downwards by inserting empty rows.
5965 The current selection is not affected.
5967 Depending on the value of the ``wholerows`` argument the inserted rows can either
5968 span the width of the specified range or span all columns in the row.
5970 ``range``: the range above which rows will be inserted, as a string.
5972 ``wholerow``: if set to ``False`` (default), then the width
5973 of the inserted rows will be the same as the width of the specified range.
5974 Otherwise, the inserted row will span all columns in the sheet.
5976 ``rows``: the number of rows to be inserted. The default value is
5977 the height of the original range. The number of rows must be a positive number.
5979 A string representing the new location of the initial range.
5983 def ShiftLeft(self, range: RANGE, wholecolumn: bool = ..., columns: int = ...) -> RANGE:
5985 Deletes the leftmost columns of a given range and moves to the left all cells to the right
5986 of the given range. The current selection is not affected.
5988 Depending on the value of the ``wholecolumn`` argument the deleted columns can either span the
5989 height of the specified range or span all rows in the column.
5991 ``range``: the range from which cells will be deleted, as a string.
5993 ``wholecolumn``: if set to ``False`` (default), then the height of the deleted
5994 columns will be the same as the height of the specified range. Otherwise, the deleted
5995 columns will span all rows in the sheet.
5997 ``columns``: the number of columns to be deleted from the specified range.
5998 The default value is the width of the original range, which is also the maximum
5999 value of this argument.
6001 A string representing the location of the remaining portion of the initial range.
6002 If all cells in the original range have been deleted, then an empty string is returned.
6006 def ShiftRight(self, range: RANGE, wholecolumn: bool = ..., columns: int = ...) -> RANGE:
6008 Moves a given range of cells to the right by inserting empty columns.
6009 The current selection is not affected.
6011 Depending on the value of the ``wholecolumn`` argument the inserted columns can
6012 either span the height of the specified range or span all rows in the column.
6014 ``range``: the range which will have empty columns inserted to its left, as a string.
6016 ``wholecolumn``: if set to ``False`` (default), then the height of the inserted
6017 columns will be the same as the height of the specified range. Otherwise, the inserted
6018 columns will span all rows in the sheet.
6020 ``columns``: the number of columns to be inserted. The default value is the width
6021 of the original range.
6023 A string representing the new location of the initial range.
6025 If the shifted range exceeds the sheet edges, then nothing happens.
6029 def ShiftUp(self, range: RANGE, wholerow: bool = ..., rows: int = ...) -> RANGE:
6031 Deletes the topmost rows of a given range and moves upwards all cells below the given range.
6032 The current selection is not affected.
6034 Depending on the value of the ``wholerow`` argument the deleted rows can either span the width
6035 of the specified range or span all columns in the row.
6037 ``range``: the range from which cells will be deleted, as a string.
6039 ``wholerow``: if set to ``False`` (default), then the width of the deleted
6040 rows will be the same as the width of the specified range. Otherwise, the deleted
6041 row will span all columns in the sheet.
6043 ``rows``: the number of rows to be deleted from the specified range.
6044 The default value is the height of the original range, which is also the maximum
6045 value of this argument.
6047 A string representing the location of the remaining portion of the initial range.
6048 If all cells in the original range have been deleted, then an empty string is returned.
6054 sortkeys: Union[int, Sequence[int]],
6055 sortorder: Union[Literal['ASC', 'DESC', ''], Sequence[Literal['ASC', 'DESC', '']]] = ...,
6056 destinationcell: RANGE = ...,
6057 containsheader: bool = ...,
6058 casesensitive: bool = ...,
6059 sortcolumns: bool = ...,
6062 Sort the given range on any number of columns/rows. The sorting order may vary by column/row.
6064 ``range``: the range to be sorted, as a string.
6066 ``sortkeys``: a scalar (if 1 column/row) or a tuple of column/row numbers starting from 1.
6068 ``sortorder``: a scalar or a tuple of strings containing the values
6069 ``"ASC"`` (ascending), ``"DESC"`` (descending) or ``""`` (which defaults to ascending).
6070 Each item is paired with the corresponding item in ``sortkeys``.
6071 If the sortorder tuple is shorter than ``sortkeys``, the remaining keys are sorted
6074 ``destinationcell``: the destination cell of the sorted range of cells,
6075 as a string. If a range is given, only its top-left cell is considered.
6076 By default, the source range is overwritten.
6078 ``containsheader``: when ``True``, the first row/column is not sorted.
6080 ``casesensitive``: only for string comparisons. Default is ``False``.
6082 ``sortcolumns``: when ``True``, the columns are sorted from left to right.
6083 Default is ``False`` : rows are sorted from top to bottom.
6085 A string representing the modified range of cells.
6089 # #########################################################################
6090 # SF_CalcReference CLASS
6091 # #########################################################################
6092 class SF_CalcReference(SFServices):
6094 The SF_CalcReference class has as unique role to hold sheet and range references.
6097 # #########################################################################
6099 # #########################################################################
6100 class SF_Chart(SFServices):
6102 The SF_Chart module is focused on the description of chart documents
6103 stored in Calc sheets.
6104 With this service, many chart types and chart characteristics available
6105 in the user interface can be read or modified.
6108 ChartType: Literal['Pie', 'Bar', 'Donut', 'Column', 'Area', 'Line', 'XY', 'Bubble', 'Net']
6109 """ Get/set the chart type as a string that can assume one of the following values: "Pie", "Bar",
6110 "Donut", "Column", "Area", "Line", "XY", "Bubble", "Net". """
6112 """ When ``True`` indicates that the chart is three-dimensional and each series is arranged in the z-direction.
6113 When ``False`` series are arranged considering only two dimensions. """
6114 Dim3D: Union[bool, str]
6115 """ Get/set if the chart is displayed with 3D elements. If the value is a string, it must be either
6116 ``"Bar", "Cylinder", "Cone"`` or ``"Pyramid"``. If the boolean ``True`` value is specified,
6117 then the chart is displayed using 3D bars. """
6118 Exploded: Union[int, float]
6119 """ Get/set how much pie segments are offset from the chart center as a percentage of the radius.
6120 Applicable to ``Pie`` and ``Donut`` charts only. """
6122 """ When ``True``, specifies a filled net chart. Applicable to ``net`` charts only. """
6124 """ Specifies whether the chart has a legend. """
6126 """ When ``True``, chart series are stacked and each category sums up to 100%.
6127 Applicable to ``Area``, ``Bar``, ``Bubble``, ``Column`` and ``Net`` charts. """
6129 """ When ``True``, chart series are stacked.
6130 Applicable to ``Area``, ``Bar``, ``Bubble``, ``Column`` and ``Net`` charts. """
6132 """ Get/set the main title of the chart. """
6134 """ Get/set the title of the X-axis. """
6136 """ Get/set the title of the Y-axis. """
6139 """ Returns the object representing the chart, which is an instance of the ``ScChartObj`` class. """
6141 """ Returns the ``com.sun.star.chart.XDiagram`` object representing the diagram of the chart. """
6143 """ Returns the ``com.sun.star.drawing.XShape`` object representing the shape of the chart. """
6145 """ Returns the ``com.sun.star.table.XTableChart`` object representing the data being displayed in the chart.
6148 def ExportToFile(self,
6150 imagetype: Literal['gif', 'jpeg', 'png', 'svg', 'tiff'] = ...,
6151 overwrite: bool = ...
6154 Saves the chart as an image file in a specified location.
6156 ``filename``: identifies the path and file name where the image will be saved.
6157 It must follow the notation defined in ``SF_FileSystem.FileNaming``.
6159 ``imagetype``: the name of the image type to be created.
6160 The following values are accepted: ``gif, jpeg, png`` (default), ``svg`` and ``tiff``.
6162 ``overwrite``: specifies if the destination file can be overwritten. Defaults to ``False``.
6164 ``True`` if the image file could be successfully created.
6168 def Resize(self, xpos: int = ..., ypos: int = ..., width: int = ..., height: int = ...) -> bool:
6170 Changes the position of the chart in the current sheet and modifies its width and height.
6172 ``xpos``: specify the new ``X`` position of the chart.
6174 ``ypos``: specify the new ``Y`` position of the chart.
6176 ``width``: specify the new width of the chart.
6178 ``height``: specify the new height of the chart.
6180 ``True`` if repositioning/resizing was successful.
6182 - All arguments are provided as integer values that correspond to ``1/100`` of a millimeter.
6183 - Omitted arguments leave the corresponding actual values unchanged.
6184 - Negative arguments are ignored.
6188 # #########################################################################
6190 # #########################################################################
6191 class SF_Form(SFServices):
6193 Management of forms defined in LibreOffice documents. Supported types are Base, Calc and Writer documents.
6194 It includes the management of sub-forms
6195 Each instance of the current class represents a single form or a single sub-form
6196 A form may optionally be (understand "is often") linked to a data source manageable with
6197 the SFDatabases.Database service. The current service offers rapid access to that service.
6201 """ Get/set if the form allows to delete records. """
6203 """ Get/set if the form allows to add records. """
6205 """ Get/set if the form allows to update records. """
6207 """ Get the hierarchical name of the Base form document containing the actual form. """
6209 """ Specifies uniquely the current record of the form's underlying table, query or SQL statement. """
6211 """ Identifies the current record in the dataset being viewed on a form. If the row number is positive,
6212 the cursor moves to the given row number with respect to the beginning of the result set. Row count starts at 1.
6213 If the given row number is negative, the cursor moves to an absolute row position with respect to the end
6214 of the result set. Row -1 refers to the last row in the result set. """
6216 """ Specifies a subset of records to be displayed as a ``SQL WHERE``-clause without the ``WHERE`` keyword. """
6217 LinkChildFields: Tuple[str, ...]
6218 """ Specifies how records in a child subform are linked to records in its parent form. """
6219 LinkParentFields: Tuple[str, ...]
6220 """ Specifies how records in a child subform are linked to records in its parent form. """
6222 """ The name of the current form. """
6224 OnApproveCursorMove: SCRIPT_URI
6225 """ Get/set the macro triggered by the ``Before record change`` event."""
6226 OnApproveParameter: SCRIPT_URI
6227 """ Get/set the macro triggered by the ``Fill parameters`` event."""
6228 OnApproveReset: SCRIPT_URI
6229 """ Get/set the macro triggered by the ``Prior to reset`` event."""
6230 OnApproveRowChange: SCRIPT_URI
6231 """ Get/set the macro triggered by the ``Before record action`` event."""
6232 OnApproveSubmit: SCRIPT_URI
6233 """ Get/set the macro triggered by the ``Before submitting`` event."""
6234 OnConfirmDelete: SCRIPT_URI
6235 """ Get/set the macro triggered by the ``Confirm deletion`` event."""
6236 OnCursorMoved: SCRIPT_URI
6237 """ Get/set the macro triggered by the ``After record change`` event."""
6238 OnErrorOccurred: SCRIPT_URI
6239 """ Get/set the macro triggered by the ``Error occurred`` event."""
6240 OnLoaded: SCRIPT_URI
6241 """ Get/set the macro triggered by the ``When loading`` event."""
6242 OnReloaded: SCRIPT_URI
6243 """ Get/set the macro triggered by the ``When reloading`` event."""
6244 OnReloading: SCRIPT_URI
6245 """ Get/set the macro triggered by the ``Before reloading`` event."""
6246 OnResetted: SCRIPT_URI
6247 """ Get/set the macro triggered by the ``After resetting`` event."""
6248 OnRowChanged: SCRIPT_URI
6249 """ Get/set the macro triggered by the ``After record action`` event."""
6250 OnUnloaded: SCRIPT_URI
6251 """ Get/set the macro triggered by the ``When unloading`` event."""
6252 OnUnloading: SCRIPT_URI
6253 """ Get/set the macro triggered by the ``Before unloading`` event."""
6256 """ Specifies in which order the records should be displayed as a ``SQL ORDER BY`` clause
6257 without the ``ORDER BY`` keywords. """
6258 Parent: Union[FORM, FORMDOCUMENT, DOCUMENT, CALC, WRITER]
6259 """ The parent of the current form. It can be either a ``SFDocuments.Form``, a ``SFDocuments.FormDocument``,
6260 a ``SFDocuments.Document`` object or one of its subclasses. """
6261 RecordSource: Union[SQL_SELECT, str]
6262 """ Specifies the source of the data, as a table name, a query name or a SQL statement. """
6265 """ The UNO object representing interactions with the form. Refer to ``com.sun.star.form.XForm`` and
6266 ``com.sun.star.form.component.DataForm`` in the API documentation for detailed information. """
6268 def Activate(self) -> bool:
6270 Sets the focus on the container of the current ``Form`` instance.
6272 The behavior of the ``Activate`` method depends on the type of document where the form is located.
6273 * In `Writer`` documents: Sets the focus on that document.
6274 * In ``Calc`` documents: Sets the focus on the sheet to which the form belongs.
6275 * In ``Base`` documents: Sets the focus on the ``FormDocument`` the ``Form`` refers to.
6277 ``True`` if focusing was successful.
6281 def CloseFormDocument(self) -> bool:
6283 Closes the ``form`` document containing the actual ``Form`` instance. The ``Form`` instance is disposed.
6285 The method is deprecated. Use the ``SF_FormDocument.CloseDocument()`` method instead.
6288 ``True`` if closure is successful.
6290 This method only closes form documents located in ``Base`` documents.
6291 If the form is stored in a ``Writer`` or ``Calc`` document, calling ``CloseFormDocument()``
6292 will have no effect.
6296 def Controls(self, controlname: str = ...) -> Union[FORMCONTROL, Tuple[str, ...]]:
6298 The value returned by the method depends on the arguments provided:
6299 - If the method is called without arguments, then it returns the list of the controls contained in the form.
6301 - If the optional ``controlName`` argument is provided, the method returns a ``FormControl`` class instance referring to the specified control.
6304 Subform controls are ignored by this method.
6308 def GetDatabase(self, user: str = ..., password: str = ...) -> Optional[DATABASE]:
6310 Gets a ``SFDatabases.Database`` instance giving access to the execution of SQL commands
6311 on the database the current form is connected to and/or that is stored in the current ``Base`` document.
6313 Each form has its own database connection, except in ``Base`` documents where they all
6314 share the same connection.
6316 ``user``, ``password````: the login parameters.
6318 A ``SFDatabases.Database`` class instance.
6322 def MoveFirst(self) -> bool:
6324 The form cursor is positioned on the first record.
6327 ``True`` if successful.
6331 def MoveLast(self) -> bool:
6333 The form cursor is positioned on the last record.
6336 ``True`` if successful.
6340 def MoveNew(self) -> bool:
6342 The form cursor is positioned on the new record area.
6345 ``True`` if successful.
6349 def MoveNext(self, offset: int = ...) -> bool:
6351 The form cursor is positioned on the next record.
6353 ``offset``: the number of records to go forward. Defaults to 1.
6355 ``True`` if successful.
6359 def MovePrevious(self, offset: int = ...) -> bool:
6361 The form cursor is positioned on the previous record.
6363 ``offset``: the number of records to go backward. Defaults to 1.
6365 ``True`` if successful.
6369 def Requery(self) -> bool:
6371 Reloads the current data from the database and refreshes the form.
6372 The cursor is positioned on the first record.
6375 ``True`` if successful.
6379 def Subforms(self, subform: Union[int, str] = ...) -> Union[FORM, Tuple[str, ...]]:
6381 Depending on the parameters provided this method will return:
6383 - A tuple with the names of all the subforms contained in the actual form (if the form argument is absent)
6384 - A ``SFDocuments.Form`` service instance representing the subform specified as argument.
6387 ``subform``: the name or index corresponding to a subform stored in the actual form.
6388 If this argument is absent, the method will return a list with the names of
6389 all available subforms.
6393 # #########################################################################
6394 # SF_FormControl CLASS
6395 # #########################################################################
6396 class SF_FormControl(SFServices):
6398 Manage the controls belonging to a form or subform stored in a document.
6400 Each instance of the current class represents a single control within a form, a subform or a column
6401 in a table-control. A prerequisite is that all controls within the same form, subform or table-control
6402 must have a unique name.
6405 Action: Literal['none', 'submitForm', 'resetForm', 'refreshForm', 'moveToFirst', 'moveToLast', 'moveToNext',
6406 'moveToPrev', 'saveRecord', 'moveToNew', 'deleteRecord', 'undoRecord']
6407 """ Get/set the action triggered when the button is clicked. Applicable to ``Button`` controls. """
6409 """ Get/set the text associated with the control. Applicable to ``Button, CheckBox, FixedText,
6410 GroupBox, RadioButton`` controls. """
6412 """ Specifies the rowset field mapped onto the current control. Applicable to
6413 ``CheckBox, ComboBox, CurrencyField, DateField, FormattedField, ImageControl, ListBox, NumericField,
6414 PatternField, RadioButton, TextField, TimeField`` controls. """
6416 """ get the type of control as a string. """
6418 """ Get/set whether a command button is the default (OK) button.
6419 Applicable to ``Button`` controls. """
6421 """ Specifies the default value used to initialize a control in a new record.
6422 Applicable to ``CheckBox, ComboBox, CurrencyField, DateField, FileControl, FormattedField, ListBox,
6423 NumericField, PatternField, RadioButton, SpinButton, TextField, TimeField`` controls. """
6425 """ Specifies if the control is accessible with the cursor. """
6426 Format: Literal["Standard (short)", "Standard (short YY)", "Standard (short YYYY)", "Standard (long)",
6427 "DD/MM/YY", "MM/DD/YY", "YY/MM/DD", "DD/MM/YYYY", "MM/DD/YYYY", "YYYY/MM/DD", "YY-MM-DD", "YYYY-MM-DD",
6428 "24h short", "24h long", "12h short", "12h long"]
6429 """ Get/set the format used to display dates and times. Applicable to ``DateField, TimeField, FormattedField``
6432 """ Get the number of rows in the control. Applicable to ``ComboBox, ListBox`` controls. """
6434 """ Get/set which item is selected in the control. In case of multiple selection, the index of the first
6435 item is returned. Applicable to ``ComboBox, ListBox`` controls. """
6436 ListSource: Union[str, Tuple[str, ...]]
6437 """ Specifies the data contained in a control as a tuple of string values.
6438 Combined with ``ListSourceType``, may also contain the name of a table, a query or a complete SQL statement.
6439 Applicable to ``ComboBox, ListBox`` controls. """
6441 """ Specifies the type of data contained in a control. It must be one of
6442 the ``com.sun.star.form.ListSourceType.*`` constants. Applicable to ``ComboBox, ListBox`` controls. """
6444 """ Get/set if the control is read-only.. Applicable to ``ComboBox, CurrencyField, DateField, FileControl,
6445 FormattedField, ImageControl, ListBox, NumericField, PatternField, TextField, TimeField`` controls. """
6447 """ Get/set whether a user can make multiple selections in a ``listbox``. """
6449 """ The name of the control. """
6451 OnActionPerformed: SCRIPT_URI
6452 """ Get/set the macro triggered by the ``Execute action`` event. """
6453 OnAdjustmentValueChanged: SCRIPT_URI
6454 """ Get/set the macro triggered by the ``While adjusting`` event. """
6455 OnApproveAction: SCRIPT_URI
6456 """ Get/set the macro triggered by the ``Approve action`` event. """
6457 OnApproveReset: SCRIPT_URI
6458 """ Get/set the macro triggered by the ``Prior to reset`` event. """
6459 OnApproveUpdate: SCRIPT_URI
6460 """ Get/set the macro triggered by the ``WBefore updating`` event. """
6461 OnChanged: SCRIPT_URI
6462 """ Get/set the macro triggered by the ``Changed`` event. """
6463 OnErrorOccurred: SCRIPT_URI
6464 """ Get/set the macro triggered by the ``Error occurred`` event. """
6465 OnFocusGained: SCRIPT_URI
6466 """ Get/set the macro triggered by the ``When receiving focus`` event."""
6467 OnFocusLost: SCRIPT_URI
6468 """ Get/set the macro triggered by the ``When losing focus`` event."""
6469 OnItemStateChanged: SCRIPT_URI
6470 """ Get/set the macro triggered by the ``Item status changed`` event. """
6471 OnKeyPressed: SCRIPT_URI
6472 """ Get/set the macro triggered by the ``Key pressed`` event."""
6473 OnKeyReleased: SCRIPT_URI
6474 """ Get/set the macro triggered by the ``Key released`` event."""
6475 OnMouseDragged: SCRIPT_URI
6476 """ Get/set the macro triggered by the ``Mouse moved while button pressed`` event."""
6477 OnMouseEntered: SCRIPT_URI
6478 """ Get/set the macro triggered by the ``Mouse inside`` event."""
6479 OnMouseExited: SCRIPT_URI
6480 """ Get/set the macro triggered by the ``Mouse outside`` event."""
6481 OnMouseMoved: SCRIPT_URI
6482 """ Get/set the macro triggered by the ``Mouse moved`` event."""
6483 OnMousePressed: SCRIPT_URI
6484 """ Get/set the macro triggered by the ``Mouse button pressed`` event."""
6485 OnMouseReleased: SCRIPT_URI
6486 """ Get/set the macro triggered by the ``Mouse button released`` event."""
6487 OnResetted: SCRIPT_URI
6488 """ Get/set the macro triggered by the ``After resetting`` event. """
6489 OnTextChanged: SCRIPT_URI
6490 """ Get/set the macro triggered by the ``Text modified`` event. """
6491 OnUpdated: SCRIPT_URI
6492 """ Get/set the macro triggered by the ``After updating`` event. """
6494 Parent: Union[FORM, FORMCONTROL]
6495 """ Depending on the parent type, a form, a subform or a tablecontrol, returns the parent
6496 ``SFDocuments.SF_Form`` or ``SFDocuments.SF_FormControl`` class instance. """
6498 """ Get/se the file name (in ``FileSystem.FileNaming`` notation) containing a bitmap or other type of graphic
6499 to be displayed on the control. Applicable to ``Button, ImageButton, ImageControl`` controls. """
6501 """ A control is said required when the underlying data must not contain a ``NULL`` value.
6502 Applicable to ``CheckBox, ComboBox, CurrencyField, DateField, ListBox, NumericField, PatternField,
6503 RadioButton, SpinButton, TextField, TimeField`` controls."""
6505 """ Get the text being displayed by the control. Applicable to ``ComboBox, DateField, FileControl,
6506 FormattedField, PatternField, TextField, TimeField`` controls. """
6508 """ Specifies the text that appears as a tooltip when you hover the mouse pointer over the control. """
6510 """ Get/set whether the ``checkbox`` control may appear dimmed (grayed). """
6513 Get/set the content of the control:
6515 - ``Button``: bool - For toggle buttons only.
6516 - ``CheckBox``: bool, int - 0, ``False``: not checked, 1, ``True``: checked, 2: grayed, don't know.
6517 - ``ComboBox``: str - The selected value. The ``ListIndex`` property is an alternate option.
6518 - ``CurrencyField``: int, float.
6519 - ``DateField``: datetime.datetime.
6520 - ``FileControl``: FILE.
6521 - ``FormattedField``: str, int, float.
6522 - ``HiddenControl``: str,
6523 - ``ListBox``: List(str), str - Get the selected row(s) as a single string or an array of strings. Only a single value can be set.
6524 - ``NumericField``: int, float.
6525 - ``PatternField``: str.
6526 - ``RadioButton``: bool - Each button has its own name. Multiple RadioButton controls are linked together when they share the same group name. If a radiobutton is set to ``True``, the other related buttons are automatically set to ``False``.
6527 - ``ScrollBar``: int - Must be within the predefined bounds.
6528 - ``SpinButton``: int - Must be within the predefined bounds.
6529 - ``TextField``: str - The text appearing in the control.
6530 - ``TimeField``: datetime.datetime.
6531 Not applicable to ``FixedText, GroupBox, ImageButton, ImageControl, NavigationBar`` and ``TableControl``
6535 """ Get/set if the form control is hidden or visible. """
6538 """ The UNO representation (``com.sun.star.awt.XControlModel``) of the control model. """
6540 """ The UNO representation (``com.sun.star.awt.XControl``) of the control view. """
6542 def Controls(self, controlname: str = ...) -> Union[FORMCONTROL, Tuple[str, ...]]:
6544 This method is applicable only to controls of the ``TableControl`` type.
6545 The returned value depends on the arguments provided.
6547 If ``controlname`` is absent, then a tuple containing the names of all controls is returned.
6549 If ``controlname`` is provided, the method returns a ``FormControl`` class instance
6550 corresponding to the specified control.
6553 ``controlname``: a valid control name as a case-sensitive string.
6555 The list of available control names
6556 or an instance of the ``SFDocuments.SF_FormControl`` class.
6560 def SetFocus(self) -> bool:
6562 Sets the focus on the control.
6565 ``True`` if focusing was successful.
6569 # #########################################################################
6570 # SF_FormDocument CLASS
6571 # #########################################################################
6572 class SF_FormDocument(SF_Document, SFServices):
6574 The ``FormDocument`` service allows to access form documents stored in ``Base`` documents.
6576 Each form document may be composed of one or more forms, including the main form and other sub-forms.
6578 This service inherits methods and properties from the ``Document`` service and is often used alongside
6579 the ``Base`` and ``Database`` services.
6582 def CloseDocument(self) -> bool:
6584 Close the form document and dispose the actual instance.
6587 ``True`` if closure is successful.
6591 def Forms(self, form: Union[int, str] = ...) -> Union[FORM, Tuple[str, ...]]:
6593 Depending on the parameters provided this method will return:
6595 - A tuple with the names of all the forms contained in the form document (if the form argument is absent)
6596 - A ``SFDocuments.Form`` service instance representing the form specified as argument.
6599 ``form``: the name or index corresponding to a form stored in the form document.
6600 If this argument is absent, the method will return a list with the names of all available forms.
6604 def GetDatabase(self, user: str = ..., password: str = ...) -> Optional[DATABASE]:
6606 Returns a Database service instance (service = ``SFDatabases.Database``) giving access
6607 to the execution of SQL commands on the database linked with the actual form document.
6609 ``user``, ``password``: the login parameters.
6616 printbackground: bool = ...,
6617 printblankpages: bool = ...,
6618 printevenpages: bool = ...,
6619 printoddpages: bool = ...,
6620 printimages: bool = ...,
6623 Send the content of the document to the printer.
6625 The printer might be defined previously by default, by the user or by the SetPrinter() method.
6628 ``pages``: the pages to print as a string, like in the user interface.
6629 Example: "1-4;10;15-18". Defaults to all pages.
6631 ``copies``: the number of copies to print. Defaults to 1.
6633 ``printbackground``: print the background image when ``True`` (default).
6635 ``printblankpages``: when ``False`` (default), omit empty pages.
6637 ``printevenpages``: print the left pages when ``True`` (default).
6639 ``printoddpages``: print the right pages when ``True`` (default).
6641 ``printimages``: print the graphic objects when ``True`` (default).
6643 ``True`` when successful.
6647 # #########################################################################
6649 # #########################################################################
6650 class SF_Writer(SF_Document, SFServices):
6652 Many methods are generic for all types of documents and are inherited from the ``SF_Document``
6653 module, whereas other methods that are specific for ``Writer`` documents are defined
6654 in the ``SF_Writer`` module.
6657 def Forms(self, form: Union[int, str] = ...) -> Union[FORM, Tuple[str, ...]]:
6659 Depending on the parameters provided this method will return:
6661 - A tuple with the names of all the forms contained in the writer document (if the form argument is absent)
6662 - A ``SFDocuments.Form`` service instance representing the form specified as argument.
6665 ``form``: the name or index corresponding to a form stored in the form document.
6666 If this argument is absent, the method will return a list with the names of all available forms.
6670 def ImportStylesFromFile(self,
6672 families: Union[str, Sequence[str]] = ...,
6673 overwrite: bool = ...
6676 This method loads all the styles belonging to one or more style families from a closed
6677 file into the actual ``Writer`` document.
6679 Are always imported together:
6680 - ``ParagraphStyles`` and ``CharacterStyles``
6681 - ``NumberingStyles`` and ``ListStyles``
6684 ``filename``: the file from which to load the styles in the ``SFScriptForge.FileSystem``
6685 notation. The file is presumed to be a ``Writer`` document.
6687 ``families``: one of the style families present in the actual document,
6688 as a case-sensitive string or a tuple of such strings.
6689 Leave this argument blank to import all families.
6691 ``overwrite``: when ``True``, the actual styles may be overwritten. Default is ``False``.
6693 ``True`` if styles were successfully imported.
6701 printbackground: bool = ...,
6702 printblankpages: bool = ...,
6703 printevenpages: bool = ...,
6704 printoddpages: bool = ...,
6705 printimages: bool = ...,
6708 Send the content of the document to the printer.
6710 The printer might be defined previously by default, by the user or by the SetPrinter() method.
6713 ``pages``: the pages to print as a string, like in the user interface.
6714 Example: "1-4;10;15-18". Defaults to all pages.
6716 ``copies``: the number of copies to print. Defaults to 1.
6718 ``printbackground``: print the background image when ``True`` (default).
6720 ``printblankpages``: when ``False`` (default), omit empty pages.
6722 ``printevenpages``: print the left pages when ``True`` (default).
6724 ``printoddpages``: print the right pages when ``True`` (default).
6726 ``printimages``: print the graphic objects when ``True`` (default).
6728 ``True`` when successful.
6734 The SFWidgets class manages toolbars, menus and popup menus.
6737 # #########################################################################
6739 # #########################################################################
6740 class SF_Menu(SFServices):
6742 Display a menu in the menubar of a document or a form document.
6743 After use, the menu will not be saved neither in the application settings, nor in the document.
6745 The menu will be displayed, as usual, when its header in the menubar is clicked.
6746 When one of its items is selected, there are 3 alternative options:
6747 - a UNO command (like ".uno:About") is triggered
6748 - a user script is run receiving a standard argument defined in this service
6749 - one of above combined with a toggle of the status of the item
6751 The menu is described from top to bottom. Each menu item receives a numeric and a string identifier.
6753 The ``SF_Menu`` service provides the following capabilities:
6754 - Creation of menus with custom entries, checkboxes, radio buttons and separators.
6755 - Decoration of menu items with icons and tooltips.
6756 Menu entries associated with a script receive a comma-separated string argument with the following values:
6757 - The toplevel name of the menu.
6758 - The string ID of the selected menu entry.
6759 - The numeric ID of the selected menu entry.
6760 - The current state of the menu item. This is useful for checkboxes and radio buttons. If the item is checked, the value "1" is returned, otherwise "0" is returned.
6763 ShortcutCharacter: str
6764 """ Character used to define the access key of a menu item. The default character is "~" (tilde). """
6765 SubmenuCharacter: str
6766 """ Character or string that defines how menu items are nested. The default character is ">".
6769 ``oMenu.AddItem("Item A")``
6771 ``oMenu.AddItem("Item B>Item B.1")``
6773 ``oMenu.AddItem("Item B>Item B.2")``
6775 ``oMenu.AddItem("---")``
6777 ``oMenu.AddItem("Item C>Item C.1>Item C.1.1")``
6779 ``oMenu.AddItem("Item C>Item C.1>Item C.1.2")``
6781 ``oMenu.AddItem("Item C>Item C.2>Item C.2.1")``
6783 ``oMenu.AddItem("Item C>Item C.2>Item C.2.2")``
6785 ``oMenu.AddItem("Item C>Item C.2>---")``
6787 ``oMenu.AddItem("Item C>Item C.2>Item C.2.3")``
6789 ``oMenu.AddItem("Item C>Item C.2>Item C.2.4")``
6792 def AddCheckBox(self,
6799 script: SCRIPT_URI = ...,
6802 Inserts a checkbox in the menu.
6804 ``menuitem``: defines the text to be displayed in the menu.
6805 This argument also defines the hierarchy of the item inside the menu by using the submenu
6808 ``name``: the string value used to identify the menu item.
6809 By default, the last component of the menu hierarchy is used.
6811 ``status``: defines whether the item is selected when the menu is created. Defaults to ``False``.
6813 ``icon``: the relative path and name of the icon to be displayed versus the folder structure
6814 found in the ZIP files located in the ``$INSTALLDIR/share/config`` directory.
6815 The actual icon shown depends on the icon set being used.
6817 ``tooltip``: text to be displayed as tooltip.
6819 ``command``: the name of a UNO command without the .uno: prefix. If the command name
6820 does not exist, nothing will happen when the item is clicked.
6822 ``script``: the URI for a Basic or Python script that will be executed when the item is clicked.
6824 The ``command`` and ``script`` arguments are mutually exclusive.
6826 A numeric value that uniquely identifies the inserted item.
6836 script: SCRIPT_URI = ...,
6839 Inserts a label entry in the menu.
6841 ``menuitem``: defines the text to be displayed in the menu.
6842 This argument also defines the hierarchy of the item inside the menu by using the submenu
6845 ``name``: the string value used to identify the menu item.
6846 By default, the last component of the menu hierarchy is used.
6848 ``icon``: the relative path and name of the icon to be displayed versus the folder structure
6849 found in the ZIP files located in the ``$INSTALLDIR/share/config`` directory.
6850 The actual icon shown depends on the icon set being used.
6852 ``tooltip``: text to be displayed as tooltip.
6854 ``command``: the name of a UNO command without the .uno: prefix. If the command name
6855 does not exist, nothing will happen when the item is clicked.
6857 ``script``: the URI for a Basic or Python script that will be executed when the item is clicked.
6859 The ``command`` and ``script`` arguments are mutually exclusive.
6861 A numeric value that uniquely identifies the inserted item.
6865 def AddRadioButton(self,
6872 script: SCRIPT_URI = ...,
6875 Inserts a radio button in the menu.
6877 ``menuitem``: defines the text to be displayed in the menu.
6878 This argument also defines the hierarchy of the item inside the menu by using the submenu
6881 ``name``: the string value used to identify the menu item.
6882 By default, the last component of the menu hierarchy is used.
6884 ``status``: defines whether the item is selected when the menu is created. Defaults to ``False``.
6886 ``icon``: the relative path and name of the icon to be displayed versus the folder structure
6887 found in the ZIP files located in the ``$INSTALLDIR/share/config`` directory.
6888 The actual icon shown depends on the icon set being used.
6890 ``tooltip``: text to be displayed as tooltip.
6892 ``command``: the name of a UNO command without the .uno: prefix. If the command name
6893 does not exist, nothing will happen when the item is clicked.
6895 ``script``: the URI for a Basic or Python script that will be executed when the item is clicked.
6897 The ``command`` and ``script`` arguments are mutually exclusive.
6899 A numeric value that uniquely identifies the inserted item.
6903 # #########################################################################
6904 # SF_ContextMenu CLASS
6905 # #########################################################################
6906 class SF_ContextMenu(SFServices):
6908 Complete a predefined context menu with new items.
6910 A context menu is obtained by a right-click on several areas of a document.
6911 Each area determines its own context menu.
6912 (Consider right-clicking on a cell or on a sheet tab in a Calc document).
6913 Each component model has its own set of context menus.
6915 A context menu is usually predefined at LibreOffice installation.
6916 Customization is done statically with the Tools + Customize dialog.
6917 The actual service provides a mean to make temporary additions at
6918 the bottom of a context menu in an active document. Those changes are lost when the document is closed.
6920 The name of a context menu is the last component of the resource URL:
6921 "private:resource/popupmenu/the-name-here"
6923 Context menu items are either usual items or line separators. Checkboxes or radio buttons are not supported.
6926 ShortcutCharacter: str
6927 """ Character used to define the access key of a menu item. The default character is "~" (tilde). """
6928 SubmenuCharacter: str
6929 """ Character or string that defines how menu items are nested. The default character is ">".
6932 ``oMenu.AddItem("Item A")``
6934 ``oMenu.AddItem("Item B>Item B.1")``
6936 ``oMenu.AddItem("Item B>Item B.2")``
6938 ``oMenu.AddItem("---")``
6940 ``oMenu.AddItem("Item C>Item C.1>Item C.1.1")``
6942 ``oMenu.AddItem("Item C>Item C.1>Item C.1.2")``
6944 ``oMenu.AddItem("Item C>Item C.2>Item C.2.1")``
6946 ``oMenu.AddItem("Item C>Item C.2>Item C.2.2")``
6948 ``oMenu.AddItem("Item C>Item C.2>---")``
6950 ``oMenu.AddItem("Item C>Item C.2>Item C.2.3")``
6952 ``oMenu.AddItem("Item C>Item C.2>Item C.2.4")``
6955 def Activate(self, enable: bool = ...) -> None:
6957 Make the added items of the context menu available for execution, or, at the opposite,
6958 disable them, depending on the argument.
6960 ``enable``: when ``True`` (default), the new items of the context menu are made visible.
6961 When ``False``, they are suppressed.
6973 Inserts a labeled entry or a line separator in the menu.
6975 ``menuitem``: defines the text to be displayed in the menu.
6976 This argument also defines the hierarchy of the item inside the menu by using the submenu
6977 character. If the last component is equal to "---", a line separator is inserted
6978 and all other arguments are ignored.
6980 ``command``: a menu command like ".uno:About". The validity of the command is not checked.
6982 ``script``: a Basic or Python script (determined by its URI notation) to be run when
6983 the item is clicked.
6984 Read https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework#Scripting_Framework_URI_Specification
6985 No argument will be passed to the called script.
6987 Arguments ``Command`` and ``Script`` are mutually exclusive.
6993 # #########################################################################
6994 # SF_PopupMenu CLASS
6995 # #########################################################################
6996 class SF_PopupMenu(SFServices):
6998 Display a popup menu anywhere and any time.
6999 A popup menu is usually triggered by a mouse action (typically a right-click) on a dialog, a form
7000 or one of their controls. In this case the menu will be displayed below the clicked area.
7002 When triggered by other events, including in the normal flow of a user script, the script should
7003 provide the coordinates of the top-left edge of the menu versus the actual component.
7005 The menu is described from top to bottom. Each menu item receives a numeric and a string identifier.
7006 The ``Execute()`` method returns the item selected by the user.
7008 The ``SF_PopupMenu`` service provides the following capabilities:
7009 - Creation of menus with custom entries, checkboxes, radio buttons and separators.
7010 - Decoration of menu items with icons and tooltips.
7013 ShortcutCharacter: str
7014 """ Character used to define the access key of a menu item. The default character is "~" (tilde). """
7015 SubmenuCharacter: str
7016 """ Character or string that defines how menu items are nested. The default character is ">".
7019 ``oMenu.AddItem("Item A")``
7021 ``oMenu.AddItem("Item B>Item B.1")``
7023 ``oMenu.AddItem("Item B>Item B.2")``
7025 ``oMenu.AddItem("---")``
7027 ``oMenu.AddItem("Item C>Item C.1>Item C.1.1")``
7029 ``oMenu.AddItem("Item C>Item C.1>Item C.1.2")``
7031 ``oMenu.AddItem("Item C>Item C.2>Item C.2.1")``
7033 ``oMenu.AddItem("Item C>Item C.2>Item C.2.2")``
7035 ``oMenu.AddItem("Item C>Item C.2>---")``
7037 ``oMenu.AddItem("Item C>Item C.2>Item C.2.3")``
7039 ``oMenu.AddItem("Item C>Item C.2>Item C.2.4")``
7042 def AddCheckBox(self,
7050 Inserts a checkbox in the menu.
7052 ``menuitem``: defines the text to be displayed in the menu.
7053 This argument also defines the hierarchy of the item inside the menu by using the submenu
7056 ``name``: the string value used to identify the menu item.
7057 By default, the last component of the menu hierarchy is used.
7059 ``status``: defines whether the item is selected when the menu is created. Defaults to ``False``.
7061 ``icon``: the relative path and name of the icon to be displayed versus the folder structure
7062 found in the ZIP files located in the ``$INSTALLDIR/share/config`` directory.
7063 The actual icon shown depends on the icon set being used.
7065 ``tooltip``: text to be displayed as tooltip.
7067 A numeric value that uniquely identifies the inserted item.
7078 Inserts a labeled entry or a line separator in the menu.
7080 ``menuitem``: defines the text to be displayed in the menu.
7081 This argument also defines the hierarchy of the item inside the menu by using the submenu
7082 character. If the last component is equal to "---", a line separator is inserted
7083 and all other arguments are ignored.
7085 ``name``: the string value used to identify the menu item.
7086 By default, the last component of the menu hierarchy is used.
7088 ``icon``: the relative path and name of the icon to be displayed versus the folder structure
7089 found in the ZIP files located in the ``$INSTALLDIR/share/config`` directory.
7090 The actual icon shown depends on the icon set being used.
7092 ``tooltip``: text to be displayed as tooltip.
7094 A numeric value that uniquely identifies the inserted item.
7098 def AddRadioButton(self,
7106 Inserts a radio button in the menu.
7108 ``menuitem``: defines the text to be displayed in the menu.
7109 This argument also defines the hierarchy of the item inside the menu by using the submenu
7112 ``name``: the string value used to identify the menu item.
7113 By default, the last component of the menu hierarchy is used.
7115 ``status``: defines whether the item is selected when the menu is created. Defaults to ``False``.
7117 ``icon``: the relative path and name of the icon to be displayed versus the folder structure
7118 found in the ZIP files located in the ``$INSTALLDIR/share/config`` directory.
7119 The actual icon shown depends on the icon set being used.
7121 ``tooltip``: text to be displayed as tooltip.
7123 A numeric value that uniquely identifies the inserted item.
7127 def Execute(self, returnid: bool = ...) -> Union[int, str]:
7129 Displays the popup menu and waits for a user action.
7131 ``returnid``: if ``True`` (default), the numeric identifier of the selected item is returned.
7132 If ``False``, the method returns the item's name.
7134 The item clicked by the user.
7135 If the user clicks outside the popup menu or presses the ``Esc`` key, then no item is selected.
7136 In such cases, the returned value is either ``0`` (zero) or the empty string, depending
7137 on the ``returnid`` argument.
7141 # #########################################################################
7143 # #########################################################################
7144 class SF_Toolbar(SFServices):
7146 Each component has its own set of toolbars, depending on the component type
7147 (Calc, Writer, Basic IDE, ...).
7149 In the context of the actual class, a toolbar is presumed defined statically:
7150 - either bat LibreOffice installation,
7151 - or by a customization done by the user at application or at document levels.
7153 The ``Toolbar`` service allows to retrieve information related to the toolbars available for
7154 a specific document window.
7156 With this service it is possible to:
7157 - toggle the visibility of specific toolbars.
7158 - access to information about the buttons available in each toolbar.
7160 This service handles both built-in and custom toolbars.
7164 """ Returns ``True`` when the toolbar is part of the set of standard toolbars shipped with LibreOffice. """
7166 """ Returns ``True`` when the toolbar is active in the window and docked. """
7167 HasGlobalScope: bool
7168 """ Returns ``True`` when the toolbar is available in all documents of the same type. """
7170 """ Returns the name of the toolbar. """
7172 """ Returns the resource URL of the toolbar, in the form ``"private:toolbar/toolbar_name"``. """
7174 """ Get/set whether the toolbar is active and visible in the document window. """
7176 """ Returns the ``com.sun.star.ui.XUIElement`` UNO object that represents the toolbar. """
7178 def ToolbarButtons(self, buttonname: str = ...) -> Union[TOOLBARBUTTON, Tuple[str]]:
7180 Returns either a list of the available toolbar button names in the actual toolbar
7181 or a ``ToolbarButton`` object instance.
7183 ``buttonname``: the usual name of one of the available buttons in the actual toolbar.
7184 The button name is the localized button name defined in the ``Tools - Customize - Toolbars``
7187 A tuple of button names when the argument is absent,
7188 or a new ``SF_ToolbarButton`` object instance otherwise.
7192 # #########################################################################
7194 # #########################################################################
7195 class SF_ToolbarButton(SFServices):
7197 A toolbar consists in a series of graphical controls to trigger actions.
7198 The ``Toolbar`` service gives access to the ``ToolbarButton`` service to manage
7199 the individual buttons belonging to the toolbar.
7201 With this service it is possible to:
7202 - know the characteristics of the button
7203 - toggle the visibility of the button.
7204 - execute the command associated with the toolbar button.
7208 """ Returns the name of the button. """
7210 """ Returns the height of the button, in pixels. """
7212 """ Returns the index of the button in its parent toolbar. """
7214 """ Get/set the UNO command or the script executed when the button is pressed. """
7216 """ Returns a ``Toolbar`` service instance corresponding to the parent toolbar of the current
7219 """ Get/set the tooltip text shown when the user hovers the toolbar button. """
7221 """ Get/set whether the toolbar button is visible or not. """
7223 """ Returns the width of the button, in pixels. """
7225 """ Returns the X (horizontal) coordinate of the top-left corner of the button, in pixels. """
7227 """ Returns the Y (vertical) coordinate of the top-left corner of the button, in pixels. """
7229 def Execute(self) -> Optional[Any]:
7231 Execute the command stored in the toolbar button.
7232 The command can be a UNO command or a Basic/Python script (expressed in the
7233 ``scripting framework_URI`` notation).
7235 The output of the script or None
7240 # #############################################################################
7241 # CreateScriptService signatures
7242 # #############################################################################
7244 def CreateScriptService(service: Literal['servicename', 'Servicename', 'Library.Servicename'], *args: Any
7245 ) -> Optional[SERVICE]:
7247 The modules and classes implemented in the ScriptForge libraries are invoked
7248 from user scripts as "Services". A generic constructor of those services has been designed for that purpose.
7251 ``service``: the name of the service as a string 'library.service' or one of its synonyms.
7253 The service names created with ``CreateScriptService()`` are:
7254 - ``Array``, ``Basic``, ``Dictionary``, ``Exception``, ``FileSystem``, ``L10N``, ``Platform``, ``Region``, ``Session``, ``String``, ``Timer``, ``UI``
7256 - ``Dialog``, ``NewDialog``, ``DialogEvent``
7257 - ``Document``, ``Base``, ``Calc``, ``Writer``
7260 ``args``: the optional arguments to pass to the service constructor.
7262 (positional): a Python dictionary. Default = ``None``.
7264 ``start``: when ``True``, the timer starts immediately. Default = ``False``.
7266 ``filename``: the name of the ``Base`` file containing the database. Must be expressed
7267 using the ``SF_FileSystem.FileNaming`` notation.
7269 ``registrationname``: the name of a registered database.
7270 If ``filename`` is provided, this argument is ignored.
7272 ``readonly``: determines if the database will be opened as readonly. Defaults to ``True``.
7274 ``user``, ``password``: additional connection parameters.
7276 ``container``: ``"GlobalScope"`` for preinstalled libraries or a window name.
7277 Defaults to the current document.
7279 ``library``: the case-sensitive name of a library contained in the container.
7280 Default value is ``"Standard"``.
7282 ``dialogname``: a case-sensitive string designating the dialog.
7284 ``dialogname``: an identifier for the dialog to be built from scratch.
7286 ``place``: the size and position expressed in "``APPFONT units``". Either:
7287 - a tuple (X, Y, Width, Height).
7288 - a ``com.sun.star.awt.Rectangle`` structure.
7290 (positional): the event object passed by ``LibreOffice`` to the event-handling routine.
7291 ``Document``, ``Base``, ``Calc``, ``Writer``
7292 ``windowname``: see definitions at ``SF_UI`` class level.
7294 ``event``: the mouse event object passed by ``LibreOffice`` to the event-handling routine.
7296 ``x``, ``y``: the screen coordinates where the menu will be displayed.
7298 ``submenuchar``: character or string that defines how menu items are nested.
7299 The default character is ``">"``.
7301 The service as a Python class instance.
7305 def CreateScriptService(service: Literal['array', 'Array', 'ScriptForge.Array']) -> ARRAY: ...
7307 def CreateScriptService(service: Literal['basic', 'Basic', 'ScriptForge.Basic']) -> BASIC: ...
7309 def CreateScriptService(service: Literal['dictionary', 'Dictionary', 'ScriptForge.Dictionary'],
7310 dic: Optional[Dict] = None) -> Optional[DICTIONARY]: ...
7312 def CreateScriptService(service: Literal['exception', 'Exception', 'ScriptForge.Exception']) -> EXCEPTION: ...
7314 def CreateScriptService(service: Literal['filesystem', 'FileSystem', 'ScriptForge.FileSystem']) -> FILESYSTEM: ...
7316 def CreateScriptService(service: Literal['l10n', 'L10N', 'ScriptForge.L10N'], foldername: str = '',
7317 locale: str = '', encoding: str = '', locale2: str = '', encoding2: str = '') -> Optional[L10N]: ...
7319 def CreateScriptService(service: Literal['platform', 'Platform', 'ScriptForge.Platform']) -> PLATFORM: ...
7321 def CreateScriptService(service: Literal['region', 'Region', 'ScriptForge.Region']) -> Optional[REGION]: ...
7323 def CreateScriptService(service: Literal['session', 'Session', 'ScriptForge.Session']) -> SESSION: ...
7325 def CreateScriptService(service: Literal['string', 'String', 'ScriptForge.String']) -> STRING: ...
7327 def CreateScriptService(service: Literal['timer', 'Timer', 'ScriptForge.Timer'], start: bool = False
7328 ) -> Optional[TIMER]: ...
7330 def CreateScriptService(service: Literal['ui', 'UI', 'ScriptForge.UI']) -> UI: ...
7332 def CreateScriptService(service: Literal['database', 'Database', 'SFDatabases.Database'], filename: str = '',
7333 registrationname: str = '', readonly: bool = True, user: str = '', password: str = ''
7334 ) -> Optional[DATABASE]: ...
7336 def CreateScriptService(service: Literal['dialog', 'Dialog', 'SFDialogs.Dialog'], container: str = '',
7337 library: str = 'Standard', dialogname: str = '') -> Optional[DIALOG]: ...
7339 def CreateScriptService(service: Literal['newdialog', 'NewDialog', 'SFDialogs.NewDialog'], dialogname: str,
7340 place: Tuple[int, int, int, int]) -> Optional[DIALOG]: ...
7342 def CreateScriptService(service: Literal['dialogevent', 'DialogEvent', 'SFDialogs.DialogEvent'],
7343 event: Optional[UNO] = None) -> Optional[Union[DIALOG, DIALOGCONTROL]]: ...
7345 def CreateScriptService(service: Literal['document', 'Document', 'SFDocuments.Document'],
7346 windowname: Union[UNO, str] = '') -> Optional[DOCUMENT]: ...
7348 def CreateScriptService(service: Literal['base', 'Base', 'SFDocuments.Base'], windowname: Union[UNO, str] = ''
7349 ) -> Optional[BASE]: ...
7351 def CreateScriptService(service: Literal['calc', 'Calc', 'SFDocuments.Calc'], windowname: Union[UNO, str] = ''
7352 ) -> Optional[CALC]: ...
7354 def CreateScriptService(service: Literal['writer', 'Writer', 'SFDocuments.Writer'], windowname: Union[UNO, str] = ''
7355 ) -> Optional[WRITER]: ...
7357 def CreateScriptService(service: Literal['popupmenu', 'PopupMenu', 'SFWidgets.PopupMenu'], event: Optional[UNO] = None,
7358 x: int = 0, y: int = 0, submenuchar:str = '') -> Optional[POPUPMENU]: ...
7360 createScriptService, createscriptservice = CreateScriptService, CreateScriptService