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_Utils" 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_Utils
13 ''' ========
14 ''' FOR INTERNAL USE ONLY
15 ''' Groups all private functions used by the official modules
16 ''' Declares the Global variable _SF_
17 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
19 REM ===================================================================== GLOBALS
21 Global _SF_ As Variant
' SF_Root (Basic) object)
23 ''' ScriptForge version
24 Const SF_Version =
"7.5"
26 ''' Standard symbolic names for VarTypes
36 ''' Additional symbolic names for VarTypes
37 Global Const V_OBJECT =
9
38 Global Const V_BOOLEAN =
11
39 Global Const V_VARIANT =
12
40 Global Const V_BYTE =
17
41 Global Const V_USHORT =
18
42 Global Const V_ULONG =
19
43 Global Const V_BIGINT =
35
44 Global Const V_DECIMAL =
37
45 Global Const V_ARRAY =
8192
46 ''' Fictive VarTypes
47 Global Const V_NUMERIC =
99 ' Synonym of any numeric value [returned by _VarTypeExt()]
48 Global Const V_NOTHING =
101 ' Object categories [returned by _VarTypeObj()] Null object
49 Global Const V_UNOOBJECT =
102 ' Uno object or Uno structure
50 Global Const V_SFOBJECT =
103 ' ScriptForge object: has ObjectType and ServiceName properties
51 Global Const V_BASICOBJECT =
104 ' User Basic object
53 Type _ObjectDescriptor
' Returned by the _VarTypeObj() method
54 iVarType As Integer
' One of the V_NOTHING, V_xxxOBJECT constants
55 sObjectType As String
' Either
"" or
"com.sun.star...
" or a ScriptForge object type (ex.
"SF_SESSION
" or
"DICTIONARY
")
56 sServiceName As String
' Either
"" or the service name of a ScriptForge object type (ex.
"ScriptForge.Exception
"-
59 REM ================================================================== EXCEPTIONS
61 Const MISSINGARGERROR =
"MISSINGARGERROR
" ' A mandatory argument is missing
62 Const ARGUMENTERROR =
"ARGUMENTERROR
" ' An argument does not pass the _Validate() validation
63 Const ARRAYERROR =
"ARRAYERROR
" ' An argument does not pass the _ValidateArray() validation
64 Const FILEERROR =
"FILEERROR
" ' An argument does not pass the _ValidateFile() validation
66 REM =========================================pvA==================== PRIVATE METHODS
68 REM -----------------------------------------------------------------------------
69 Public Function _CDateToIso(pvDate As Variant) As Variant
70 ''' Returns a string representation of the given Basic date
71 ''' Dates as strings are essential in property values, where Basic dates are evil
73 Dim sIsoDate As Variant
' Return value
75 If VarType(pvDate) = V_DATE Then
76 If Year(pvDate)
< 1900 Then
' Time only
77 sIsoDate = Right(
"0" & Hour(pvDate),
2)
& ":
" & Right(
"0" & Minute(pvDate),
2)
& ":
" & Right(
"0" & Second(pvDate),
2)
78 ElseIf Hour(pvDate) + Minute(pvDate) + Second(pvDate) =
0 Then
' Date only
79 sIsoDate = Year(pvDate)
& "-
" & Right(
"0" & Month(pvDate),
2)
& "-
" & Right(
"0" & Day(pvDate),
2)
81 sIsoDate = Year(pvDate)
& "-
" & Right(
"0" & Month(pvDate),
2)
& "-
" & Right(
"0" & Day(pvDate),
2) _
82 & " " & Right(
"0" & Hour(pvDate),
2)
& ":
" & Right(
"0" & Minute(pvDate),
2) _
83 & ":
" & Right(
"0" & Second(pvDate),
2)
89 _CDateToIso = sIsoDate
91 End Function
' ScriptForge.SF_Utils._CDateToIso
93 REM -----------------------------------------------------------------------------
94 Public Function _CDateToUnoDate(pvDate As Variant) As Variant
95 ''' Returns a UNO com.sun.star.util.DateTime/Date/Time object depending on the given date
96 ''' by using the appropriate CDateToUnoDateXxx builtin function
97 ''' UNO dates are essential in property values, where Basic dates are evil
99 Dim vUnoDate As Variant
' Return value
101 If VarType(pvDate) = V_DATE Then
102 If Year(pvDate)
< 1900 Then
103 vUnoDate = CDateToUnoTime(pvDate)
104 ElseIf Hour(pvDate) + Minute(pvDate) + Second(pvDate) =
0 Then
105 vUnoDate = CDateToUnoDate(pvDate)
107 vUnoDate = CDateToUnoDateTime(pvDate)
113 _CDateToUnoDate = vUnoDate
115 End Function
' ScriptForge.SF_Utils._CDateToUnoDate
117 REM -----------------------------------------------------------------------------
118 Public Function _CPropertyValue(ByRef pvValue As Variant) As Variant
119 ''' Set a value of a correct type in a com.sun.star.beans.PropertyValue
120 ''' Date BASIC variables give error. Change them to UNO types
121 ''' Empty arrays should be replaced by Null
123 Dim vValue As Variant
' Return value
125 If VarType(pvValue) = V_DATE Then
126 vValue = SF_Utils._CDateToUnoDate(pvValue)
127 ElseIf IsArray(pvValue) Then
128 If UBound(pvValue,
1)
< LBound(pvValue,
1) Then vValue = Null Else vValue = pvValue
132 _CPropertyValue() = vValue
134 End Function
' ScriptForge.SF_Utils._CPropertyValue
136 REM -----------------------------------------------------------------------------
137 Public Function _CStrToDate(ByRef pvStr As String) As Date
138 ''' Attempt to convert the input string to a Date variable with the CDate builtin function
139 ''' If not successful, returns conventionally -
1 (
29/
12/
1899)
140 ''' Date patterns: YYYY-MM-DD, HH:MM:DD and YYYY-MM-DD HH:MM:DD
142 Dim dDate As Date
' Return value
147 On Local Error Resume Next
153 End Function
' ScriptForge.SF_Utils._CStrToDate
155 REM -----------------------------------------------------------------------------
156 Public Function _EnterFunction(ByVal psSub As String, Optional ByVal psArgs As String)
157 ''' Called on top of each public function
158 ''' Used to trace routine in/outs (debug mode)
159 ''' and to allow the explicit mention of the user call which caused an error
160 ''' Args:
161 ''' psSub = the called Sub/Function/Property, usually something like
"service.sub
"
162 ''' Return: True when psSub is called from a user script
163 ''' Used to bypass the validation of the arguments when unnecessary
165 If IsEmpty(_SF_) Or IsNull(_SF_) Then SF_Utils._InitializeRoot()
' First use of ScriptForge during current LibO session
166 If IsMissing(psArgs) Then psArgs =
""
168 If .StackLevel =
0 Then
169 .MainFunction = psSub
170 .MainFunctionArgs = psArgs
171 _EnterFunction = True
173 _EnterFunction = False
175 .StackLevel = .StackLevel +
1
176 If .DebugMode Then ._AddToConsole(
"==
> " & psSub
& "(
" & .StackLevel
& ")
")
179 End Function
' ScriptForge.SF_Utils._EnterFunction
181 REM -----------------------------------------------------------------------------
182 Public Function _ErrorHandling(Optional ByVal pbErrorHandler As Boolean) As Boolean
183 ''' Error handling is normally ON and can be set OFF for debugging purposes
184 ''' Each user visible routine starts with a call to this function to enable/disable
185 ''' standard handling of internal errors
186 ''' Args:
187 ''' pbErrorHandler = if present, set its value
188 ''' Return: the current value of the error handler
190 If IsEmpty(_SF_) Or IsNull(_SF_) Then SF_Utils._InitializeRoot()
' First use of ScriptForge during current LibO session
191 If Not IsMissing(pbErrorHandler) Then _SF_.ErrorHandler = pbErrorHandler
192 _ErrorHandling = _SF_.ErrorHandler
194 End Function
' ScriptForge.SF_Utils._ErrorHandling
196 REM -----------------------------------------------------------------------------
197 Public Sub _ExitFunction(ByVal psSub As String)
198 ''' Called in the Finally block of each public function
199 ''' Manage ScriptForge internal aborts
200 ''' Resets MainFunction (root) when exiting the method called by a user script
201 ''' Used to trace routine in/outs (debug mode)
202 ''' Args:
203 ''' psSub = the called Sub/Function/Property, usually something like
"service.sub
"
205 If IsEmpty(_SF_) Or IsNull(_SF_) Then SF_Utils._InitializeRoot()
' Useful only when current module has been recompiled
208 SF_Exception.RaiseAbort(psSub)
210 If .StackLevel =
1 Then
211 .MainFunction =
""
212 .MainFunctionArgs =
""
214 If .DebugMode Then ._AddToConsole(
"<==
" & psSub
& "(
" & .StackLevel
& ")
")
215 If .StackLevel
> 0 Then .StackLevel = .StackLevel -
1
218 End Sub
' ScriptForge.SF_Utils._ExitFunction
220 REM -----------------------------------------------------------------------------
221 Public Sub _ExportScriptForgePOTFile(ByVal FileName As String)
222 ''' Export the ScriptForge POT file related to its own user interface
223 ''' Should be called only before issuing new ScriptForge releases only
224 ''' Args:
225 ''' FileName: the resulting file. If it exists, is overwritten without warning
227 Dim sHeader As String
' The specific header to insert
229 sHeader =
"" _
230 & "*********************************************************************\n
" _
231 & "*** The ScriptForge library and its associated libraries ***\n
" _
232 & "*** are part of the LibreOffice project. ***\n
" _
233 & "*********************************************************************\n
" _
234 & "\n
" _
235 & "ScriptForge Release
" & SF_Version
& "\n
" _
236 & "-----------------------
"
240 If Not IsNull(.LocalizedInterface) Then .LocalizedInterface.Dispose()
241 ._LoadLocalizedInterface(psMode :=
"ADDTEXT
")
' Force reload of labels from the code
242 .LocalizedInterface.ExportToPOTFile(FileName, Header := sHeader)
247 End Sub
' ScriptForge.SF_Utils._ExportScriptForgePOTFile
249 REM -----------------------------------------------------------------------------
250 Public Function _GetPropertyValue(ByRef pvArgs As Variant, ByVal psName As String) As Variant
251 ''' Returns the Value corresponding to the given name
252 ''' Args
253 ''' pvArgs: a zero_based array of PropertyValues
254 ''' psName: the comparison is not case-sensitive
255 ''' Returns:
256 ''' Zero-length string if not found
258 Dim vValue As Variant
' Return value
261 vValue =
""
262 If IsArray(pvArgs) Then
263 For i = LBound(pvArgs) To UBound(pvArgs)
264 If UCase(psName) = UCase(pvArgs(i).Name) Then
265 vValue = pvArgs(i).Value
270 _GetPropertyValue = vValue
272 End Function
' ScriptForge.SF_Utils._GetPropertyValue
274 REM -----------------------------------------------------------------------------
275 Public Function _GetRegistryKeyContent(ByVal psKeyName as string _
276 , Optional pbForUpdate as Boolean _
278 ''' Implement a ConfigurationProvider service
279 ''' Derived from the Tools library
280 ''' Args:
281 ''' psKeyName: the name of the node in the configuration tree
282 ''' pbForUpdate: default = False
284 Dim oConfigProvider as Object
' com.sun.star.configuration.ConfigurationProvider
285 Dim vNodePath(
0) as New com.sun.star.beans.PropertyValue
286 Dim sConfig As String
' One of next
2 constants
287 Const cstConfig =
"com.sun.star.configuration.ConfigurationAccess
"
288 Const cstConfigUpdate =
"com.sun.star.configuration.ConfigurationUpdateAccess
"
290 Set oConfigProvider = _GetUNOService(
"ConfigurationProvider
")
291 vNodePath(
0).Name =
"nodepath
"
292 vNodePath(
0).Value = psKeyName
294 If IsMissing(pbForUpdate) Then pbForUpdate = False
295 If pbForUpdate Then sConfig = cstConfigUpdate Else sConfig = cstConfig
297 Set _GetRegistryKeyContent = oConfigProvider.createInstanceWithArguments(sConfig, vNodePath())
299 End Function
' ScriptForge.SF_Utils._GetRegistryKeyContent
301 REM -----------------------------------------------------------------------------
302 Private Function _GetSetting(ByVal psPreference As String, psProperty As String) As Variant
303 ''' Find in the configuration a specific setting based on its location in the
304 ''' settings registry
306 Dim oConfigProvider As Object
' com.sun.star.configuration.ConfigurationProvider
307 Dim vNodePath As Variant
' Array of com.sun.star.beans.PropertyValue
309 ' Derived from the Tools library
310 Set oConfigProvider = createUnoService(
"com.sun.star.configuration.ConfigurationProvider
")
311 vNodePath = Array(SF_Utils._MakePropertyValue(
"nodepath
", psPreference))
313 _GetSetting = oConfigProvider.createInstanceWithArguments( _
314 "com.sun.star.configuration.ConfigurationAccess
", vNodePath()).getByName(psProperty)
316 End Function
' ScriptForge.SF_Utils._GetSetting
318 REM -----------------------------------------------------------------------------
319 Public Function _GetUNOService(ByVal psService As String _
320 , Optional ByVal pvArg As Variant _
322 ''' Create a UNO service
323 ''' Each service is called only once
324 ''' Args:
325 ''' psService: shortcut to service
326 ''' pvArg: some services might require an argument
328 Dim sLocale As String
' fr-BE f.i.
329 Dim oDefaultContext As Object
331 Set _GetUNOService = Nothing
333 Select Case psService
334 Case
"BrowseNodeFactory
"
335 Set oDefaultContext = GetDefaultContext()
336 If Not IsNull(oDefaultContext) Then Set _GetUNOService = oDefaultContext.getValueByName(
"/singletons/com.sun.star.script.browse.theBrowseNodeFactory
")
337 Case
"CalendarImpl
"
338 If IsEmpty(.CalendarImpl) Or IsNull(.CalendarImpl) Then
339 Set .CalendarImpl = CreateUnoService(
"com.sun.star.i18n.CalendarImpl
")
341 Set _GetUNOService = .CalendarImpl
342 Case
"CharacterClass
"
343 If IsEmpty(.CharacterClass) Or IsNull(.CharacterClass) Then
344 Set .CharacterClass = CreateUnoService(
"com.sun.star.i18n.CharacterClassification
")
346 Set _GetUNOService = .CharacterClass
347 Case
"ConfigurationProvider
"
348 If IsEmpty(.ConfigurationProvider) Or IsNull(.ConfigurationProvider) Then
349 Set .ConfigurationProvider = CreateUnoService(
"com.sun.star.configuration.ConfigurationProvider
")
351 Set _GetUNOService = .ConfigurationProvider
352 Case
"CoreReflection
"
353 If IsEmpty(.CoreReflection) Or IsNull(.CoreReflection) Then
354 Set .CoreReflection = CreateUnoService(
"com.sun.star.reflection.CoreReflection
")
356 Set _GetUNOService = .CoreReflection
357 Case
"DatabaseContext
"
358 If IsEmpty(.DatabaseContext) Or IsNull(.DatabaseContext) Then
359 Set .DatabaseContext = CreateUnoService(
"com.sun.star.sdb.DatabaseContext
")
361 Set _GetUNOService = .DatabaseContext
362 Case
"DispatchHelper
"
363 If IsEmpty(.DispatchHelper) Or IsNull(.DispatchHelper) Then
364 Set .DispatchHelper = CreateUnoService(
"com.sun.star.frame.DispatchHelper
")
366 Set _GetUNOService = .DispatchHelper
367 Case
"FileAccess
"
368 If IsEmpty(.FileAccess) Or IsNull(.FileAccess) Then
369 Set .FileAccess = CreateUnoService(
"com.sun.star.ucb.SimpleFileAccess
")
371 Set _GetUNOService = .FileAccess
372 Case
"FilePicker
"
373 Set .FilePicker = CreateUnoService(
"com.sun.star.ui.dialogs.FilePicker
")
' Do not reuse an existing FilePicker: TDF#
154462
374 Set _GetUNOService = .FilePicker
375 Case
"FilterFactory
"
376 If IsEmpty(.FilterFactory) Or IsNull(.FilterFactory) Then
377 Set .FilterFactory = CreateUnoService(
"com.sun.star.document.FilterFactory
")
379 Set _GetUNOService = .FilterFactory
380 Case
"FolderPicker
"
381 If IsEmpty(.FolderPicker) Or IsNull(.FolderPicker) Then
382 Set .FolderPicker = CreateUnoService(
"com.sun.star.ui.dialogs.FolderPicker
")
384 Set _GetUNOService = .FolderPicker
385 Case
"FormatLocale
"
386 If IsEmpty(.FormatLocale) Or IsNull(.FormatLocale) Then
387 .FormatLocale = CreateUnoStruct(
"com.sun.star.lang.Locale
")
388 ' 1st and
2nd chance
389 sLocale = SF_Utils._GetSetting(
"org.openoffice.Setup/L10N
",
"ooSetupSystemLocale
")
390 If Len(sLocale) =
0 Then sLocale = SF_Utils._GetSetting(
"org.openoffice.System/L10N
",
"UILocale
")
391 .FormatLocale.Language = Split(sLocale,
"-
")(
0)
' Language is most often
2 chars long, but not always
392 .FormatLocale.Country = Right(sLocale,
2)
394 Set _GetUNOService = .FormatLocale
395 Case
"FunctionAccess
"
396 If IsEmpty(.FunctionAccess) Or IsNull(.FunctionAccess) Then
397 Set .FunctionAccess = CreateUnoService(
"com.sun.star.sheet.FunctionAccess
")
399 Set _GetUNOService = .FunctionAccess
400 Case
"GraphicExportFilter
"
401 If IsEmpty(.GraphicExportFilter) Or IsNull(.GraphicExportFilter) Then
402 Set .GraphicExportFilter = CreateUnoService(
"com.sun.star.drawing.GraphicExportFilter
")
404 Set _GetUNOService = .GraphicExportFilter
405 Case
"Introspection
"
406 If IsEmpty(.Introspection) Or IsNull(.Introspection) Then
407 Set .Introspection = CreateUnoService(
"com.sun.star.beans.Introspection
")
409 Set _GetUNOService = .Introspection
410 Case
"LocaleData
"
411 If IsEmpty(.LocaleData) Or IsNull(.LocaleData) Then
412 Set .LocaleData = CreateUnoService(
"com.sun.star.i18n.LocaleData
")
414 Set _GetUNOService = .LocaleData
415 Case
"MacroExpander
"
416 Set oDefaultContext = GetDefaultContext()
417 If Not IsNull(oDefaultContext) Then Set _GetUNOService = oDefaultContext.getValueByName(
"/singletons/com.sun.star.util.theMacroExpander
")
418 Case
"MailService
"
419 If IsEmpty(.MailService) Or IsNull(.MailService) Then
420 If GetGuiType =
1 Then
' Windows
421 Set .MailService = CreateUnoService(
"com.sun.star.system.SimpleSystemMail
")
423 Set .MailService = CreateUnoService(
"com.sun.star.system.SimpleCommandMail
")
426 Set _GetUNOService = .MailService
427 Case
"Number2Text
"
428 If IsEmpty(.Number2Text) Or IsNull(.Number2Text) Then
429 Set .Number2Text = CreateUnoService(
"com.sun.star.linguistic2.NumberText
")
431 Set _GetUNOService = .Number2Text
432 Case
"OfficeLocale
"
433 If IsEmpty(.OfficeLocale) Or IsNull(.OfficeLocale) Then
434 .OfficeLocale = CreateUnoStruct(
"com.sun.star.lang.Locale
")
435 ' 1st and
2nd chance
436 sLocale = SF_Utils._GetSetting(
"org.openoffice.Setup/L10N
",
"ooLocale
")
437 If Len(sLocale) =
0 Then sLocale = SF_Utils._GetSetting(
"org.openoffice.System/L10N
",
"UILocale
")
438 .OfficeLocale.Language = Split(sLocale,
"-
")(
0)
' Language is most often
2 chars long, but not always
439 .OfficeLocale.Country = Right(sLocale,
2)
441 Set _GetUNOService = .OfficeLocale
442 Case
"PackageInformationProvider
"
443 If IsEmpty(.PackageProvider) Or IsNull(.PackageProvider) Then
444 Set .PackageProvider = GetDefaultContext.getByName(
"/singletons/com.sun.star.deployment.PackageInformationProvider
")
446 Set _GetUNOService = .PackageProvider
447 Case
"PathSettings
"
448 If IsEmpty(.PathSettings) Or IsNull(.PathSettings) Then
449 Set .PathSettings = CreateUnoService(
"com.sun.star.util.PathSettings
")
451 Set _GetUNOService = .PathSettings
452 Case
"PathSubstitution
"
453 If IsEmpty(.PathSubstitution) Or IsNull(.PathSubstitution) Then
454 Set .PathSubstitution = CreateUnoService(
"com.sun.star.util.PathSubstitution
")
456 Set _GetUNOService = .PathSubstitution
457 Case
"PrinterServer
"
458 If IsEmpty(.PrinterServer) Or IsNull(.PrinterServer) Then
459 Set .PrinterServer = CreateUnoService(
"com.sun.star.awt.PrinterServer
")
461 Set _GetUNOService = .PrinterServer
462 Case
"ScriptProvider
"
463 If IsMissing(pvArg) Then pvArg = SF_Session.SCRIPTISAPPLICATION
464 Select Case LCase(pvArg)
465 Case SF_Session.SCRIPTISEMBEDDED
' Document
466 If Not IsNull(ThisComponent) Then Set _GetUNOService = ThisComponent.getScriptProvider()
468 If IsEmpty(.ScriptProvider) Or IsNull(.ScriptProvider) Then
469 Set .ScriptProvider = _
470 CreateUnoService(
"com.sun.star.script.provider.MasterScriptProviderFactory
").createScriptProvider(
"")
472 Set _GetUNOService = .ScriptProvider
474 Case
"SearchOptions
"
475 If IsEmpty(.SearchOptions) Or IsNull(.SearchOptions) Then
476 Set .SearchOptions = New com.sun.star.util.SearchOptions
478 .algorithmType = com.sun.star.util.SearchAlgorithms.REGEXP
482 Set _GetUNOService = .SearchOptions
483 Case
"SystemLocale
",
"Locale
"
484 If IsEmpty(.SystemLocale) Or IsNull(.SystemLocale) Then
485 .SystemLocale = CreateUnoStruct(
"com.sun.star.lang.Locale
")
486 sLocale = SF_Utils._GetSetting(
"org.openoffice.System/L10N
",
"SystemLocale
")
487 .SystemLocale.Language = Split(sLocale,
"-
")(
0)
' Language is most often
2 chars long, but not always
488 .SystemLocale.Country = Right(sLocale,
2)
490 Set _GetUNOService = .SystemLocale
491 Case
"SystemShellExecute
"
492 If IsEmpty(.SystemShellExecute) Or IsNull(.SystemShellExecute) Then
493 Set .SystemShellExecute = CreateUnoService(
"com.sun.star.system.SystemShellExecute
")
495 Set _GetUNOService = .SystemShellExecute
496 Case
"TextSearch
"
497 If IsEmpty(.TextSearch) Or IsNull(.TextSearch) Then
498 Set .TextSearch = CreateUnoService(
"com.sun.star.util.TextSearch
")
500 Set _GetUNOService = .TextSearch
501 Case
"Toolkit
"
502 If IsEmpty(.Toolkit) Or IsNull(.Toolkit) Then
503 Set .Toolkit = CreateUnoService(
"com.sun.star.awt.Toolkit
")
505 Set _GetUNOService = .Toolkit
506 Case
"URLTransformer
"
507 If IsEmpty(.URLTransformer) Or IsNull(.URLTransformer) Then
508 Set .URLTransformer = CreateUnoService(
"com.sun.star.util.URLTransformer
")
510 Set _GetUNOService = .URLTransformer
515 End Function
' ScriptForge.SF_Utils._GetUNOService
517 REM -----------------------------------------------------------------------------
518 Public Sub _InitializeRoot(Optional ByVal pbForce As Boolean)
519 ''' Initialize _SF_ as SF_Root basic object
520 ''' Args:
521 ''' pbForce = True forces the reinit (default = False)
523 If IsMissing(pbForce) Then pbForce = False
524 If pbForce Then Set _SF_ = Nothing
525 If IsEmpty(_SF_) Or IsNull(_SF_) Then
526 Set _SF_ = New SF_Root
530 End Sub
' ScriptForge.SF_Utils._InitializeRoot
532 REM -----------------------------------------------------------------------------
533 Public Function _MakePropertyValue(ByVal psName As String _
534 , ByRef pvValue As Variant _
535 ) As com.sun.star.beans.PropertyValue
536 ''' Create and return a new com.sun.star.beans.PropertyValue
538 Dim oPropertyValue As New com.sun.star.beans.PropertyValue
542 .Value = SF_Utils._CPropertyValue(pvValue)
544 _MakePropertyValue() = oPropertyValue
546 End Function
' ScriptForge.SF_Utils._MakePropertyValue
548 REM -----------------------------------------------------------------------------
549 Public Function _Repr(ByVal pvArg As Variant, Optional ByVal plMax As Long) As String
550 ''' Convert pvArg into a readable string (truncated if length
> plMax)
551 ''' Args
552 ''' pvArg: may be of any type
553 ''' plMax: maximum length of the resulting string (default =
32K)
555 Dim sArg As String
' Return value
556 Dim oObject As Object
' Alias of argument to avoid
"Object variable not set
"
557 Dim oObjectDesc As Object
' Object descriptor
558 Dim sLength As String
' String length as a string
560 Const cstBasicObject =
"com.sun.star.script.NativeObjectWrapper
"
562 Const cstMaxLength =
2^
15 -
1 ' 32767
563 Const cstByteLength =
25
564 Const cstEtc =
" …
"
566 If IsMissing(plMax) Then plMax = cstMaxLength
567 If plMax =
0 Then plMax = cstMaxLength
568 If IsArray(pvArg) Then
569 sArg = SF_Array._Repr(pvArg)
571 Select Case VarType(pvArg)
572 Case V_EMPTY : sArg =
"[EMPTY]
"
573 Case V_NULL : sArg =
"[NULL]
"
575 Set oObjectDesc = SF_Utils._VarTypeObj(pvArg)
577 Select Case .iVarType
578 Case V_NOTHING : sArg =
"[NOTHING]
"
579 Case V_OBJECT, V_BASICOBJECT
580 sArg =
"[OBJECT]
"
581 Case V_UNOOBJECT : sArg =
"[
" & .sObjectType
& "]
"
583 If Left(.sObjectType,
3) =
"SF_
" Then
' Standard module
584 sArg =
"[
" & .sObjectType
& "]
"
585 Else
' Class module must have a _Repr() method
587 sArg = oObject._Repr()
591 Case V_VARIANT : sArg =
"[VARIANT]
"
593 sArg = SF_String._Repr(pvArg)
594 Case V_BOOLEAN : sArg = Iif(pvArg,
"[TRUE]
",
"[FALSE]
")
595 Case V_BYTE : sArg = Right(
"00" & Hex(pvArg),
2)
596 Case V_SINGLE, V_DOUBLE, V_CURRENCY
598 If InStr(
1, sArg,
"E
",
1) =
0 Then sArg = Format(pvArg,
"##
0.0##
")
599 sArg = Replace(sArg,
",
",
".
")
'Force decimal point
600 Case V_BIGINT : sArg = CStr(CLng(pvArg))
601 Case V_DATE : sArg = _CDateToIso(pvArg)
602 Case Else : sArg = CStr(pvArg)
605 If Len(sArg)
> plMax Then
606 sLength =
"(
" & Len(sArg)
& ")
"
607 sArg = Left(sArg, plMax - Len(cstEtc) - Len(slength))
& cstEtc
& sLength
611 End Function
' ScriptForge.SF_Utils._Repr
613 REM -----------------------------------------------------------------------------
614 Private Function _ReprValues(Optional ByVal pvArgs As Variant _
615 , Optional ByVal plMax As Long _
617 ''' Convert an array of values to a comma-separated list of readable strings
619 Dim sValues As String
' Return value
620 Dim sValue As String
' A single value
621 Dim vValue As Variant
' A single item in the argument
622 Dim i As Long
' Items counter
623 Const cstMax =
20 ' Maximum length of single string
624 Const cstContinue =
"…
" ' Unicode continuation char U+
2026
626 _ReprValues =
""
627 If IsMissing(pvArgs) Then Exit Function
628 If Not IsArray(pvArgs) Then pvArgs = Array(pvArgs)
629 sValues =
""
630 For i =
0 To UBound(pvArgs)
633 If VarType(vValue) = V_STRING Then sValue =
"""" & vValue
& """" Else sValue = SF_Utils._Repr(vValue, cstMax)
634 If Len(sValues) =
0 Then sValues = sValue Else sValues = sValues
& ",
" & sValue
635 ElseIf i
< UBound(pvArgs) Then
636 sValues = sValues
& ",
" & cstContinue
640 _ReprValues = sValues
642 End Function
' ScriptForge.SF_Utils._ReprValues
644 REM -----------------------------------------------------------------------------
645 Public Function _SetPropertyValue(ByVal pvPropertyValue As Variant _
646 , ByVal psName As String _
647 , ByRef pvValue As Variant _
649 ''' Return the
1st argument (passed by reference), which is an array of property values
650 ''' If the property psName exists, update it with pvValue, otherwise create it on top of the returned array
652 Dim oPropertyValue As New com.sun.star.beans.PropertyValue
653 Dim lIndex As Long
' Found entry
654 Dim vValue As Variant
' Alias of pvValue
655 Dim vProperties As Variant
' Alias of pvPropertyValue
659 vProperties = pvPropertyValue
660 For i =
0 To UBound(vProperties)
661 If vProperties(i).Name = psName Then
666 If lIndex
< 0 Then
' Not found
667 lIndex = UBound(vProperties) +
1
668 ReDim Preserve vProperties(
0 To lIndex)
669 Set oPropertyValue = SF_Utils._MakePropertyValue(psName, pvValue)
670 vProperties(lIndex) = oPropertyValue
671 vProperties = vProperties
672 Else
' psName exists already in array of property values
673 vProperties(lIndex).Value = SF_Utils._CPropertyValue(pvValue)
676 _SetPropertyValue = vProperties
678 End Function
' ScriptForge.SF_Utils._SetPropertyValue
680 REM -----------------------------------------------------------------------------
681 Private Function _TypeNames(Optional ByVal pvArgs As Variant) As String
682 ''' Converts the array of VarTypes to a comma-separated list of TypeNames
684 Dim sTypes As String
' Return value
685 Dim sType As String
' A single type
686 Dim iType As Integer
' A single item of the argument
688 _TypeNames =
""
689 If IsMissing(pvArgs) Then Exit Function
690 If Not IsArray(pvArgs) Then pvArgs = Array(pvArgs)
691 sTypes =
""
692 For Each iType In pvArgs
694 Case V_EMPTY : sType =
"Empty
"
695 Case V_NULL : sType =
"Null
"
696 Case V_INTEGER : sType =
"Integer
"
697 Case V_LONG : sType =
"Long
"
698 Case V_SINGLE : sType =
"Single
"
699 Case V_DOUBLE : sType =
"Double
"
700 Case V_CURRENCY : sType =
"Currency
"
701 Case V_DATE : sType =
"Date
"
702 Case V_STRING : sType =
"String
"
703 Case V_OBJECT : sType =
"Object
"
704 Case V_BOOLEAN : sType =
"Boolean
"
705 Case V_VARIANT : sType =
"Variant
"
706 Case V_DECIMAL : sType =
"Decimal
"
707 Case
>= V_ARRAY : sType =
"Array
"
708 Case V_NUMERIC : sType =
"Numeric
"
710 If Len(sTypes) =
0 Then sTypes = sType Else sTypes = sTypes
& ",
" & sType
714 End Function
' ScriptForge.SF_Utils._TypeNames
716 REM -----------------------------------------------------------------------------
717 Public Function _Validate(Optional ByRef pvArgument As Variant _
718 , ByVal psName As String _
719 , Optional ByVal pvTypes As Variant _
720 , Optional ByVal pvValues As Variant _
721 , Optional ByVal pvRegex As Variant _
722 , Optional ByVal pvObjectType As Variant _
724 ''' Validate the arguments set by user scripts
725 ''' The arguments of the function define the validation rules
726 ''' This function ignores arrays. Use _ValidateArray instead
727 ''' Args:
728 ''' pvArgument: the argument to (in)validate
729 ''' psName: the documented name of the argument (can be inserted in an error message)
730 ''' pvTypes: array of allowed VarTypes
731 ''' pvValues: array of allowed values
732 ''' pvRegex: regular expression to comply with
733 ''' pvObjectType: mandatory Basic class
734 ''' Return: True if validation OK
735 ''' Otherwise an error is raised
736 ''' Exceptions:
737 ''' ARGUMENTERROR
739 Dim iVarType As Integer
' Extended VarType of argument
740 Dim bValid As Boolean
' Returned value
741 Dim oObjectDescriptor As Object
' _ObjectDescriptor type
742 Const cstMaxLength =
256 ' Maximum length of readable value
743 Const cstMaxValues =
10 ' Maximum number of allowed items to list in an error message
745 ' To avoid useless recursions, keep main function, only increase stack depth
746 _SF_.StackLevel = _SF_.StackLevel +
1
747 On Local Error GoTo Finally
' Do never interrupt
751 If IsMissing(pvArgument) Then GoTo CatchMissing
752 If IsMissing(pvRegex) Or IsEmpty(pvRegex) Then pvRegex =
""
753 If IsMissing(pvObjectType) Or IsEmpty(pvObjectType) Then pvObjectType =
""
754 iVarType = SF_Utils._VarTypeExt(pvArgument)
756 ' Arrays NEVER pass validation
757 If iVarType
>= V_ARRAY Then
760 ' Check existence of argument
761 bValid = iVarType
<> V_NULL And iVarType
<> V_EMPTY
762 ' Check if argument
's VarType is valid
763 If bValid And Not IsMissing(pvTypes) Then
764 If Not IsArray(pvTypes) Then bValid = ( pvTypes = iVarType ) Else bValid = SF_Array.Contains(pvTypes, iVarType)
766 ' Check if argument
's value is valid
767 If bValid And Not IsMissing(pvValues) Then
768 If Not IsArray(pvValues) Then pvValues = Array(pvValues)
769 bValid = SF_Array.Contains(pvValues, pvArgument, CaseSensitive := False)
771 ' Check regular expression
772 If bValid And Len(pvRegex)
> 0 And iVarType = V_STRING Then
773 If Len(pvArgument)
> 0 Then bValid = SF_String.IsRegex(pvArgument, pvRegex, CaseSensitive := False)
775 ' Check instance types
776 If bValid And Len(pvObjectType)
> 0 And iVarType = V_OBJECT Then
777 'Set oArgument = pvArgument
778 Set oObjectDescriptor = SF_Utils._VarTypeObj(pvArgument)
779 bValid = ( oObjectDescriptor.iVarType = V_SFOBJECT )
780 If bValid Then bValid = ( oObjectDescriptor.sObjectType = pvObjectType )
785 ''' Library: ScriptForge
786 ''' Service: Array
787 ''' Method: Contains
788 ''' Arguments: Array_1D, ToFind, [CaseSensitive=False], [SortOrder=
""]
789 ''' A serious error has been detected on argument SortOrder
790 ''' Rules: SortOrder is of type String
791 ''' SortOrder must contain one of next values:
"ASC
",
"DESC
",
""
792 ''' Actual value:
"Ascending
"
793 SF_Exception.RaiseFatal(ARGUMENTERROR _
794 , SF_Utils._Repr(pvArgument, cstMaxLength), psName, SF_Utils._TypeNames(pvTypes) _
795 , SF_Utils._ReprValues(pvValues, cstMaxValues), pvRegex, pvObjectType _
801 _SF_.StackLevel = _SF_.StackLevel -
1
805 SF_Exception.RaiseFatal(MISSINGARGERROR, psName)
807 End Function
' ScriptForge.SF_Utils._Validate
809 REM -----------------------------------------------------------------------------
810 Public Function _ValidateArray(Optional ByRef pvArray As Variant _
811 , ByVal psName As String _
812 , Optional ByVal piDimensions As Integer _
813 , Optional ByVal piType As Integer _
814 , Optional ByVal pbNotNull As Boolean _
816 ''' Validate the (array) arguments set by user scripts
817 ''' The arguments of the function define the validation rules
818 ''' This function ignores non-arrays. Use _Validate instead
819 ''' Args:
820 ''' pvArray: the argument to (in)validate
821 ''' psName: the documented name of the array (can be inserted in an error message)
822 ''' piDimensions: the # of dimensions the array must have.
0 = Any (default)
823 ''' piType: (default = -
1, i.e. not applicable)
824 ''' For
2D arrays, the
1st column is checked
825 ''' 0 =
> all items must be any out of next types: string, date or numeric,
826 ''' but homogeneously: all strings or all dates or all numeric
827 ''' V_STRING or V_DATE or V_NUMERIC =
> that specific type is required
828 ''' pbNotNull: piType must be
>=
0, otherwise ignored
829 ''' If True: Empty, Null items are rejected
830 ''' Return: True if validation OK
831 ''' Otherwise an error is raised
832 ''' Exceptions:
833 ''' ARRAYERROR
835 Dim iVarType As Integer
' VarType of argument
836 Dim vItem As Variant
' Array item
837 Dim iItemType As Integer
' VarType of individual items of argument
838 Dim iDims As Integer
' Number of dimensions of the argument
839 Dim bValid As Boolean
' Returned value
840 Dim iArrayType As Integer
' Static array type
841 Dim iFirstItemType As Integer
' Type of
1st non-null/empty item
842 Dim sType As String
' Allowed item types as a string
844 Const cstMaxLength =
256 ' Maximum length of readable value
846 ' To avoid useless recursions, keep main function, only increase stack depth
848 _SF_.StackLevel = _SF_.StackLevel +
1
849 On Local Error GoTo Finally
' Do never interrupt
853 If IsMissing(pvArray) Then GoTo CatchMissing
854 If IsMissing(piDimensions) Then piDimensions =
0
855 If IsMissing(piType) Then piType = -
1
856 If IsMissing(pbNotNull) Then pbNotNull = False
857 iVarType = VarType(pvArray)
859 ' Scalars NEVER pass validation
860 If iVarType
< V_ARRAY Then
863 ' Check dimensions
864 iDims = SF_Array.CountDims(pvArray)
865 If iDims
> 2 Then bValid = False
' Only
1D and
2D arrays
866 If bValid And piDimensions
> 0 Then
867 bValid = ( iDims = piDimensions Or (iDims =
0 And piDimensions =
1) )
' Allow empty vectors
869 ' Check VarType and Empty/Null status of the array items
870 If bValid And iDims =
1 And piType
>=
0 Then
871 iArrayType = SF_Array._StaticType(pvArray)
872 If (piType =
0 And iArrayType
> 0) Or (piType
> 0 And iArrayType = piType) Then
873 ' If static array of the right VarType ..., OK
875 ' Go through array and check individual items
877 For i = LBound(pvArray,
1) To UBound(pvArray,
1)
878 If iDims =
1 Then vItem = pvArray(i) Else vItem = pvArray(i, LBound(pvArray,
2))
879 iItemType = SF_Utils._VarTypeExt(vItem)
880 If iItemType
> V_NULL Then
' Exclude Empty and Null
881 ' Initialization at first non-null item
882 If iFirstItemType
< 0 Then
883 iFirstItemType = iItemType
884 If piType
> 0 Then bValid = ( iFirstItemType = piType ) Else bValid = SF_Array.Contains(Array(V_STRING, V_DATE, V_NUMERIC), iFirstItemType)
886 bValid = (iItemType = iFirstItemType)
889 bValid = Not pbNotNull
891 If Not bValid Then Exit For
898 ''' Library: ScriptForge
899 ''' Service: Array
900 ''' Method: Contains
901 ''' Arguments: Array_1D, ToFind, [CaseSensitive=False], [SortOrder=
""|
"ASC
"|
"DESC
"]
902 ''' An error was detected on argument Array_1D
903 ''' Rules: Array_1D is of type Array
904 ''' Array_1D must have maximum
1 dimension
905 ''' Array_1D must have all elements of the same type: either String, Date or Numeric
906 ''' Actual value: (
0:
2,
0:
3)
909 sType =
"String, Date, Numeric
"
910 ElseIf piType
> 0 Then
911 sType = SF_Utils._TypeNames(piType)
913 SF_Exception.RaiseFatal(ARRAYERROR _
914 , SF_Utils._Repr(pvArray, cstMaxLength), psName, piDimensions, sType, pbNotNull)
918 _ValidateArray = bValid
919 _SF_.StackLevel = _SF_.StackLevel -
1
923 SF_Exception.RaiseFatal(MISSINGARGERROR, psName)
925 End Function
' ScriptForge.SF_Utils._ValidateArray
927 REM -----------------------------------------------------------------------------
928 Public Function _ValidateFile(Optional ByRef pvArgument As Variant _
929 , ByVal psName As String _
930 , Optional ByVal pbWildCards As Boolean _
931 , Optional ByVal pbSpace As Boolean _
933 ''' Validate the argument as a valid FileName
934 ''' Args:
935 ''' pvArgument: the argument to (in)validate
936 ''' pbWildCards: if True, wildcard characters are accepted in the last component of the
1st argument
937 ''' pbSpace: if True, the argument may be an empty string. Default = False
938 ''' Return: True if validation OK
939 ''' Otherwise an error is raised
940 ''' Exceptions:
941 ''' ARGUMENTERROR
943 Dim iVarType As Integer
' VarType of argument
944 Dim sFile As String
' Alias for argument
945 Dim bValid As Boolean
' Returned value
946 Dim sFileNaming As String
' Alias of SF_FileSystem.FileNaming
947 Dim oArgument As Variant
' Workaround
"Object variable not set
" error on
1st executable statement
948 Const cstMaxLength =
256 ' Maximum length of readable value
950 ' To avoid useless recursions, keep main function, only increase stack depth
952 _SF_.StackLevel = _SF_.StackLevel +
1
953 On Local Error GoTo Finally
' Do never interrupt
957 If IsMissing(pvArgument) Then GoTo CatchMissing
958 If IsMissing(pbWildCards) Then pbWildCards = False
959 If IsMissing(pbSpace) Then pbSpace = False
960 iVarType = VarType(pvArgument)
962 ' Arrays NEVER pass validation
963 If iVarType
>= V_ARRAY Then
966 ' Argument must be a string containing a valid file name
967 bValid = ( iVarType = V_STRING )
969 bValid = ( Len(pvArgument)
> 0 Or pbSpace )
970 If bValid And Len(pvArgument)
> 0 Then
971 ' Wildcards are replaced by arbitrary alpha characters
973 sFile = Replace(Replace(pvArgument,
"?
",
"Z
"),
"*
",
"A
")
976 bValid = ( InStr(sFile,
"?
") + InStr(sFile,
"*
") =
0 )
978 ' Check file format without wildcards
981 sFileNaming = .FileNaming
982 Select Case sFileNaming
983 Case
"ANY
" : bValid = SF_String.IsUrl(ConvertToUrl(sFile))
984 Case
"URL
" : bValid = SF_String.IsUrl(sFile)
985 Case
"SYS
" : bValid = SF_String.IsFileName(sFile)
989 ' Check that wildcards are only present in last component
990 If bValid And pbWildCards Then
991 sFile = SF_FileSystem.GetParentFolderName(pvArgument)
992 bValid = ( InStr(sFile,
"*
") + InStr(sFile,
"?
") + InStr(sFile,
"%
3F
") =
0 )
' ConvertToUrl replaces ? by %
3F
999 ''' Library: ScriptForge
1000 ''' Service: FileSystem
1001 ''' Method: CopyFile
1002 ''' Arguments: Source, Destination
1003 ''' A serious error has been detected on argument Source
1004 ''' Rules: Source is of type String
1005 ''' Source must be a valid file name expressed in operating system notation
1006 ''' Source may contain one or more wildcard characters in its last component
1007 ''' Actual value: /home/jean-*/SomeFile.odt
1008 SF_Exception.RaiseFatal(FILEERROR _
1009 , SF_Utils._Repr(pvArgument, cstMaxLength), psName, pbWildCards)
1013 _ValidateFile = bValid
1014 _SF_.StackLevel = _SF_.StackLevel -
1
1018 SF_Exception.RaiseFatal(MISSINGARGERROR, psName)
1020 End Function
' ScriptForge.SF_Utils._ValidateFile
1022 REM -----------------------------------------------------------------------------
1023 Public Function _VarTypeExt(ByRef pvValue As Variant) As Integer
1024 ''' Return the VarType of the argument but all numeric types are aggregated into V_NUMERIC
1025 ''' Args:
1026 ''' pvValue: value to examine
1027 ''' Return:
1028 ''' The extended VarType
1030 Dim iType As Integer
' VarType of argument
1032 iType = VarType(pvValue)
1034 Case V_INTEGER, V_LONG, V_SINGLE, V_DOUBLE, V_CURRENCY, V_BIGINT, V_DECIMAL
1035 _VarTypeExt = V_NUMERIC
1036 Case Else : _VarTypeExt = iType
1039 End Function
' ScriptForge.SF_Utils._VarTypeExt
1041 REM -----------------------------------------------------------------------------
1042 Public Function _VarTypeObj(ByRef pvValue As Variant) As Object
1043 ''' Inspect the argument that is supposed to be an Object
1044 ''' Return the internal type of object as one of the values
1045 ''' V_NOTHING Null object
1046 ''' V_UNOOBJECT Uno object or Uno structure
1047 ''' V_SFOBJECT ScriptForge object: has ObjectType and ServiceName properties
1048 ''' V_BASICOBJECT User Basic object
1049 ''' coupled with object type as a string (
"com.sun.star...
" or
"SF_...
" or
"... ScriptForge class ...
")
1050 ''' When the argument is not an Object, return the usual VarType() of the argument
1052 Dim oObjDesc As _ObjectDescriptor
' Return value
1053 Dim oValue As Object
' Alias of pvValue used to avoid
"Object variable not set
" error
1054 Dim sObjType As String
' The type of object is first derived as a string
1055 Dim oReflection As Object
' com.sun.star.reflection.CoreReflection
1056 Dim vClass As Variant
' com.sun.star.reflection.XIdlClass
1057 Dim bUno As Boolean
' True when object recognized as UNO object
1059 Const cstBasicClass =
"com.sun.star.script.NativeObjectWrapper
" ' Way to recognize Basic objects
1061 On Local Error Resume Next
' Object type is established by trial and error
1065 .iVarType = VarType(pvValue)
1066 .sObjectType =
""
1067 .sServiceName =
""
1069 If .iVarType = V_OBJECT Then
1070 If IsNull(pvValue) Then
1071 .iVarType = V_NOTHING
1073 Set oValue = pvValue
1074 ' Try UNO type with usual ImplementationName property
1075 .sObjectType = oValue.getImplementationName()
1076 If .sObjectType =
"" Then
1077 ' Try UNO type with alternative CoreReflection trick
1078 Set oReflection = SF_Utils._GetUNOService(
"CoreReflection
")
1079 vClass = oReflection.getType(oValue)
1080 If vClass.TypeClass
>= com.sun.star.uno.TypeClass.STRUCT Then
1081 .sObjectType = vClass.Name
1087 ' Identify Basic objects
1088 If .sObjectType = cstBasicClass Then
1090 ' Try if the Basic object has an ObjectType property
1091 .sObjectType = oValue.ObjectType
1092 .sServiceName = oValue.ServiceName
1094 ' Derive the return value from the object type
1096 Case Len(.sObjectType) =
0 ' Do nothing (return V_OBJECT)
1097 Case .sObjectType = cstBasicClass : .iVarType = V_BASICOBJECT
1098 Case bUno : .iVarType = V_UNOOBJECT
1099 Case Else : .iVarType = V_SFOBJECT
1106 Set _VarTypeObj = oObjDesc
1108 End Function
' ScriptForge.SF_Utils._VarTypeObj
1110 REM ================================================= END OF SCRIPTFORGE.SF_UTILS