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 a string, a numeric value
194 ''' or an array of arrays combining those types
195 ''' Returns:
196 ''' The (string or numeric) value or the array of arrays returned by the call to the function
197 ''' When the arguments contain arrays, the function is executed as an array function
198 ''' Wrong arguments generate an error
199 ''' Exceptions:
200 ''' CALCFUNCERROR
' Execution error in calc function
201 ''' Examples:
202 ''' session.ExecuteCalcFunction(
"AVERAGE
",
1,
5,
3,
7) returns
4
203 ''' session.ExecuteCalcFunction(
"ABS
", Array(Array(-
1,
2,
3),Array(
4,-
5,
6),Array(
7,
8,-
9)))(
2)(
2) returns
9
204 ''' session.ExecuteCalcFunction(
"LN
", -
3) generates an error
206 Dim oCalc As Object
' Give access to the com.sun.star.sheet.FunctionAccess service
207 Dim vReturn As Variant
' Returned value
208 Const cstThisSub =
"Session.ExecuteCalcFunction
"
209 Const cstSubArgs =
"CalcFunction, arg0[, arg1] ...
"
211 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
215 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
216 If Not SF_Utils._Validate(CalcFunction,
"CalcFunction
", V_STRING) Then GoTo Finally
220 ' Execute function
221 Set oCalc = SF_Utils._GetUNOService(
"FunctionAccess
")
222 ' Intercept calls from Python when no arguments. Example NOW()
223 If UBound(pvArgs) =
0 Then
224 If IsEmpty(pvArgs(
0)) Then pvArgs = Array()
226 On Local Error GoTo CatchCall
227 vReturn = oCalc.callFunction(UCase(CalcFunction), pvArgs())
230 ExecuteCalcFunction = vReturn
231 SF_Utils._ExitFunction(cstThisSub)
236 SF_Exception.RaiseFatal(CALCFUNCERROR, CalcFunction)
238 End Function
' ScriptForge.SF_Session.ExecuteCalcFunction
240 REM -----------------------------------------------------------------------------
241 Public Function ExecutePythonScript(Optional ByVal Scope As Variant _
242 , Optional ByVal Script As Variant _
243 , ParamArray pvArgs As Variant _
245 ''' Execute the Python script given as a string and return the value returned by the script
246 ''' Args:
247 ''' Scope: one of the SCRIPTIS... public constants above (default =
"share
")
248 ''' Script: (Case sensitive)
249 ''' "library/module.py$method
"
250 ''' or
"module.py$method
"
251 ''' or
"myExtension.oxt|myScript|module.py$method
"
252 ''' library =
> The library may be not loaded yet
253 ''' myScript =
> The directory containing the python module
254 ''' module.py =
> The python module
255 ''' method =
> The python function
256 ''' Read https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework#Scripting_Framework_URI_Specification
257 ''' pvArgs: the arguments of the called script
258 ''' Date arguments are converted to iso format. However dates in arrays are not converted
259 ''' Returns:
260 ''' The value(s) returned by the call to the script. If
>1 values, enclosed in an array
261 ''' Exceptions:
262 ''' NOSCRIPTERROR The script could not be found
263 ''' Examples:
264 ''' session.ExecutePythonScript(session.SCRIPTISSHARED,
"Capitalise.py$getNewString
",
"Abc
") returns
"abc
"
266 Dim oScript As Object
' Script to be invoked
267 Dim vArg As Variant
' Individual argument
268 Dim vReturn As Variant
' Returned value
271 Const cstThisSub =
"Session.ExecutePythonScript
"
272 Const cstSubArgs =
"[Scope], Script, arg0[, arg1] ...
"
274 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
279 If IsError(Scope) Or IsMissing(Scope) Then Scope = SCRIPTISSHARED
280 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
281 If Not SF_Utils._Validate(Scope,
"Scope
", V_STRING _
282 , Array(SCRIPTISSHARED, SCRIPTISEMBEDDED, SCRIPTISPERSONAL, SCRIPTISSHAROXT, SCRIPTISPERSOXT, SCRIPTISOXT) _
284 If Not SF_Utils._Validate(Script,
"Script
", V_STRING) Then GoTo Finally
288 ' Filter date arguments - NB: dates in arrays are not filtered
289 For i =
0 To UBound(pvArgs)
' pvArgs always zero-based
291 If VarType(vArg) = V_DATE Then pvArgs(i) = SF_Utils._CDateToIso(vArg)
294 ' Intercept alternate Python helpers file when relevant
296 If SF_String.StartsWith(Script, .PythonHelper) And Len(.PythonHelper2)
> 0 Then
297 Scope = SCRIPTISPERSONAL
298 Script = .PythonHelper2
& Mid(Script, Len(.PythonHelper) +
1)
302 Set oScript = SF_Session._GetScript(
"Python
", Scope, Script)
304 ' Execute script
305 If Not IsNull(oScript) Then
306 vReturn = oScript.Invoke(pvArgs(), Array(), Array())
307 ' Remove surrounding array when single returned value
308 If IsArray(vReturn) Then
309 If UBound(vReturn) =
0 Then vReturn = vReturn(
0)
314 ExecutePythonScript = vReturn
315 SF_Utils._ExitFunction(cstThisSub)
319 End Function
' ScriptForge.SF_Session.ExecutePythonScript
321 REM -----------------------------------------------------------------------------
322 Public Function GetPDFExportOptions() As Variant
323 ''' Return the actual values of the PDF export options
324 ''' The PDF options are described on https://wiki.openoffice.org/wiki/API/Tutorials/PDF_export
325 ''' PDF options are set at each use of the Export as ... PDF command by the user and kept
326 ''' permanently until their reset by script or by a new export
327 ''' Args:
328 ''' Returns:
329 ''' A ScriptForge dictionary instance listing the
40+ properties and their value
330 ''' Examples:
331 ''' Dim dict As Object
332 ''' Set dict = session.GetPDFExportOptions()
333 ''' MsgBox dict.Item(
"Quality
")
335 Dim vDict As Variant
' Returned value
336 Dim oConfig As Object
' com.sun.star.configuration.ConfigurationProvider
337 Dim oNodePath As Object
' com.sun.star.beans.PropertyValue
338 Dim oOptions As Object
' configmgr.RootAccess
339 Dim vOptionNames As Variant
' Array of PDF options names
340 Dim vOptionValues As Variant
' Array of PDF options values
343 Const cstThisSub =
"Session.GetPDFExportOptions
"
344 Const cstSubArgs =
""
346 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
350 SF_Utils._EnterFunction(cstThisSub, cstSubArgs)
353 ' Get the (read-only) internal PDF options
354 Set oConfig = SF_Utils._GetUNOService(
"ConfigurationProvider
")
355 Set oNodePath = SF_Utils._MakePropertyValue(
"nodepath
",
"/org.openoffice.Office.Common/Filter/PDF/Export/
")
356 Set oOptions = oConfig.createInstanceWithArguments(
"com.sun.star.configuration.ConfigurationAccess
", Array(oNodePath))
358 ' Copy the options into a ScriptForge dictionary
359 Set vDict = CreateScriptService(
"dictionary
")
360 vOptionNames = oOptions.getElementNames()
361 vOptionValues = oOptions.getPropertyValues(vOptionNames)
363 For i =
0 To UBound(vOptionNames)
364 vDict.Add(vOptionNames(i), vOptionValues(i))
369 GetPDFExportOptions = vDict
370 SF_Utils._ExitFunction(cstThisSub)
374 End Function
' ScriptForge.SF_Session.GetPDFExportOptions
376 REM -----------------------------------------------------------------------------
377 Public Function GetProperty(Optional ByVal PropertyName As Variant) As Variant
378 ''' Return the actual value of the given property
379 ''' Args:
380 ''' PropertyName: the name of the property as a string
381 ''' Returns:
382 ''' The actual value of the property
383 ''' Exceptions
384 ''' ARGUMENTERROR The property does not exist
386 Const cstThisSub =
"Session.GetProperty
"
387 Const cstSubArgs =
"PropertyName
"
389 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
393 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
394 If Not SF_Utils._Validate(PropertyName,
"PropertyName
", V_STRING, Properties()) Then GoTo Catch
398 Select Case UCase(PropertyName)
403 SF_Utils._ExitFunction(cstThisSub)
407 End Function
' ScriptForge.SF_Session.GetProperty
409 REM -----------------------------------------------------------------------------
410 Public Function HasUnoMethod(Optional ByRef UnoObject As Variant _
411 , Optional ByVal MethodName As Variant _
413 ''' Returns True if a UNO object contains the given method
414 ''' Code-snippet derived from XRAY
415 ''' Args:
416 ''' UnoObject: the object to identify
417 ''' MethodName: the name of the method as a string. The search is case-sensitive
418 ''' Returns:
419 ''' False when the method is not found or when an argument is invalid
421 Dim oIntrospect As Object
' com.sun.star.beans.Introspection
422 Dim oInspect As Object
' com.sun.star.beans.XIntrospectionAccess
423 Dim bMethod As Boolean
' Return value
424 Const cstThisSub =
"Session.HasUnoMethod
"
425 Const cstSubArgs =
"UnoObject, MethodName
"
427 SF_Utils._EnterFunction(cstThisSub, cstSubArgs)
431 If VarType(UnoObject)
<> V_OBJECT Then GoTo Finally
432 If IsNull(UnoObject) Then GoTo Finally
433 If VarType(MethodName)
<> V_STRING Then GoTo Finally
434 If MethodName = Space(Len(MethodName)) Then GoTo Finally
437 On Local Error GoTo Catch
438 Set oIntrospect = SF_Utils._GetUNOService(
"Introspection
")
439 Set oInspect = oIntrospect.inspect(UnoObject)
440 bMethod = oInspect.hasMethod(MethodName, com.sun.star.beans.MethodConcept.ALL)
443 HasUnoMethod = bMethod
444 SF_Utils._ExitFunction(cstThisSub)
447 On Local Error GoTo
0
449 End Function
' ScriptForge.SF_Session.HasUnoMethod
451 REM -----------------------------------------------------------------------------
452 Public Function HasUnoProperty(Optional ByRef UnoObject As Variant _
453 , Optional ByVal PropertyName As Variant _
455 ''' Returns True if a UNO object contains the given property
456 ''' Code-snippet derived from XRAY
457 ''' Args:
458 ''' UnoObject: the object to identify
459 ''' PropertyName: the name of the property as a string. The search is case-sensitive
460 ''' Returns:
461 ''' False when the property is not found or when an argument is invalid
463 Dim oIntrospect As Object
' com.sun.star.beans.Introspection
464 Dim oInspect As Object
' com.sun.star.beans.XIntrospectionAccess
465 Dim bProperty As Boolean
' Return value
466 Const cstThisSub =
"Session.HasUnoProperty
"
467 Const cstSubArgs =
"UnoObject, PropertyName
"
469 SF_Utils._EnterFunction(cstThisSub, cstSubArgs)
473 If VarType(UnoObject)
<> V_OBJECT Then GoTo Finally
474 If IsNull(UnoObject) Then GoTo Finally
475 If VarType(PropertyName)
<> V_STRING Then GoTo Finally
476 If PropertyName = Space(Len(PropertyName)) Then GoTo Finally
479 On Local Error GoTo Catch
480 Set oIntrospect = SF_Utils._GetUNOService(
"Introspection
")
481 Set oInspect = oIntrospect.inspect(UnoObject)
482 bProperty = oInspect.hasProperty(PropertyName, com.sun.star.beans.PropertyConcept.ALL)
485 HasUnoProperty = bProperty
486 SF_Utils._ExitFunction(cstThisSub)
489 On Local Error GoTo
0
491 End Function
' ScriptForge.SF_Session.HasUnoProperty
493 REM -----------------------------------------------------------------------------
494 Public Function Methods() As Variant
495 ''' Return the list of public methods of the Session service as an array
498 "ExecuteBasicScript
" _
499 ,
"ExecuteCalcFunction
" _
500 ,
"ExecutePythonScript
" _
501 ,
"HasUnoMethod
" _
502 ,
"HasUnoProperty
" _
503 ,
"OpenURLInBrowser
" _
504 ,
"RunApplication
" _
505 ,
"SendMail
" _
506 ,
"UnoMethods
" _
507 ,
"UnoObjectType
" _
508 ,
"UnoProperties
" _
509 ,
"WebService
" _
512 End Function
' ScriptForge.SF_Session.Methods
514 REM -----------------------------------------------------------------------------
515 Public Sub OpenURLInBrowser(Optional ByVal URL As Variant)
516 ''' Opens a URL in the default browser
517 ''' Args:
518 ''' URL: The URL to open in the browser
519 ''' Examples:
520 ''' session.OpenURLInBrowser(
"https://docs.python.org/
3/library/webbrowser.html
")
522 Const cstPyHelper =
"$
" & "_SF_Session__OpenURLInBrowser
"
524 Const cstThisSub =
"Session.OpenURLInBrowser
"
525 Const cstSubArgs =
"URL
"
527 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
530 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
531 If Not SF_Utils._Validate(URL,
"URL
", V_STRING) Then GoTo Finally
535 ExecutePythonScript(SCRIPTISSHARED, _SF_.PythonHelper
& cstPyHelper, URL)
538 SF_Utils._ExitFunction(cstThisSub)
542 End Sub
' ScriptForge.SF_Session.OpenURLInBrowser
544 REM -----------------------------------------------------------------------------
545 Public Function Properties() As Variant
546 ''' Return the list or properties as an array
548 Properties = Array( _
551 End Function
' ScriptForge.SF_Session.Properties
553 REM -----------------------------------------------------------------------------
554 Public Function RunApplication(Optional ByVal Command As Variant _
555 , Optional ByVal Parameters As Variant _
557 ''' Executes an arbitrary system command
558 ''' Args:
559 ''' Command: The command to execute
560 ''' This may be an executable file or a document which is registered with an application
561 ''' so that the system knows what application to launch for that document
562 ''' Parameters: a list of space separated parameters as a single string
563 ''' The method does not validate the given parameters, but only passes them to the specified command
564 ''' Returns:
565 ''' True if success
566 ''' Examples:
567 ''' session.RunApplication(
"Notepad.exe
")
568 ''' session.RunApplication(
"C:\myFolder\myDocument.odt
")
569 ''' session.RunApplication(
"kate
",
"/home/me/install.txt
")
' (Linux)
571 Dim bReturn As Boolean
' Returned value
572 Dim oShell As Object
' com.sun.star.system.SystemShellExecute
573 Dim sCommand As String
' Command as an URL
574 Const cstThisSub =
"Session.RunApplication
"
575 Const cstSubArgs =
"Command, [Parameters]
"
577 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
581 If IsMissing(Parameters) Then Parameters =
""
582 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
583 If Not SF_Utils._ValidateFile(Command,
"Command
") Then GoTo Finally
584 If Not SF_Utils._Validate(Parameters,
"Parameters
", V_STRING) Then GoTo Finally
588 Set oShell = SF_Utils._GetUNOService(
"SystemShellExecute
")
589 sCommand = SF_FileSystem._ConvertToUrl(Command)
590 oShell.execute(sCommand, Parameters, com.sun.star.system.SystemShellExecuteFlags.URIS_ONLY)
594 RunApplication = bReturn
595 SF_Utils._ExitFunction(cstThisSub)
599 End Function
' ScriptForge.SF_Session.RunApplication
601 REM -----------------------------------------------------------------------------
602 Public Sub SendMail(Optional ByVal Recipient As Variant _
603 , Optional ByRef Cc As Variant _
604 , Optional ByRef Bcc As Variant _
605 , Optional ByVal Subject As Variant _
606 , Optional ByRef Body As Variant _
607 , Optional ByVal FileNames As Variant _
608 , Optional ByVal EditMessage As Variant _
610 ''' Send a message (with or without attachments) to recipients from the user
's mail client
611 ''' The message may be edited by the user before sending or, alternatively, be sent immediately
612 ''' Args:
613 ''' Recipient: an email addresses (To recipient)
614 ''' Cc: a comma-delimited list of email addresses (carbon copy)
615 ''' Bcc: a comma-delimited list of email addresses (blind carbon copy)
616 ''' Subject: the header of the message
617 ''' FileNames: a comma-separated list of filenames to attach to the mail. SF_FileSystem naming conventions apply
618 ''' Body: the unformatted text of the message
619 ''' EditMessage: when True (default) the message is editable before being sent
620 ''' Exceptions:
621 ''' UNKNOWNFILEERROR File does not exist
622 ''' WRONGEMAILERROR String not recognized as an email address
623 ''' SENDMAILERROR System error, probably no mail client
625 Dim sEmail As String
' An single email address
626 Dim sFile As String
' A single file name
627 Dim sArg As String
' Argument name
628 Dim vCc As Variant
' Array alias of Cc
629 Dim vBcc As Variant
' Array alias of Bcc
630 Dim vFileNames As Variant
' Array alias of FileNames
631 Dim oMailService As Object
' com.sun.star.system.SimpleCommandMail or com.sun.star.system.SimpleSystemMail
632 Dim oMail As Object
' com.sun.star.system.XSimpleMailClient
633 Dim oMessage As Object
' com.sun.star.system.XSimpleMailMessage
634 Dim lFlag As Long
' com.sun.star.system.SimpleMailClientFlags.XXX
635 Dim ARR As Object : ARR = ScriptForge.SF_Array
637 Const cstComma =
",
", cstSemiColon =
";
"
638 Const cstThisSub =
"Session.SendMail
"
639 Const cstSubArgs =
"Recipient, [Cc=
""""], [Bcc=
""""], [Subject=
""""], [FileNames=
""""], [Body=
""""], [EditMessage=True]
"
641 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
644 If IsMissing(Cc) Or IsEmpty(Cc) Then Cc =
""
645 If IsMissing(Bcc) Or IsEmpty(Bcc) Then Bcc =
""
646 If IsMissing(Subject) Or IsEmpty(Subject) Then Subject =
""
647 If IsMissing(FileNames) Or IsEmpty(FileNames) Then FileNames =
""
648 If IsMissing(Body) Or IsEmpty(Body) Then Body =
""
649 If IsMissing(EditMessage) Or IsEmpty(EditMessage) Then EditMessage = True
651 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
652 If Not SF_Utils._Validate(Cc,
"Recipient
", V_STRING) Then GoTo Finally
653 If Not SF_Utils._Validate(Cc,
"Cc
", V_STRING) Then GoTo Finally
654 If Not SF_Utils._Validate(Bcc,
"Bcc
", V_STRING) Then GoTo Finally
655 If Not SF_Utils._Validate(Subject,
"Subject
", V_STRING) Then GoTo Finally
656 If Not SF_Utils._Validate(FileNames,
"FileNames
", V_STRING) Then GoTo Finally
657 If Not SF_Utils._Validate(Body,
"Body
", V_STRING) Then GoTo Finally
658 If Not SF_Utils._Validate(EditMessage,
"EditMessage
", V_BOOLEAN) Then GoTo Finally
661 ' Check email addresses
662 sArg =
"Recipient
" : sEmail = Recipient
663 If Not SF_String.IsEmail(sEmail) Then GoTo CatchEmail
664 sArg =
"Cc
" : vCc = ARR.TrimArray(Split(Cc, cstComma))
665 For Each sEmail In vCc
666 If Not SF_String.IsEmail(sEmail) Then GoTo CatchEmail
668 sArg =
"Bcc
" : vBcc = ARR.TrimArray(Split(Bcc, cstComma))
669 For Each sEmail In vBcc
670 If Not SF_String.IsEmail(sEmail) Then GoTo CatchEmail
673 ' Check file existence
674 If Len(FileNames)
> 0 Then
675 vFileNames = ARR.TrimArray(Split(FileNames, cstComma))
676 For i =
0 To UBound(vFileNames)
677 sFile = vFileNames(i)
678 If Not SF_Utils._ValidateFile(sFile,
"FileNames
") Then GoTo Finally
679 If Not SF_FileSystem.FileExists(sFile) Then GoTo CatchNotExists
680 vFileNames(i) = ConvertToUrl(sFile)
687 ' Initialize the mail service
688 Set oMailService = SF_Utils._GetUNOService(
"MailService
")
689 If IsNull(oMailService) Then GoTo CatchMail
690 Set oMail = oMailService.querySimpleMailClient()
691 If IsNull(oMail) Then GoTo CatchMail
692 Set oMessage = oMail.createSimpleMailMessage()
693 If IsNull(oMessage) Then GoTo CatchMail
695 ' Feed the new mail message
697 .setRecipient(Recipient)
698 If Subject
<> "" Then .setSubject(Subject)
699 If UBound(vCc)
>=
0 Then .setCcRecipient(vCc)
700 If UBound(vBcc)
>=
0 Then .setBccRecipient(vBcc)
701 .Body = Iif(Len(Body) =
0,
" ", Body)
' Body must not be the empty string ??
702 .setAttachement(vFileNames)
704 lFlag = Iif(EditMessage, com.sun.star.system.SimpleMailClientFlags.DEFAULTS, com.sun.star.system.SimpleMailClientFlags.NO_USER_INTERFACE)
706 ' Send using the mail service
707 oMail.sendSimpleMailMessage(oMessage, lFlag)
710 SF_Utils._ExitFunction(cstThisSub)
715 SF_Exception.RaiseFatal(WRONGEMAILERROR, sArg, sEmail)
718 SF_Exception.RaiseFatal(UNKNOWNFILEERROR,
"FileNames
", sFile)
721 SF_Exception.RaiseFatal(SENDMAILERROR)
723 End Sub
' ScriptForge.SF_Session.SendMail
725 REM -----------------------------------------------------------------------------
726 Public Function SetPDFExportOptions(Optional ByRef PDFOptions As Variant) As Boolean
727 ''' Modify the actual values of the PDF export options from an options dictionary
728 ''' The PDF options are described on https://wiki.openoffice.org/wiki/API/Tutorials/PDF_export
729 ''' PDF options are set at each use of the Export as ... PDF command by the user and kept
730 ''' permanently until their reset by script (like this one) or by a new export
731 ''' The changed options are applicable on any subsequent ExportToPDF user command or to any SaveAsPDF script execution
732 ''' Args:
733 ''' PDFOptions: a ScriptForge dictionary object
734 ''' Returns:
735 ''' True when successful
736 ''' Examples:
737 ''' Dim dict As Object
738 ''' Set dict = session.GetPDFExportOptions()
739 ''' dict.ReplaceItem(
"Quality
",
50)
740 ''' session.SetPDFExportOptions(dict)
742 Dim bSetPDF As Boolean
' Returned value
743 Dim oConfig As Object
' com.sun.star.configuration.ConfigurationProvider
744 Dim oNodePath As Object
' com.sun.star.beans.PropertyValue
745 Dim oOptions As Object
' configmgr.RootAccess
746 Dim vOptionNames As Variant
' Array of PDF options names
747 Dim vOptionValues As Variant
' Array of PDF options values
748 Dim oDict As Object
' Alias of PDFOptions
751 Const cstThisSub =
"Session.SetPDFExportOptions
"
752 Const cstSubArgs =
"PDFOptions
"
754 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
758 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
759 If Not SF_Utils._Validate(PDFOptions,
"PDFOptions
", V_OBJECT, , ,
"DICTIONARY
") Then GoTo Finally
763 ' Get the (updatable) internal PDF options
764 Set oConfig = SF_Utils._GetUNOService(
"ConfigurationProvider
")
765 Set oNodePath = SF_Utils._MakePropertyValue(
"nodepath
",
"/org.openoffice.Office.Common/Filter/PDF/Export/
")
766 Set oOptions = oConfig.createInstanceWithArguments(
"com.sun.star.configuration.ConfigurationUpdateAccess
", Array(oNodePath))
768 ' Copy the options from the ScriptForge dictionary in argument to property values
769 Set oDict = PDFOptions
770 oOptions.setPropertyValues(oDict.Keys, oDict.Items)
771 oOptions.commitChanges()
776 SetPDFExportOptions = bSetPDF
777 SF_Utils._ExitFunction(cstThisSub)
781 End Function
' ScriptForge.SF_Session.SetPDFExportOptions
783 REM -----------------------------------------------------------------------------
784 Public Function SetProperty(Optional ByVal PropertyName As Variant _
785 , Optional ByRef Value As Variant _
787 ''' Set a new value to the given property
788 ''' Args:
789 ''' PropertyName: the name of the property as a string
790 ''' Value: its new value
791 ''' Exceptions
792 ''' ARGUMENTERROR The property does not exist
794 Const cstThisSub =
"Session.SetProperty
"
795 Const cstSubArgs =
"PropertyName, Value
"
797 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
801 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
802 If Not SF_Utils._Validate(PropertyName,
"PropertyName
", V_STRING, Properties()) Then GoTo Catch
806 Select Case UCase(PropertyName)
811 SF_Utils._ExitFunction(cstThisSub)
815 End Function
' ScriptForge.SF_Session.SetProperty
817 REM -----------------------------------------------------------------------------
818 Public Function UnoMethods(Optional ByRef UnoObject As Variant) As Variant
819 ''' Returns a list of the methods callable from an UNO object
820 ''' Code-snippet derived from XRAY
821 ''' Args:
822 ''' UnoObject: the object to identify
823 ''' Returns:
824 ''' A zero-based sorted array. May be empty
826 Dim oIntrospect As Object
' com.sun.star.beans.Introspection
827 Dim oInspect As Object
' com.sun.star.beans.XIntrospectionAccess
828 Dim vMethods As Variant
' Array of com.sun.star.reflection.XIdlMethod
829 Dim vMethod As Object
' com.sun.star.reflection.XIdlMethod
830 Dim lMax As Long
' UBounf of vMethods
831 Dim vMethodsList As Variant
' Return value
833 Const cstThisSub =
"Session.UnoMethods
"
834 Const cstSubArgs =
"UnoObject
"
836 SF_Utils._EnterFunction(cstThisSub, cstSubArgs)
839 vMethodsList = Array()
840 If VarType(UnoObject)
<> V_OBJECT Then GoTo Finally
841 If IsNull(UnoObject) Then GoTo Finally
844 On Local Error GoTo Catch
845 Set oIntrospect = SF_Utils._GetUNOService(
"Introspection
")
846 Set oInspect = oIntrospect.inspect(UnoObject)
847 vMethods = oInspect.getMethods(com.sun.star.beans.MethodConcept.ALL)
849 ' The names must be extracted from com.sun.star.reflection.XIdlMethod structures
850 lMax = UBound(vMethods)
852 ReDim vMethodsList(
0 To lMax)
854 vMethodsList(i) = vMethods(i).Name
856 vMethodsList = SF_Array.Sort(vMethodsList, CaseSensitive := True)
860 UnoMethods = vMethodsList
861 SF_Utils._ExitFunction(cstThisSub)
864 On Local Error GoTo
0
866 End Function
' ScriptForge.SF_Session.UnoMethods
868 REM -----------------------------------------------------------------------------
869 Public Function UnoObjectType(Optional ByRef UnoObject As Variant) As String
870 ''' Identify the UNO type of an UNO object
871 ''' Code-snippet derived from XRAY
872 ''' Args:
873 ''' UnoObject: the object to identify
874 ''' Returns:
875 ''' com.sun.star. ... as a string
876 ''' a zero-length string if identification was not successful
878 Dim oObjDesc As Object
' _ObjectDescriptor type
879 Dim sObjectType As String
' Return value
880 Const cstThisSub =
"Session.UnoObjectType
"
881 Const cstSubArgs =
"UnoObject
"
883 SF_Utils._EnterFunction(cstThisSub, cstSubArgs)
886 sObjectType =
""
887 If VarType(UnoObject)
<> V_OBJECT Then GoTo Finally
888 If IsNull(UnoObject) Then GoTo Finally
891 Set oObjDesc = SF_Utils._VarTypeObj(UnoObject)
892 If oObjDesc.iVarType = V_UNOOBJECT Then sObjectType = oObjDesc.sObjectType
895 UnoObjectType = sObjectType
896 SF_Utils._ExitFunction(cstThisSub)
898 End Function
' ScriptForge.SF_Session.UnoObjectType
900 REM -----------------------------------------------------------------------------
901 Public Function UnoProperties(Optional ByRef UnoObject As Variant) As Variant
902 ''' Returns a list of the properties of an UNO object
903 ''' Code-snippet derived from XRAY
904 ''' Args:
905 ''' UnoObject: the object to identify
906 ''' Returns:
907 ''' A zero-based sorted array. May be empty
909 Dim oIntrospect As Object
' com.sun.star.beans.Introspection
910 Dim oInspect As Object
' com.sun.star.beans.XIntrospectionAccess
911 Dim vProperties As Variant
' Array of com.sun.star.beans.Property
912 Dim vProperty As Object
' com.sun.star.beans.Property
913 Dim lMax As Long
' UBounf of vProperties
914 Dim vPropertiesList As Variant
' Return value
916 Const cstThisSub =
"Session.UnoProperties
"
917 Const cstSubArgs =
"UnoObject
"
919 SF_Utils._EnterFunction(cstThisSub, cstSubArgs)
922 vPropertiesList = Array()
923 If VarType(UnoObject)
<> V_OBJECT Then GoTo Finally
924 If IsNull(UnoObject) Then GoTo Finally
927 On Local Error GoTo Catch
928 Set oIntrospect = SF_Utils._GetUNOService(
"Introspection
")
929 Set oInspect = oIntrospect.inspect(UnoObject)
930 vProperties = oInspect.getProperties(com.sun.star.beans.PropertyConcept.ALL)
932 ' The names must be extracted from com.sun.star.beans.Property structures
933 lMax = UBound(vProperties)
935 ReDim vPropertiesList(
0 To lMax)
937 vPropertiesList(i) = vProperties(i).Name
939 vPropertiesList = SF_Array.Sort(vPropertiesList, CaseSensitive := True)
943 UnoProperties = vPropertiesList
944 SF_Utils._ExitFunction(cstThisSub)
947 On Local Error GoTo
0
949 End Function
' ScriptForge.SF_Session.UnoProperties
951 REM -----------------------------------------------------------------------------
952 Public Function WebService(Optional ByVal URI As Variant) As String
953 ''' Get some web content from a URI
954 ''' Args:
955 ''' URI: URI text of the web service
956 ''' Returns:
957 ''' The web page content of the URI
958 ''' Exceptions:
959 ''' CALCFUNCERROR
960 ''' Examples:
961 ''' session.WebService(
"wiki.documentfoundation.org/api.php?
" _
962 ''' & "hidebots=
1&days=
7&limit=
50&action=feedrecentchanges
&feedformat=rss
")
964 Dim sReturn As String
' Returned value
965 Const cstThisSub =
"Session.WebService
"
966 Const cstSubArgs =
"URI
"
968 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
969 sReturn =
""
972 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
973 If Not SF_Utils._Validate(URI,
"URI
", V_STRING) Then GoTo Finally
977 sReturn = SF_Session.ExecuteCalcFunction(
"WEBSERVICE
", URI)
981 SF_Utils._ExitFunction(cstThisSub)
985 End Function
' ScriptForge.SF_Session.WebService
987 REM =========================================================== PRIVATE FUNCTIONS
989 REM -----------------------------------------------------------------------------
990 Private Function _ExecuteScript(ByVal psScript As String _
991 , Optional ByRef pvArg As Variant _
993 ''' Execute the script expressed in the scripting framework_URI notation
994 ''' Args:
995 ''' psScript: read https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework#Scripting_Framework_URI_Specification
996 ''' pvArg: the unique argument to pass to the called script.
997 ''' It is often an event object that triggered the execution of the script.
998 ''' Returns:
999 ''' The return value after the script execution. May be ignored for events
1001 Dim sScope As String
' The scope part of the script URI
1002 Dim sLanguage As String
' The language part of the script URI
1003 Dim sScript As String
' The script part of the script URI
1004 Dim vStrings As Variant
' Array of strings: (script, language, scope)
1005 Const cstComma =
",
"
1008 If ScriptForge.SF_String.StartsWith(psScript, cstScript1) Then
1012 Replace(Mid(psScript, Len(cstScript1) +
1), cstScript2, cstComma) _
1013 , cstScript3, cstComma) _
1015 sScript = vStrings(
0) : sLanguage = vStrings(
1) : sScope = vStrings(
2)
1016 ' Execute script
1017 If UCase(sLanguage) =
"BASIC
" Then
1018 _ExecuteScript = ExecuteBasicScript(sScope, sScript, pvArg)
1020 _ExecuteScript = ExecutePythonScript(sScope, sScript, pvArg)
1024 End Function
' ScriptForge.SF_Session._ExecuteScript
1026 REM -----------------------------------------------------------------------------
1027 Private Function _GetScript(ByVal psLanguage As String _
1028 , ByVal psScope As String _
1029 , ByVal psScript As String _
1031 ''' Get the adequate script provider and from there the requested script
1032 ''' Called by ExecuteBasicScript() and ExecutePythonScript()
1033 ''' The execution of the script is done by the caller
1034 ''' Args:
1035 ''' psLanguage: Basic or Python
1036 ''' psScope: one of the SCRIPTISxxx constants
1037 ''' The SCRIPTISOXT constant is an alias for
2 cases, extension either
1038 ''' installed for one user only, or for all users
1039 ''' Managed here by trial and error
1040 ''' psScript: Read https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework#Scripting_Framework_URI_Specification
1041 ''' Returns:
1042 ''' A com.sun.star.script.provider.XScript object
1044 Dim sScript As String
' The complete script string
1045 Dim oScriptProvider As Object
' Script provider singleton
1046 Dim oScript As Object
' Return value
1049 ' Build script string
1050 sScript = cstScript1
& psScript
& cstScript2
& psLanguage
& cstScript3
& LCase(psScope)
1053 Set oScript = Nothing
1054 ' Python only: installation of extension is determined by user =
> unknown to script author
1055 If psScope = SCRIPTISOXT Then
' =
> Trial and error
1056 On Local Error GoTo ForAllUsers
1057 sScript = cstScript1
& psScript
& cstScript2
& psLanguage
& cstScript3
& SCRIPTISPERSOXT
1058 Set oScriptProvider = SF_Utils._GetUNOService(
"ScriptProvider
", SCRIPTISPERSOXT)
1059 Set oScript = oScriptProvider.getScript(sScript)
1062 On Local Error GoTo CatchNotFound
1063 If IsNull(oScript) Then
1064 If psScope = SCRIPTISOXT Then psScope = SCRIPTISSHAROXT
1065 Set oScriptProvider = SF_Utils._GetUNOService(
"ScriptProvider
", psScope)
1066 Set oScript = oScriptProvider.getScript(sScript)
1070 _GetScript = oScript
1073 SF_Exception.RaiseFatal(NOSCRIPTERROR, psLanguage,
"Scope
", psScope,
"Script
", psScript)
1075 End Function
' ScriptForge.SF_Session._GetScript
1077 REM =============================================== END OF SCRIPTFORGE.SF_SESSION