1 <?xml version=
"1.0" encoding=
"UTF-8"?>
2 <!DOCTYPE script:module PUBLIC
"-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
3 <script:module xmlns:
script=
"http://openoffice.org/2000/script" script:
name=
"SF_Session" script:
language=
"StarBasic" script:
moduleType=
"normal">REM =======================================================================================================================
4 REM === The ScriptForge library and its associated libraries are part of the LibreOffice project. ===
5 REM === Full documentation is available on https://help.libreoffice.org/ ===
6 REM =======================================================================================================================
11 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
12 ''' SF_Session
13 ''' ==========
14 ''' Singleton class implementing the
"ScriptForge.Session
" service
15 ''' Implemented as a usual Basic module
17 ''' Gathers diverse general-purpose properties and methods about :
18 ''' - installation/execution environment
19 ''' - UNO introspection utilities
20 ''' - clipboard management
21 ''' - invocation of external scripts or programs
23 ''' Service invocation example:
24 ''' Dim session As Variant
25 ''' session = CreateScriptService(
"Session
")
27 ''' Detailed user documentation:
28 ''' https://help.libreoffice.org/latest/en-US/text/sbasic/shared/
03/sf_session.html?DbPAR=BASIC
29 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
31 REM ================================================================== EXCEPTIONS
33 Const CALCFUNCERROR =
"CALCFUNCERROR
" ' Calc function execution failed
34 Const NOSCRIPTERROR =
"NOSCRIPTERROR
" ' Script could not be located
35 Const SCRIPTEXECERROR =
"SCRIPTEXECERROR
" ' Exception during script execution
36 Const WRONGEMAILERROR =
"WRONGEMAILERROR
" ' Wrong email address
37 Const SENDMAILERROR =
"SENDMAILERROR
" ' Mail could not be sent
38 Const UNKNOWNFILEERROR =
"UNKNOWNFILEERROR
" ' Source file does not exist
40 REM ============================================================ MODULE CONSTANTS
42 ''' Script locations
43 ''' ================
44 ''' Use next constants as Scope argument when invoking next methods:
45 ''' ExecuteBasicScript()
46 ''' ExecutePythonScript()
47 ''' Example:
48 ''' session.ExecuteBasicScript(session.SCRIPTISEMBEDDED,
"Standard.myModule.myFunc
", etc)
50 Const cstSCRIPTISEMBEDDED =
"document
" ' a library of the document (BASIC + PYTHON)
51 Const cstSCRIPTISAPPLICATION =
"application
" ' a shared library (BASIC)
52 Const cstSCRIPTISPERSONAL =
"user
" ' a library of My Macros (PYTHON)
53 Const cstSCRIPTISPERSOXT =
"user:uno_packages
" ' an extension for the current user (PYTHON)
54 Const cstSCRIPTISSHARED =
"share
" ' a library of LibreOffice Macros (PYTHON)
55 Const cstSCRIPTISSHAROXT =
"share:uno_packages
" ' an extension for all users (PYTHON)
56 Const cstSCRIPTISOXT =
"uno_packages
" ' an extension but install params are unknown (PYTHON)
58 ''' To build or to parse scripting framework URI
's
59 Const cstScript1 =
"vnd.sun.star.script:
"
60 Const cstScript2 =
"?language=
"
61 Const cstScript3 =
"&location=
"
63 REM ===================================================== CONSTRUCTOR/DESTRUCTOR
65 REM -----------------------------------------------------------------------------
66 Public Function Dispose() As Variant
68 End Function
' ScriptForge.SF_Array Explicit destructor
70 REM ================================================================== PROPERTIES
72 REM -----------------------------------------------------------------------------
73 Property Get ObjectType As String
74 ''' Only to enable object representation
75 ObjectType =
"SF_Session
"
76 End Property
' ScriptForge.SF_Session.ObjectType
78 REM -----------------------------------------------------------------------------
79 Property Get ServiceName As String
80 ''' Internal use
81 ServiceName =
"ScriptForge.Session
"
82 End Property
' ScriptForge.SF_Array.ServiceName
84 REM -----------------------------------------------------------------------------
85 Property Get SCRIPTISAPPLICATION As String
86 ''' Convenient constants
87 SCRIPTISAPPLICATION = cstSCRIPTISAPPLICATION
88 End Property
' ScriptForge.SF_Session.SCRIPTISAPPLICATION
90 REM -----------------------------------------------------------------------------
91 Property Get SCRIPTISEMBEDDED As String
92 ''' Convenient constants
93 SCRIPTISEMBEDDED = cstSCRIPTISEMBEDDED
94 End Property
' ScriptForge.SF_Session.SCRIPTISEMBEDDED
96 REM -----------------------------------------------------------------------------
97 Property Get SCRIPTISOXT As String
98 ''' Convenient constants
99 SCRIPTISOXT = cstSCRIPTISOXT
100 End Property
' ScriptForge.SF_Session.SCRIPTISOXT
102 REM -----------------------------------------------------------------------------
103 Property Get SCRIPTISPERSONAL As String
104 ''' Convenient constants
105 SCRIPTISPERSONAL = cstSCRIPTISPERSONAL
106 End Property
' ScriptForge.SF_Session.SCRIPTISPERSONAL
108 REM -----------------------------------------------------------------------------
109 Property Get SCRIPTISPERSOXT As String
110 ''' Convenient constants
111 SCRIPTISPERSOXT = cstSCRIPTISPERSOXT
112 End Property
' ScriptForge.SF_Session.SCRIPTISPERSOXT
114 REM -----------------------------------------------------------------------------
115 Property Get SCRIPTISSHARED As String
116 ''' Convenient constants
117 SCRIPTISSHARED = cstSCRIPTISSHARED
118 End Property
' ScriptForge.SF_Session.SCRIPTISSHARED
120 REM -----------------------------------------------------------------------------
121 Property Get SCRIPTISSHAROXT As String
122 ''' Convenient constants
123 SCRIPTISSHAROXT = cstSCRIPTISSHAROXT
124 End Property
' ScriptForge.SF_Session.SCRIPTISSHAROXT
126 REM ============================================================== PUBLIC METHODS
128 REM -----------------------------------------------------------------------------
129 Public Function ExecuteBasicScript(Optional ByVal Scope As Variant _
130 , Optional ByVal Script As Variant _
131 , ParamArray pvArgs As Variant _
133 ''' Execute the Basic script given as a string and return the value returned by the script
134 ''' Args:
135 ''' Scope:
"Application
" (default) or
"Document
" (NOT case-sensitive)
136 ''' (or use one of the SCRIPTIS... public constants above)
137 ''' Script: library.module.method (Case sensitive)
138 ''' library =
> The library may be not loaded yet
139 ''' module =
> Must not be a class module
140 ''' method =
> Sub or Function
141 ''' Read https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework#Scripting_Framework_URI_Specification
142 ''' pvArgs: the arguments of the called script
143 ''' Returns:
144 ''' The value returned by the call to the script
145 ''' Exceptions:
146 ''' NOSCRIPTERROR The script could not be found
147 ''' Examples:
148 ''' session.ExecuteBasicScript(,
"XrayTool._Main.Xray
", someuno)
' Sub: no return expected
150 Dim oScript As Object
' Script to be invoked
151 Dim vReturn As Variant
' Returned value
153 Const cstThisSub =
"Session.ExecuteBasicScript
"
154 Const cstSubArgs =
"[Scope], Script, arg0[, arg1] ...
"
156 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
161 If IsMissing(Scope) Or IsEmpty(Scope) Then Scope = SCRIPTISAPPLICATION
162 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
163 If Not SF_Utils._Validate(Scope,
"Scope
", V_STRING _
164 , Array(SCRIPTISAPPLICATION, SCRIPTISEMBEDDED)) Then GoTo Finally
165 If Not SF_Utils._Validate(Script,
"Script
", V_STRING) Then GoTo Finally
169 ' Execute script
170 Set oScript = SF_Session._GetScript(
"Basic
", Scope, Script)
171 On Local Error GoTo CatchExec
172 If Not IsNull(oScript) Then vReturn = oScript.Invoke(pvArgs, Array(), Array())
175 ExecuteBasicScript = vReturn
176 SF_Utils._ExitFunction(cstThisSub)
181 SF_Exception.RaiseFatal(SCRIPTEXECERROR,
"Script
", Script, Error$)
183 End Function
' ScriptForge.SF_Session.ExecuteBasicScript
185 REM -----------------------------------------------------------------------------
186 Public Function ExecuteCalcFunction(Optional ByVal CalcFunction As Variant _
187 , ParamArray pvArgs As Variant _
189 ''' Execute a Calc function by its (english) name and based on the given arguments
190 ''' Args:
191 ''' CalcFunction: the english name of the function to execute
192 ''' pvArgs: the arguments of the called function
193 ''' Each argument must be either
194 ''' - a string, a numeric value, a date or a boolean
195 ''' - a
1D array, a
2D array or an array of arrays combining those types
196 ''' - a com.sun.star.table.XCellRange UNO object
197 ''' Returns:
198 ''' The (string or numeric) value or the array of arrays returned by the call to the function
199 ''' When the arguments contain arrays, the function is executed as an array function
200 ''' Wrong arguments generate an error
201 ''' Exceptions:
202 ''' CALCFUNCERROR
' Execution error in calc function
203 ''' Examples:
204 ''' session.ExecuteCalcFunction(
"AVERAGE
",
1,
5,
3,
7) returns
4
205 ''' session.ExecuteCalcFunction(
"ABS
", Array(Array(-
1,
2,
3),Array(
4,-
5,
6),Array(
7,
8,-
9)))(
2)(
2) returns
9
206 ''' session.ExecuteCalcFunction(
"LN
", -
3) generates an error
208 Dim oCalc As Object
' Give access to the com.sun.star.sheet.FunctionAccess service
209 Dim vReturn As Variant
' Returned value
211 Const cstThisSub =
"Session.ExecuteCalcFunction
"
212 Const cstSubArgs =
"CalcFunction, arg0[, arg1] ...
"
214 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
218 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
219 If Not SF_Utils._Validate(CalcFunction,
"CalcFunction
", V_STRING) Then GoTo Finally
223 ' Execute function
224 Set oCalc = SF_Utils._GetUNOService(
"FunctionAccess
")
225 ' Intercept calls from Python when no arguments. Example NOW()
226 If UBound(pvArgs) =
0 Then
227 If IsEmpty(pvArgs(
0)) Then pvArgs = Array()
229 ' Force suitable arguments
230 For i =
0 To UBound(pvArgs)
231 pvArgs(i) = SF_Array.ConvertToRange(pvArgs(i), Direction :=
"V
")
233 ' Error trapping and execution
234 If SF_Utils._ErrorHandling() Then On Local Error GoTo CatchCall
235 vReturn = oCalc.callFunction(UCase(CalcFunction), pvArgs())
238 ExecuteCalcFunction = vReturn
239 SF_Utils._ExitFunction(cstThisSub)
244 SF_Exception.RaiseFatal(CALCFUNCERROR, CalcFunction)
246 End Function
' ScriptForge.SF_Session.ExecuteCalcFunction
248 REM -----------------------------------------------------------------------------
249 Public Function ExecutePythonScript(Optional ByVal Scope As Variant _
250 , Optional ByVal Script As Variant _
251 , ParamArray pvArgs As Variant _
253 ''' Execute the Python script given as a string and return the value returned by the script
254 ''' Args:
255 ''' Scope: one of the SCRIPTIS... public constants above (default =
"share
")
256 ''' Script: (Case sensitive)
257 ''' "library/module.py$method
"
258 ''' or
"module.py$method
"
259 ''' or
"myExtension.oxt|myScript|module.py$method
"
260 ''' library =
> The library may be not loaded yet
261 ''' myScript =
> The directory containing the python module
262 ''' module.py =
> The python module
263 ''' method =
> The python function
264 ''' Read https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework#Scripting_Framework_URI_Specification
265 ''' pvArgs: the arguments of the called script
266 ''' Date arguments are converted to iso format. However dates in arrays are not converted
267 ''' Returns:
268 ''' The value(s) returned by the call to the script. If
>1 values, enclosed in an array
269 ''' Exceptions:
270 ''' NOSCRIPTERROR The script could not be found
271 ''' Examples:
272 ''' session.ExecutePythonScript(session.SCRIPTISSHARED,
"Capitalise.py$getNewString
",
"Abc
") returns
"abc
"
274 Dim oScript As Object
' Script to be invoked
275 Dim vArg As Variant
' Individual argument
276 Dim vReturn As Variant
' Returned value
279 Const cstThisSub =
"Session.ExecutePythonScript
"
280 Const cstSubArgs =
"[Scope], Script, arg0[, arg1] ...
"
282 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
287 If IsError(Scope) Or IsMissing(Scope) Then Scope = SCRIPTISSHARED
288 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
289 If Not SF_Utils._Validate(Scope,
"Scope
", V_STRING _
290 , Array(SCRIPTISSHARED, SCRIPTISEMBEDDED, SCRIPTISPERSONAL, SCRIPTISSHAROXT, SCRIPTISPERSOXT, SCRIPTISOXT) _
292 If Not SF_Utils._Validate(Script,
"Script
", V_STRING) Then GoTo Finally
296 ' Filter date arguments - NB: dates in arrays are not filtered
297 For i =
0 To UBound(pvArgs)
' pvArgs always zero-based
299 If VarType(vArg) = V_DATE Then pvArgs(i) = SF_Utils._CDateToIso(vArg)
302 ' Intercept alternate Python helpers file when relevant
304 If SF_String.StartsWith(Script, .PythonHelper) And Len(.PythonHelper2)
> 0 Then
305 Scope = SCRIPTISPERSONAL
306 Script = .PythonHelper2
& Mid(Script, Len(.PythonHelper) +
1)
310 Set oScript = SF_Session._GetScript(
"Python
", Scope, Script)
312 ' Execute script
313 If Not IsNull(oScript) Then
314 vReturn = oScript.Invoke(pvArgs(), Array(), Array())
315 ' Remove surrounding array when single returned value
316 If IsArray(vReturn) Then
317 If UBound(vReturn) =
0 Then vReturn = vReturn(
0)
322 ExecutePythonScript = vReturn
323 SF_Utils._ExitFunction(cstThisSub)
327 End Function
' ScriptForge.SF_Session.ExecutePythonScript
329 REM -----------------------------------------------------------------------------
330 Public Function GetPDFExportOptions() As Variant
331 ''' Return the actual values of the PDF export options
332 ''' The PDF options are described on https://wiki.openoffice.org/wiki/API/Tutorials/PDF_export
333 ''' PDF options are set at each use of the Export as ... PDF command by the user and kept
334 ''' permanently until their reset by script or by a new export
335 ''' Args:
336 ''' Returns:
337 ''' A ScriptForge dictionary instance listing the
40+ properties and their value
338 ''' Examples:
339 ''' Dim dict As Object
340 ''' Set dict = session.GetPDFExportOptions()
341 ''' MsgBox dict.Item(
"Quality
")
343 Dim vDict As Variant
' Returned value
344 Dim oConfig As Object
' com.sun.star.configuration.ConfigurationProvider
345 Dim oNodePath As Object
' com.sun.star.beans.PropertyValue
346 Dim oOptions As Object
' configmgr.RootAccess
347 Dim vOptionNames As Variant
' Array of PDF options names
348 Dim vOptionValues As Variant
' Array of PDF options values
351 Const cstThisSub =
"Session.GetPDFExportOptions
"
352 Const cstSubArgs =
""
354 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
358 SF_Utils._EnterFunction(cstThisSub, cstSubArgs)
361 ' Get the (read-only) internal PDF options
362 Set oConfig = SF_Utils._GetUNOService(
"ConfigurationProvider
")
363 Set oNodePath = SF_Utils._MakePropertyValue(
"nodepath
",
"/org.openoffice.Office.Common/Filter/PDF/Export/
")
364 Set oOptions = oConfig.createInstanceWithArguments(
"com.sun.star.configuration.ConfigurationAccess
", Array(oNodePath))
366 ' Copy the options into a ScriptForge dictionary with case-sensitive comparison of keys
367 Set vDict = CreateScriptService(
"Dictionary
", True)
368 vOptionNames = oOptions.getElementNames()
369 vOptionValues = oOptions.getPropertyValues(vOptionNames)
371 For i =
0 To UBound(vOptionNames)
372 vDict.Add(vOptionNames(i), vOptionValues(i))
377 GetPDFExportOptions = vDict
378 SF_Utils._ExitFunction(cstThisSub)
382 End Function
' ScriptForge.SF_Session.GetPDFExportOptions
384 REM -----------------------------------------------------------------------------
385 Public Function GetProperty(Optional ByVal PropertyName As Variant) As Variant
386 ''' Return the actual value of the given property
387 ''' Args:
388 ''' PropertyName: the name of the property as a string
389 ''' Returns:
390 ''' The actual value of the property
391 ''' Exceptions
392 ''' ARGUMENTERROR The property does not exist
394 Const cstThisSub =
"Session.GetProperty
"
395 Const cstSubArgs =
"PropertyName
"
397 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
401 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
402 If Not SF_Utils._Validate(PropertyName,
"PropertyName
", V_STRING, Properties()) Then GoTo Catch
406 Select Case UCase(PropertyName)
411 SF_Utils._ExitFunction(cstThisSub)
415 End Function
' ScriptForge.SF_Session.GetProperty
417 REM -----------------------------------------------------------------------------
418 Public Function HasUnoMethod(Optional ByRef UnoObject As Variant _
419 , Optional ByVal MethodName As Variant _
421 ''' Returns True if a UNO object contains the given method
422 ''' Code-snippet derived from XRAY
423 ''' Args:
424 ''' UnoObject: the object to identify
425 ''' MethodName: the name of the method as a string. The search is case-sensitive
426 ''' Returns:
427 ''' False when the method is not found or when an argument is invalid
429 Dim oIntrospect As Object
' com.sun.star.beans.Introspection
430 Dim oInspect As Object
' com.sun.star.beans.XIntrospectionAccess
431 Dim bMethod As Boolean
' Return value
432 Const cstThisSub =
"Session.HasUnoMethod
"
433 Const cstSubArgs =
"UnoObject, MethodName
"
435 SF_Utils._EnterFunction(cstThisSub, cstSubArgs)
439 If VarType(UnoObject)
<> V_OBJECT Then GoTo Finally
440 If IsNull(UnoObject) Then GoTo Finally
441 If VarType(MethodName)
<> V_STRING Then GoTo Finally
442 If MethodName = Space(Len(MethodName)) Then GoTo Finally
445 On Local Error GoTo Catch
446 Set oIntrospect = SF_Utils._GetUNOService(
"Introspection
")
447 Set oInspect = oIntrospect.inspect(UnoObject)
448 bMethod = oInspect.hasMethod(MethodName, com.sun.star.beans.MethodConcept.ALL)
451 HasUnoMethod = bMethod
452 SF_Utils._ExitFunction(cstThisSub)
455 On Local Error GoTo
0
457 End Function
' ScriptForge.SF_Session.HasUnoMethod
459 REM -----------------------------------------------------------------------------
460 Public Function HasUnoProperty(Optional ByRef UnoObject As Variant _
461 , Optional ByVal PropertyName As Variant _
463 ''' Returns True if a UNO object contains the given property
464 ''' Code-snippet derived from XRAY
465 ''' Args:
466 ''' UnoObject: the object to identify
467 ''' PropertyName: the name of the property as a string. The search is case-sensitive
468 ''' Returns:
469 ''' False when the property is not found or when an argument is invalid
471 Dim oIntrospect As Object
' com.sun.star.beans.Introspection
472 Dim oInspect As Object
' com.sun.star.beans.XIntrospectionAccess
473 Dim bProperty As Boolean
' Return value
474 Const cstThisSub =
"Session.HasUnoProperty
"
475 Const cstSubArgs =
"UnoObject, PropertyName
"
477 SF_Utils._EnterFunction(cstThisSub, cstSubArgs)
481 If VarType(UnoObject)
<> V_OBJECT Then GoTo Finally
482 If IsNull(UnoObject) Then GoTo Finally
483 If VarType(PropertyName)
<> V_STRING Then GoTo Finally
484 If PropertyName = Space(Len(PropertyName)) Then GoTo Finally
487 On Local Error GoTo Catch
488 Set oIntrospect = SF_Utils._GetUNOService(
"Introspection
")
489 Set oInspect = oIntrospect.inspect(UnoObject)
490 bProperty = oInspect.hasProperty(PropertyName, com.sun.star.beans.PropertyConcept.ALL)
493 HasUnoProperty = bProperty
494 SF_Utils._ExitFunction(cstThisSub)
497 On Local Error GoTo
0
499 End Function
' ScriptForge.SF_Session.HasUnoProperty
501 REM -----------------------------------------------------------------------------
502 Public Function Methods() As Variant
503 ''' Return the list of public methods of the Session service as an array
506 "ExecuteBasicScript
" _
507 ,
"ExecuteCalcFunction
" _
508 ,
"ExecutePythonScript
" _
509 ,
"HasUnoMethod
" _
510 ,
"HasUnoProperty
" _
511 ,
"OpenURLInBrowser
" _
512 ,
"RunApplication
" _
513 ,
"SendMail
" _
514 ,
"UnoMethods
" _
515 ,
"UnoObjectType
" _
516 ,
"UnoProperties
" _
517 ,
"WebService
" _
520 End Function
' ScriptForge.SF_Session.Methods
522 REM -----------------------------------------------------------------------------
523 Public Sub OpenURLInBrowser(Optional ByVal URL As Variant)
524 ''' Opens a URL in the default browser
525 ''' Args:
526 ''' URL: The URL to open in the browser
527 ''' Examples:
528 ''' session.OpenURLInBrowser(
"https://docs.python.org/
3/library/webbrowser.html
")
530 Const cstPyHelper =
"$
" & "_SF_Session__OpenURLInBrowser
"
532 Const cstThisSub =
"Session.OpenURLInBrowser
"
533 Const cstSubArgs =
"URL
"
535 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
538 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
539 If Not SF_Utils._Validate(URL,
"URL
", V_STRING) Then GoTo Finally
543 ExecutePythonScript(SCRIPTISSHARED, _SF_.PythonHelper
& cstPyHelper, URL)
546 SF_Utils._ExitFunction(cstThisSub)
550 End Sub
' ScriptForge.SF_Session.OpenURLInBrowser
552 REM -----------------------------------------------------------------------------
553 Public Function Properties() As Variant
554 ''' Return the list or properties as an array
556 Properties = Array( _
559 End Function
' ScriptForge.SF_Session.Properties
561 REM -----------------------------------------------------------------------------
562 Public Function RunApplication(Optional ByVal Command As Variant _
563 , Optional ByVal Parameters As Variant _
565 ''' Executes an arbitrary system command
566 ''' Args:
567 ''' Command: The command to execute
568 ''' This may be an executable file or a document which is registered with an application
569 ''' so that the system knows what application to launch for that document
570 ''' Parameters: a list of space separated parameters as a single string
571 ''' The method does not validate the given parameters, but only passes them to the specified command
572 ''' Returns:
573 ''' True if success
574 ''' Exceptions:
575 ''' UNKNOWNFILEERROR Command could not be identified as a valid file
576 ''' Examples:
577 ''' session.RunApplication(
"Notepad.exe
")
578 ''' session.RunApplication(
"C:\myFolder\myDocument.odt
")
579 ''' session.RunApplication(
"kate
")
' (Linux)
580 ''' session.RunApplication(
"kate
",
"/home/me/install.txt
")
' (Linux)
582 Dim bReturn As Boolean
' Returned value
583 Dim oShell As Object
' com.sun.star.system.SystemShellExecute
584 Dim sCommand As String
' Command as an URL
585 Const cstThisSub =
"Session.RunApplication
"
586 Const cstSubArgs =
"Command, [Parameters]
"
588 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
592 If IsMissing(Parameters) Then Parameters =
""
593 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
594 If Not SF_Utils._ValidateFile(Command,
"Command
") Then GoTo Finally
595 If Not SF_Utils._Validate(Parameters,
"Parameters
", V_STRING) Then GoTo Finally
599 ' Cfr. discussion tdf#
160222
600 ' 1) Try Shell(), always in not synchronized mode
601 ' 2) If failure - check command existence as a valid file
602 ' - try com.sun.star.system.SystemShellExecute
603 sCommand = SF_FileSystem._ConvertFromUrl(Command)
604 On Local Error GoTo Step2
605 Shell(sCommand, , Parameters, False)
608 On Error GoTo
0 ' Reset error status
609 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
610 If Not SF_FileSystem.FileExists(Command) Then GoTo CatchNotExists
611 Set oShell = SF_Utils._GetUNOService(
"SystemShellExecute
")
612 sCommand = SF_FileSystem._ConvertToUrl(Command)
613 oShell.execute(sCommand, Parameters, com.sun.star.system.SystemShellExecuteFlags.DEFAULTS)
619 RunApplication = bReturn
620 SF_Utils._ExitFunction(cstThisSub)
625 SF_Exception.RaiseFatal(UNKNOWNFILEERROR,
"Command
", Command)
627 End Function
' ScriptForge.SF_Session.RunApplication
629 REM -----------------------------------------------------------------------------
630 Public Sub SendMail(Optional ByVal Recipient As Variant _
631 , Optional ByRef Cc As Variant _
632 , Optional ByRef Bcc As Variant _
633 , Optional ByVal Subject As Variant _
634 , Optional ByRef Body As Variant _
635 , Optional ByVal FileNames As Variant _
636 , Optional ByVal EditMessage As Variant _
638 ''' Send a message (with or without attachments) to recipients from the user
's mail client
639 ''' The message may be edited by the user before sending or, alternatively, be sent immediately
640 ''' Args:
641 ''' Recipient: an email addresses (To recipient)
642 ''' Cc: a comma-delimited list of email addresses (carbon copy)
643 ''' Bcc: a comma-delimited list of email addresses (blind carbon copy)
644 ''' Subject: the header of the message
645 ''' FileNames: a comma-separated list of filenames to attach to the mail. SF_FileSystem naming conventions apply
646 ''' Body: the unformatted text of the message
647 ''' EditMessage: when True (default) the message is editable before being sent
648 ''' Exceptions:
649 ''' UNKNOWNFILEERROR File does not exist
650 ''' WRONGEMAILERROR String not recognized as an email address
651 ''' SENDMAILERROR System error, probably no mail client
653 Dim sEmail As String
' An single email address
654 Dim sFile As String
' A single file name
655 Dim sArg As String
' Argument name
656 Dim vCc As Variant
' Array alias of Cc
657 Dim vBcc As Variant
' Array alias of Bcc
658 Dim vFileNames As Variant
' Array alias of FileNames
659 Dim oMailService As Object
' com.sun.star.system.SimpleCommandMail or com.sun.star.system.SimpleSystemMail
660 Dim oMail As Object
' com.sun.star.system.XSimpleMailClient
661 Dim oMessage As Object
' com.sun.star.system.XSimpleMailMessage
662 Dim lFlag As Long
' com.sun.star.system.SimpleMailClientFlags.XXX
663 Dim ARR As Object : ARR = ScriptForge.SF_Array
665 Const cstComma =
",
", cstSemiColon =
";
"
666 Const cstThisSub =
"Session.SendMail
"
667 Const cstSubArgs =
"Recipient, [Cc=
""""], [Bcc=
""""], [Subject=
""""], [FileNames=
""""], [Body=
""""], [EditMessage=True]
"
669 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
672 If IsMissing(Cc) Or IsEmpty(Cc) Then Cc =
""
673 If IsMissing(Bcc) Or IsEmpty(Bcc) Then Bcc =
""
674 If IsMissing(Subject) Or IsEmpty(Subject) Then Subject =
""
675 If IsMissing(FileNames) Or IsEmpty(FileNames) Then FileNames =
""
676 If IsMissing(Body) Or IsEmpty(Body) Then Body =
""
677 If IsMissing(EditMessage) Or IsEmpty(EditMessage) Then EditMessage = True
679 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
680 If Not SF_Utils._Validate(Recipient,
"Recipient
", V_STRING) Then GoTo Finally
681 If Not SF_Utils._Validate(Cc,
"Cc
", V_STRING) Then GoTo Finally
682 If Not SF_Utils._Validate(Bcc,
"Bcc
", V_STRING) Then GoTo Finally
683 If Not SF_Utils._Validate(Subject,
"Subject
", V_STRING) Then GoTo Finally
684 If Not SF_Utils._Validate(FileNames,
"FileNames
", V_STRING) Then GoTo Finally
685 If Not SF_Utils._Validate(Body,
"Body
", V_STRING) Then GoTo Finally
686 If Not SF_Utils._Validate(EditMessage,
"EditMessage
", V_BOOLEAN) Then GoTo Finally
689 ' Check email addresses
690 sArg =
"Recipient
" : sEmail = Recipient
691 If Not SF_String.IsEmail(sEmail) Then GoTo CatchEmail
692 sArg =
"Cc
" : vCc = ARR.TrimArray(Split(Cc, cstComma))
693 For Each sEmail In vCc
694 If Not SF_String.IsEmail(sEmail) Then GoTo CatchEmail
696 sArg =
"Bcc
" : vBcc = ARR.TrimArray(Split(Bcc, cstComma))
697 For Each sEmail In vBcc
698 If Not SF_String.IsEmail(sEmail) Then GoTo CatchEmail
701 ' Check file existence
702 If Len(FileNames)
> 0 Then
703 vFileNames = ARR.TrimArray(Split(FileNames, cstComma))
704 For i =
0 To UBound(vFileNames)
705 sFile = vFileNames(i)
706 If Not SF_Utils._ValidateFile(sFile,
"FileNames
") Then GoTo Finally
707 If Not SF_FileSystem.FileExists(sFile) Then GoTo CatchNotExists
708 vFileNames(i) = ConvertToUrl(sFile)
715 ' Initialize the mail service
716 Set oMailService = SF_Utils._GetUNOService(
"MailService
")
717 If IsNull(oMailService) Then GoTo CatchMail
718 Set oMail = oMailService.querySimpleMailClient()
719 If IsNull(oMail) Then GoTo CatchMail
720 Set oMessage = oMail.createSimpleMailMessage()
721 If IsNull(oMessage) Then GoTo CatchMail
723 ' Feed the new mail message
725 .setRecipient(Recipient)
726 If Subject
<> "" Then .setSubject(Subject)
727 If UBound(vCc)
>=
0 Then .setCcRecipient(vCc)
728 If UBound(vBcc)
>=
0 Then .setBccRecipient(vBcc)
729 .Body = Iif(Len(Body) =
0,
" ", Body)
' Body must not be the empty string ??
730 .setAttachement(vFileNames)
732 lFlag = Iif(EditMessage, com.sun.star.system.SimpleMailClientFlags.DEFAULTS, com.sun.star.system.SimpleMailClientFlags.NO_USER_INTERFACE)
734 ' Send using the mail service
735 oMail.sendSimpleMailMessage(oMessage, lFlag)
738 SF_Utils._ExitFunction(cstThisSub)
743 SF_Exception.RaiseFatal(WRONGEMAILERROR, sArg, sEmail)
746 SF_Exception.RaiseFatal(UNKNOWNFILEERROR,
"FileNames
", sFile)
749 SF_Exception.RaiseFatal(SENDMAILERROR)
751 End Sub
' ScriptForge.SF_Session.SendMail
753 REM -----------------------------------------------------------------------------
754 Public Function SetPDFExportOptions(Optional ByRef PDFOptions As Variant) As Boolean
755 ''' Modify the actual values of the PDF export options from an options dictionary
756 ''' The PDF options are described on https://wiki.openoffice.org/wiki/API/Tutorials/PDF_export
757 ''' PDF options are set at each use of the Export as ... PDF command by the user and kept
758 ''' permanently until their reset by script (like this one) or by a new export
759 ''' The changed options are applicable on any subsequent ExportToPDF user command or to any SaveAsPDF script execution
760 ''' Args:
761 ''' PDFOptions: a ScriptForge dictionary object
762 ''' Returns:
763 ''' True when successful
764 ''' Examples:
765 ''' Dim dict As Object
766 ''' Set dict = session.GetPDFExportOptions()
767 ''' dict.ReplaceItem(
"Quality
",
50)
768 ''' session.SetPDFExportOptions(dict)
770 Dim bSetPDF As Boolean
' Returned value
771 Dim oConfig As Object
' com.sun.star.configuration.ConfigurationProvider
772 Dim oNodePath As Object
' com.sun.star.beans.PropertyValue
773 Dim oOptions As Object
' configmgr.RootAccess
774 Dim vOptionNames As Variant
' Array of PDF options names
775 Dim vOptionValues As Variant
' Array of PDF options values
776 Dim oDict As Object
' Alias of PDFOptions
779 Const cstThisSub =
"Session.SetPDFExportOptions
"
780 Const cstSubArgs =
"PDFOptions
"
782 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
786 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
787 If Not SF_Utils._Validate(PDFOptions,
"PDFOptions
", V_OBJECT, , ,
"DICTIONARY
") Then GoTo Finally
791 ' Get the (updatable) internal PDF options
792 Set oConfig = SF_Utils._GetUNOService(
"ConfigurationProvider
")
793 Set oNodePath = SF_Utils._MakePropertyValue(
"nodepath
",
"/org.openoffice.Office.Common/Filter/PDF/Export/
")
794 Set oOptions = oConfig.createInstanceWithArguments(
"com.sun.star.configuration.ConfigurationUpdateAccess
", Array(oNodePath))
796 ' Copy the options from the ScriptForge dictionary in argument to property values
797 Set oDict = PDFOptions
798 oOptions.setPropertyValues(oDict.Keys, oDict.Items)
799 oOptions.commitChanges()
804 SetPDFExportOptions = bSetPDF
805 SF_Utils._ExitFunction(cstThisSub)
809 End Function
' ScriptForge.SF_Session.SetPDFExportOptions
811 REM -----------------------------------------------------------------------------
812 Public Function SetProperty(Optional ByVal PropertyName As Variant _
813 , Optional ByRef Value As Variant _
815 ''' Set a new value to the given property
816 ''' Args:
817 ''' PropertyName: the name of the property as a string
818 ''' Value: its new value
819 ''' Exceptions
820 ''' ARGUMENTERROR The property does not exist
822 Const cstThisSub =
"Session.SetProperty
"
823 Const cstSubArgs =
"PropertyName, Value
"
825 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
829 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
830 If Not SF_Utils._Validate(PropertyName,
"PropertyName
", V_STRING, Properties()) Then GoTo Catch
834 Select Case UCase(PropertyName)
839 SF_Utils._ExitFunction(cstThisSub)
843 End Function
' ScriptForge.SF_Session.SetProperty
845 REM -----------------------------------------------------------------------------
846 Public Function UnoMethods(Optional ByRef UnoObject As Variant) As Variant
847 ''' Returns a list of the methods callable from an UNO object
848 ''' Code-snippet derived from XRAY
849 ''' Args:
850 ''' UnoObject: the object to identify
851 ''' Returns:
852 ''' A zero-based sorted array. May be empty
854 Dim oIntrospect As Object
' com.sun.star.beans.Introspection
855 Dim oInspect As Object
' com.sun.star.beans.XIntrospectionAccess
856 Dim vMethods As Variant
' Array of com.sun.star.reflection.XIdlMethod
857 Dim vMethod As Object
' com.sun.star.reflection.XIdlMethod
858 Dim lMax As Long
' UBounf of vMethods
859 Dim vMethodsList As Variant
' Return value
861 Const cstThisSub =
"Session.UnoMethods
"
862 Const cstSubArgs =
"UnoObject
"
864 SF_Utils._EnterFunction(cstThisSub, cstSubArgs)
867 vMethodsList = Array()
868 If VarType(UnoObject)
<> V_OBJECT Then GoTo Finally
869 If IsNull(UnoObject) Then GoTo Finally
872 On Local Error GoTo Catch
873 Set oIntrospect = SF_Utils._GetUNOService(
"Introspection
")
874 Set oInspect = oIntrospect.inspect(UnoObject)
875 vMethods = oInspect.getMethods(com.sun.star.beans.MethodConcept.ALL)
877 ' The names must be extracted from com.sun.star.reflection.XIdlMethod structures
878 lMax = UBound(vMethods)
880 ReDim vMethodsList(
0 To lMax)
882 vMethodsList(i) = vMethods(i).Name
884 vMethodsList = SF_Array.Sort(vMethodsList, CaseSensitive := True)
888 UnoMethods = vMethodsList
889 SF_Utils._ExitFunction(cstThisSub)
892 On Local Error GoTo
0
894 End Function
' ScriptForge.SF_Session.UnoMethods
896 REM -----------------------------------------------------------------------------
897 Public Function UnoObjectType(Optional ByRef UnoObject As Variant) As String
898 ''' Identify the UNO type of an UNO object
899 ''' Code-snippet derived from XRAY
900 ''' Args:
901 ''' UnoObject: the object to identify
902 ''' Returns:
903 ''' com.sun.star. ... as a string
904 ''' a zero-length string if identification was not successful
906 Dim oObjDesc As Object
' _ObjectDescriptor type
907 Dim sObjectType As String
' Return value
908 Const cstThisSub =
"Session.UnoObjectType
"
909 Const cstSubArgs =
"UnoObject
"
911 SF_Utils._EnterFunction(cstThisSub, cstSubArgs)
914 sObjectType =
""
915 If VarType(UnoObject)
<> V_OBJECT Then GoTo Finally
916 If IsNull(UnoObject) Then GoTo Finally
919 Set oObjDesc = SF_Utils._VarTypeObj(UnoObject)
920 If oObjDesc.iVarType = V_UNOOBJECT Then sObjectType = oObjDesc.sObjectType
923 UnoObjectType = sObjectType
924 SF_Utils._ExitFunction(cstThisSub)
926 End Function
' ScriptForge.SF_Session.UnoObjectType
928 REM -----------------------------------------------------------------------------
929 Public Function UnoProperties(Optional ByRef UnoObject As Variant) As Variant
930 ''' Returns a list of the properties of an UNO object
931 ''' Code-snippet derived from XRAY
932 ''' Args:
933 ''' UnoObject: the object to identify
934 ''' Returns:
935 ''' A zero-based sorted array. May be empty
937 Dim oIntrospect As Object
' com.sun.star.beans.Introspection
938 Dim oInspect As Object
' com.sun.star.beans.XIntrospectionAccess
939 Dim vProperties As Variant
' Array of com.sun.star.beans.Property
940 Dim vProperty As Object
' com.sun.star.beans.Property
941 Dim lMax As Long
' UBounf of vProperties
942 Dim vPropertiesList As Variant
' Return value
944 Const cstThisSub =
"Session.UnoProperties
"
945 Const cstSubArgs =
"UnoObject
"
947 SF_Utils._EnterFunction(cstThisSub, cstSubArgs)
950 vPropertiesList = Array()
951 If VarType(UnoObject)
<> V_OBJECT Then GoTo Finally
952 If IsNull(UnoObject) Then GoTo Finally
955 On Local Error GoTo Catch
956 Set oIntrospect = SF_Utils._GetUNOService(
"Introspection
")
957 Set oInspect = oIntrospect.inspect(UnoObject)
958 vProperties = oInspect.getProperties(com.sun.star.beans.PropertyConcept.ALL)
960 ' The names must be extracted from com.sun.star.beans.Property structures
961 lMax = UBound(vProperties)
963 ReDim vPropertiesList(
0 To lMax)
965 vPropertiesList(i) = vProperties(i).Name
967 vPropertiesList = SF_Array.Sort(vPropertiesList, CaseSensitive := True)
971 UnoProperties = vPropertiesList
972 SF_Utils._ExitFunction(cstThisSub)
975 On Local Error GoTo
0
977 End Function
' ScriptForge.SF_Session.UnoProperties
979 REM -----------------------------------------------------------------------------
980 Public Function WebService(Optional ByVal URI As Variant) As String
981 ''' Get some web content from a URI
982 ''' Args:
983 ''' URI: URI text of the web service
984 ''' Returns:
985 ''' The web page content of the URI
986 ''' Exceptions:
987 ''' CALCFUNCERROR
988 ''' Examples:
989 ''' session.WebService(
"wiki.documentfoundation.org/api.php?
" _
990 ''' & "hidebots=
1&days=
7&limit=
50&action=feedrecentchanges
&feedformat=rss
")
992 Dim sReturn As String
' Returned value
993 Const cstThisSub =
"Session.WebService
"
994 Const cstSubArgs =
"URI
"
996 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
997 sReturn =
""
1000 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1001 If Not SF_Utils._Validate(URI,
"URI
", V_STRING) Then GoTo Finally
1005 sReturn = SF_Session.ExecuteCalcFunction(
"WEBSERVICE
", URI)
1008 WebService = sReturn
1009 SF_Utils._ExitFunction(cstThisSub)
1013 End Function
' ScriptForge.SF_Session.WebService
1015 REM =========================================================== PRIVATE FUNCTIONS
1017 REM -----------------------------------------------------------------------------
1018 Private Function _ExecuteScript(ByVal psScript As String _
1019 , Optional ByRef pvArg As Variant _
1021 ''' Execute the script expressed in the scripting framework_URI notation
1022 ''' Args:
1023 ''' psScript: read https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework#Scripting_Framework_URI_Specification
1024 ''' pvArg: the unique argument to pass to the called script.
1025 ''' It is often an event object that triggered the execution of the script.
1026 ''' Returns:
1027 ''' The return value after the script execution. May be ignored for events
1029 Dim sScope As String
' The scope part of the script URI
1030 Dim sLanguage As String
' The language part of the script URI
1031 Dim sScript As String
' The script part of the script URI
1032 Dim vStrings As Variant
' Array of strings: (script, language, scope)
1033 Const cstComma =
",
"
1036 If ScriptForge.SF_String.StartsWith(psScript, cstScript1) Then
1040 Replace(Mid(psScript, Len(cstScript1) +
1), cstScript2, cstComma) _
1041 , cstScript3, cstComma) _
1043 sScript = vStrings(
0) : sLanguage = vStrings(
1) : sScope = vStrings(
2)
1044 ' Execute script
1045 If UCase(sLanguage) =
"BASIC
" Then
1046 _ExecuteScript = ExecuteBasicScript(sScope, sScript, pvArg)
1048 _ExecuteScript = ExecutePythonScript(sScope, sScript, pvArg)
1052 End Function
' ScriptForge.SF_Session._ExecuteScript
1054 REM -----------------------------------------------------------------------------
1055 Private Function _GetScript(ByVal psLanguage As String _
1056 , ByVal psScope As String _
1057 , ByVal psScript As String _
1059 ''' Get the adequate script provider and from there the requested script
1060 ''' Called by ExecuteBasicScript() and ExecutePythonScript()
1061 ''' The execution of the script is done by the caller
1062 ''' Args:
1063 ''' psLanguage: Basic or Python
1064 ''' psScope: one of the SCRIPTISxxx constants
1065 ''' The SCRIPTISOXT constant is an alias for
2 cases, extension either
1066 ''' installed for one user only, or for all users
1067 ''' Managed here by trial and error
1068 ''' psScript: Read https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework#Scripting_Framework_URI_Specification
1069 ''' Returns:
1070 ''' A com.sun.star.script.provider.XScript object
1072 Dim sScript As String
' The complete script string
1073 Dim oScriptProvider As Object
' Script provider singleton
1074 Dim oScript As Object
' Return value
1077 ' Build script string
1078 sScript = cstScript1
& psScript
& cstScript2
& psLanguage
& cstScript3
& LCase(psScope)
1081 Set oScript = Nothing
1082 ' Python only: installation of extension is determined by user =
> unknown to script author
1083 If psScope = SCRIPTISOXT Then
' =
> Trial and error
1084 On Local Error GoTo ForAllUsers
1085 sScript = cstScript1
& psScript
& cstScript2
& psLanguage
& cstScript3
& SCRIPTISPERSOXT
1086 Set oScriptProvider = SF_Utils._GetUNOService(
"ScriptProvider
", SCRIPTISPERSOXT)
1087 Set oScript = oScriptProvider.getScript(sScript)
1090 On Local Error GoTo CatchNotFound
1091 If IsNull(oScript) Then
1092 If psScope = SCRIPTISOXT Then psScope = SCRIPTISSHAROXT
1093 Set oScriptProvider = SF_Utils._GetUNOService(
"ScriptProvider
", psScope)
1094 Set oScript = oScriptProvider.getScript(sScript)
1098 _GetScript = oScript
1101 SF_Exception.RaiseFatal(NOSCRIPTERROR, psLanguage,
"Scope
", psScope,
"Script
", psScript)
1103 End Function
' ScriptForge.SF_Session._GetScript
1105 REM =============================================== END OF SCRIPTFORGE.SF_SESSION